pdf_viewer.js 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102
  1. /* Copyright 2014 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. /* jshint globalstrict: false */
  16. /* umdutils ignore */
  17. (function (root, factory) {
  18. 'use strict';
  19. if (typeof define === 'function' && define.amd) {
  20. define('pdfjs-dist/web/pdf_viewer', ['exports', 'pdfjs-dist/build/pdf'],
  21. factory);
  22. } else if (typeof exports !== 'undefined') {
  23. factory(exports, require('../build/pdf.js'));
  24. } else {
  25. factory((root.pdfjsDistWebPDFViewer = {}), root.pdfjsDistBuildPdf);
  26. }
  27. }(this, function (exports, pdfjsLib) {
  28. 'use strict';
  29. var pdfViewerLibs = {
  30. pdfjsWebPDFJS: pdfjsLib
  31. };
  32. (function () {
  33. (function (root, factory) {
  34. {
  35. factory((root.pdfjsWebPDFRenderingQueue = {}));
  36. }
  37. }(this, function (exports) {
  38. var CLEANUP_TIMEOUT = 30000;
  39. var RenderingStates = {
  40. INITIAL: 0,
  41. RUNNING: 1,
  42. PAUSED: 2,
  43. FINISHED: 3
  44. };
  45. /**
  46. * Controls rendering of the views for pages and thumbnails.
  47. * @class
  48. */
  49. var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
  50. /**
  51. * @constructs
  52. */
  53. function PDFRenderingQueue() {
  54. this.pdfViewer = null;
  55. this.pdfThumbnailViewer = null;
  56. this.onIdle = null;
  57. this.highestPriorityPage = null;
  58. this.idleTimeout = null;
  59. this.printing = false;
  60. this.isThumbnailViewEnabled = false;
  61. }
  62. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
  63. /**
  64. * @param {PDFViewer} pdfViewer
  65. */
  66. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  67. this.pdfViewer = pdfViewer;
  68. },
  69. /**
  70. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  71. */
  72. setThumbnailViewer:
  73. function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  74. this.pdfThumbnailViewer = pdfThumbnailViewer;
  75. },
  76. /**
  77. * @param {IRenderableView} view
  78. * @returns {boolean}
  79. */
  80. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  81. return this.highestPriorityPage === view.renderingId;
  82. },
  83. renderHighestPriority: function
  84. PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  85. if (this.idleTimeout) {
  86. clearTimeout(this.idleTimeout);
  87. this.idleTimeout = null;
  88. }
  89. // Pages have a higher priority than thumbnails, so check them first.
  90. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  91. return;
  92. }
  93. // No pages needed rendering so check thumbnails.
  94. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  95. if (this.pdfThumbnailViewer.forceRendering()) {
  96. return;
  97. }
  98. }
  99. if (this.printing) {
  100. // If printing is currently ongoing do not reschedule cleanup.
  101. return;
  102. }
  103. if (this.onIdle) {
  104. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  105. }
  106. },
  107. getHighestPriority: function
  108. PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  109. // The state has changed figure out which page has the highest priority to
  110. // render next (if any).
  111. // Priority:
  112. // 1 visible pages
  113. // 2 if last scrolled down page after the visible pages
  114. // 2 if last scrolled up page before the visible pages
  115. var visibleViews = visible.views;
  116. var numVisible = visibleViews.length;
  117. if (numVisible === 0) {
  118. return false;
  119. }
  120. for (var i = 0; i < numVisible; ++i) {
  121. var view = visibleViews[i].view;
  122. if (!this.isViewFinished(view)) {
  123. return view;
  124. }
  125. }
  126. // All the visible views have rendered, try to render next/previous pages.
  127. if (scrolledDown) {
  128. var nextPageIndex = visible.last.id;
  129. // ID's start at 1 so no need to add 1.
  130. if (views[nextPageIndex] &&
  131. !this.isViewFinished(views[nextPageIndex])) {
  132. return views[nextPageIndex];
  133. }
  134. } else {
  135. var previousPageIndex = visible.first.id - 2;
  136. if (views[previousPageIndex] &&
  137. !this.isViewFinished(views[previousPageIndex])) {
  138. return views[previousPageIndex];
  139. }
  140. }
  141. // Everything that needs to be rendered has been.
  142. return null;
  143. },
  144. /**
  145. * @param {IRenderableView} view
  146. * @returns {boolean}
  147. */
  148. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  149. return view.renderingState === RenderingStates.FINISHED;
  150. },
  151. /**
  152. * Render a page or thumbnail view. This calls the appropriate function
  153. * based on the views state. If the view is already rendered it will return
  154. * false.
  155. * @param {IRenderableView} view
  156. */
  157. renderView: function PDFRenderingQueue_renderView(view) {
  158. var state = view.renderingState;
  159. switch (state) {
  160. case RenderingStates.FINISHED:
  161. return false;
  162. case RenderingStates.PAUSED:
  163. this.highestPriorityPage = view.renderingId;
  164. view.resume();
  165. break;
  166. case RenderingStates.RUNNING:
  167. this.highestPriorityPage = view.renderingId;
  168. break;
  169. case RenderingStates.INITIAL:
  170. this.highestPriorityPage = view.renderingId;
  171. var continueRendering = function () {
  172. this.renderHighestPriority();
  173. }.bind(this);
  174. view.draw().then(continueRendering, continueRendering);
  175. break;
  176. }
  177. return true;
  178. },
  179. };
  180. return PDFRenderingQueue;
  181. })();
  182. exports.RenderingStates = RenderingStates;
  183. exports.PDFRenderingQueue = PDFRenderingQueue;
  184. }));
  185. (function (root, factory) {
  186. {
  187. factory((root.pdfjsWebDownloadManager = {}), root.pdfjsWebPDFJS);
  188. }
  189. }(this, function (exports, pdfjsLib) {
  190. function download(blobUrl, filename) {
  191. var a = document.createElement('a');
  192. if (a.click) {
  193. // Use a.click() if available. Otherwise, Chrome might show
  194. // "Unsafe JavaScript attempt to initiate a navigation change
  195. // for frame with URL" and not open the PDF at all.
  196. // Supported by (not mentioned = untested):
  197. // - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
  198. // - Chrome 19 - 26 (18- does not support a.click)
  199. // - Opera 9 - 12.15
  200. // - Internet Explorer 6 - 10
  201. // - Safari 6 (5.1- does not support a.click)
  202. a.href = blobUrl;
  203. a.target = '_parent';
  204. // Use a.download if available. This increases the likelihood that
  205. // the file is downloaded instead of opened by another PDF plugin.
  206. if ('download' in a) {
  207. a.download = filename;
  208. }
  209. // <a> must be in the document for IE and recent Firefox versions.
  210. // (otherwise .click() is ignored)
  211. (document.body || document.documentElement).appendChild(a);
  212. a.click();
  213. a.parentNode.removeChild(a);
  214. } else {
  215. if (window.top === window &&
  216. blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
  217. // If _parent == self, then opening an identical URL with different
  218. // location hash will only cause a navigation, not a download.
  219. var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
  220. blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
  221. }
  222. window.open(blobUrl, '_parent');
  223. }
  224. }
  225. function DownloadManager() {}
  226. DownloadManager.prototype = {
  227. downloadUrl: function DownloadManager_downloadUrl(url, filename) {
  228. if (!pdfjsLib.isValidUrl(url, true)) {
  229. return; // restricted/invalid URL
  230. }
  231. download(url + '#pdfjs.action=download', filename);
  232. },
  233. downloadData: function DownloadManager_downloadData(data, filename,
  234. contentType) {
  235. if (navigator.msSaveBlob) { // IE10 and above
  236. return navigator.msSaveBlob(new Blob([data], { type: contentType }),
  237. filename);
  238. }
  239. var blobUrl = pdfjsLib.createObjectURL(data, contentType,
  240. pdfjsLib.PDFJS.disableCreateObjectURL);
  241. download(blobUrl, filename);
  242. },
  243. download: function DownloadManager_download(blob, url, filename) {
  244. if (!URL) {
  245. // URL.createObjectURL is not supported
  246. this.downloadUrl(url, filename);
  247. return;
  248. }
  249. if (navigator.msSaveBlob) {
  250. // IE10 / IE11
  251. if (!navigator.msSaveBlob(blob, filename)) {
  252. this.downloadUrl(url, filename);
  253. }
  254. return;
  255. }
  256. var blobUrl = URL.createObjectURL(blob);
  257. download(blobUrl, filename);
  258. }
  259. };
  260. exports.DownloadManager = DownloadManager;
  261. }));
  262. (function (root, factory) {
  263. {
  264. factory((root.pdfjsWebUIUtils = {}), root.pdfjsWebPDFJS);
  265. }
  266. }(this, function (exports, pdfjsLib) {
  267. var CSS_UNITS = 96.0 / 72.0;
  268. var DEFAULT_SCALE_VALUE = 'auto';
  269. var DEFAULT_SCALE = 1.0;
  270. var UNKNOWN_SCALE = 0;
  271. var MAX_AUTO_SCALE = 1.25;
  272. var SCROLLBAR_PADDING = 40;
  273. var VERTICAL_PADDING = 5;
  274. var mozL10n = document.mozL10n || document.webL10n;
  275. var PDFJS = pdfjsLib.PDFJS;
  276. /**
  277. * Disables fullscreen support, and by extension Presentation Mode,
  278. * in browsers which support the fullscreen API.
  279. * @var {boolean}
  280. */
  281. PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
  282. false : PDFJS.disableFullscreen);
  283. /**
  284. * Enables CSS only zooming.
  285. * @var {boolean}
  286. */
  287. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  288. false : PDFJS.useOnlyCssZoom);
  289. /**
  290. * The maximum supported canvas size in total pixels e.g. width * height.
  291. * The default value is 4096 * 4096. Use -1 for no limit.
  292. * @var {number}
  293. */
  294. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  295. 16777216 : PDFJS.maxCanvasPixels);
  296. /**
  297. * Disables saving of the last position of the viewed PDF.
  298. * @var {boolean}
  299. */
  300. PDFJS.disableHistory = (PDFJS.disableHistory === undefined ?
  301. false : PDFJS.disableHistory);
  302. /**
  303. * Disables creation of the text layer that used for text selection and search.
  304. * @var {boolean}
  305. */
  306. PDFJS.disableTextLayer = (PDFJS.disableTextLayer === undefined ?
  307. false : PDFJS.disableTextLayer);
  308. /**
  309. * Disables maintaining the current position in the document when zooming.
  310. */
  311. PDFJS.ignoreCurrentPositionOnZoom = (PDFJS.ignoreCurrentPositionOnZoom ===
  312. undefined ? false : PDFJS.ignoreCurrentPositionOnZoom);
  313. /**
  314. * Interface locale settings.
  315. * @var {string}
  316. */
  317. PDFJS.locale = (PDFJS.locale === undefined ? navigator.language : PDFJS.locale);
  318. /**
  319. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  320. * @return {Object} The object with horizontal (sx) and vertical (sy)
  321. scales. The scaled property is set to false if scaling is
  322. not required, true otherwise.
  323. */
  324. function getOutputScale(ctx) {
  325. var devicePixelRatio = window.devicePixelRatio || 1;
  326. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  327. ctx.mozBackingStorePixelRatio ||
  328. ctx.msBackingStorePixelRatio ||
  329. ctx.oBackingStorePixelRatio ||
  330. ctx.backingStorePixelRatio || 1;
  331. var pixelRatio = devicePixelRatio / backingStoreRatio;
  332. return {
  333. sx: pixelRatio,
  334. sy: pixelRatio,
  335. scaled: pixelRatio !== 1
  336. };
  337. }
  338. /**
  339. * Scrolls specified element into view of its parent.
  340. * @param {Object} element - The element to be visible.
  341. * @param {Object} spot - An object with optional top and left properties,
  342. * specifying the offset from the top left edge.
  343. * @param {boolean} skipOverflowHiddenElements - Ignore elements that have
  344. * the CSS rule `overflow: hidden;` set. The default is false.
  345. */
  346. function scrollIntoView(element, spot, skipOverflowHiddenElements) {
  347. // Assuming offsetParent is available (it's not available when viewer is in
  348. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  349. // producing the error. See also animationStartedClosure.
  350. var parent = element.offsetParent;
  351. if (!parent) {
  352. console.error('offsetParent is not set -- cannot scroll');
  353. return;
  354. }
  355. var checkOverflow = skipOverflowHiddenElements || false;
  356. var offsetY = element.offsetTop + element.clientTop;
  357. var offsetX = element.offsetLeft + element.clientLeft;
  358. while (parent.clientHeight === parent.scrollHeight ||
  359. (checkOverflow && getComputedStyle(parent).overflow === 'hidden')) {
  360. if (parent.dataset._scaleY) {
  361. offsetY /= parent.dataset._scaleY;
  362. offsetX /= parent.dataset._scaleX;
  363. }
  364. offsetY += parent.offsetTop;
  365. offsetX += parent.offsetLeft;
  366. parent = parent.offsetParent;
  367. if (!parent) {
  368. return; // no need to scroll
  369. }
  370. }
  371. if (spot) {
  372. if (spot.top !== undefined) {
  373. offsetY += spot.top;
  374. }
  375. if (spot.left !== undefined) {
  376. offsetX += spot.left;
  377. parent.scrollLeft = offsetX;
  378. }
  379. }
  380. parent.scrollTop = offsetY;
  381. }
  382. /**
  383. * Helper function to start monitoring the scroll event and converting them into
  384. * PDF.js friendly one: with scroll debounce and scroll direction.
  385. */
  386. function watchScroll(viewAreaElement, callback) {
  387. var debounceScroll = function debounceScroll(evt) {
  388. if (rAF) {
  389. return;
  390. }
  391. // schedule an invocation of scroll for next animation frame.
  392. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  393. rAF = null;
  394. var currentY = viewAreaElement.scrollTop;
  395. var lastY = state.lastY;
  396. if (currentY !== lastY) {
  397. state.down = currentY > lastY;
  398. }
  399. state.lastY = currentY;
  400. callback(state);
  401. });
  402. };
  403. var state = {
  404. down: true,
  405. lastY: viewAreaElement.scrollTop,
  406. _eventHandler: debounceScroll
  407. };
  408. var rAF = null;
  409. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  410. return state;
  411. }
  412. /**
  413. * Helper function to parse query string (e.g. ?param1=value&parm2=...).
  414. */
  415. function parseQueryString(query) {
  416. var parts = query.split('&');
  417. var params = {};
  418. for (var i = 0, ii = parts.length; i < ii; ++i) {
  419. var param = parts[i].split('=');
  420. var key = param[0].toLowerCase();
  421. var value = param.length > 1 ? param[1] : null;
  422. params[decodeURIComponent(key)] = decodeURIComponent(value);
  423. }
  424. return params;
  425. }
  426. /**
  427. * Use binary search to find the index of the first item in a given array which
  428. * passes a given condition. The items are expected to be sorted in the sense
  429. * that if the condition is true for one item in the array, then it is also true
  430. * for all following items.
  431. *
  432. * @returns {Number} Index of the first array element to pass the test,
  433. * or |items.length| if no such element exists.
  434. */
  435. function binarySearchFirstItem(items, condition) {
  436. var minIndex = 0;
  437. var maxIndex = items.length - 1;
  438. if (items.length === 0 || !condition(items[maxIndex])) {
  439. return items.length;
  440. }
  441. if (condition(items[minIndex])) {
  442. return minIndex;
  443. }
  444. while (minIndex < maxIndex) {
  445. var currentIndex = (minIndex + maxIndex) >> 1;
  446. var currentItem = items[currentIndex];
  447. if (condition(currentItem)) {
  448. maxIndex = currentIndex;
  449. } else {
  450. minIndex = currentIndex + 1;
  451. }
  452. }
  453. return minIndex; /* === maxIndex */
  454. }
  455. /**
  456. * Approximates float number as a fraction using Farey sequence (max order
  457. * of 8).
  458. * @param {number} x - Positive float number.
  459. * @returns {Array} Estimated fraction: the first array item is a numerator,
  460. * the second one is a denominator.
  461. */
  462. function approximateFraction(x) {
  463. // Fast paths for int numbers or their inversions.
  464. if (Math.floor(x) === x) {
  465. return [x, 1];
  466. }
  467. var xinv = 1 / x;
  468. var limit = 8;
  469. if (xinv > limit) {
  470. return [1, limit];
  471. } else if (Math.floor(xinv) === xinv) {
  472. return [1, xinv];
  473. }
  474. var x_ = x > 1 ? xinv : x;
  475. // a/b and c/d are neighbours in Farey sequence.
  476. var a = 0, b = 1, c = 1, d = 1;
  477. // Limiting search to order 8.
  478. while (true) {
  479. // Generating next term in sequence (order of q).
  480. var p = a + c, q = b + d;
  481. if (q > limit) {
  482. break;
  483. }
  484. if (x_ <= p / q) {
  485. c = p; d = q;
  486. } else {
  487. a = p; b = q;
  488. }
  489. }
  490. // Select closest of the neighbours to x.
  491. if (x_ - a / b < c / d - x_) {
  492. return x_ === x ? [a, b] : [b, a];
  493. } else {
  494. return x_ === x ? [c, d] : [d, c];
  495. }
  496. }
  497. function roundToDivide(x, div) {
  498. var r = x % div;
  499. return r === 0 ? x : Math.round(x - r + div);
  500. }
  501. /**
  502. * Generic helper to find out what elements are visible within a scroll pane.
  503. */
  504. function getVisibleElements(scrollEl, views, sortByVisibility) {
  505. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  506. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  507. function isElementBottomBelowViewTop(view) {
  508. var element = view.div;
  509. var elementBottom =
  510. element.offsetTop + element.clientTop + element.clientHeight;
  511. return elementBottom > top;
  512. }
  513. var visible = [], view, element;
  514. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  515. var currentWidth, viewWidth;
  516. var firstVisibleElementInd = (views.length === 0) ? 0 :
  517. binarySearchFirstItem(views, isElementBottomBelowViewTop);
  518. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  519. view = views[i];
  520. element = view.div;
  521. currentHeight = element.offsetTop + element.clientTop;
  522. viewHeight = element.clientHeight;
  523. if (currentHeight > bottom) {
  524. break;
  525. }
  526. currentWidth = element.offsetLeft + element.clientLeft;
  527. viewWidth = element.clientWidth;
  528. if (currentWidth + viewWidth < left || currentWidth > right) {
  529. continue;
  530. }
  531. hiddenHeight = Math.max(0, top - currentHeight) +
  532. Math.max(0, currentHeight + viewHeight - bottom);
  533. percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
  534. visible.push({
  535. id: view.id,
  536. x: currentWidth,
  537. y: currentHeight,
  538. view: view,
  539. percent: percentHeight
  540. });
  541. }
  542. var first = visible[0];
  543. var last = visible[visible.length - 1];
  544. if (sortByVisibility) {
  545. visible.sort(function(a, b) {
  546. var pc = a.percent - b.percent;
  547. if (Math.abs(pc) > 0.001) {
  548. return -pc;
  549. }
  550. return a.id - b.id; // ensure stability
  551. });
  552. }
  553. return {first: first, last: last, views: visible};
  554. }
  555. /**
  556. * Event handler to suppress context menu.
  557. */
  558. function noContextMenuHandler(e) {
  559. e.preventDefault();
  560. }
  561. /**
  562. * Returns the filename or guessed filename from the url (see issue 3455).
  563. * url {String} The original PDF location.
  564. * @return {String} Guessed PDF file name.
  565. */
  566. function getPDFFileNameFromURL(url) {
  567. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  568. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  569. // Pattern to get last matching NAME.pdf
  570. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  571. var splitURI = reURI.exec(url);
  572. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  573. reFilename.exec(splitURI[2]) ||
  574. reFilename.exec(splitURI[3]);
  575. if (suggestedFilename) {
  576. suggestedFilename = suggestedFilename[0];
  577. if (suggestedFilename.indexOf('%') !== -1) {
  578. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  579. try {
  580. suggestedFilename =
  581. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  582. } catch(e) { // Possible (extremely rare) errors:
  583. // URIError "Malformed URI", e.g. for "%AA.pdf"
  584. // TypeError "null has no properties", e.g. for "%2F.pdf"
  585. }
  586. }
  587. }
  588. return suggestedFilename || 'document.pdf';
  589. }
  590. /**
  591. * Simple event bus for an application. Listeners are attached using the
  592. * `on` and `off` methods. To raise an event, the `dispatch` method shall be
  593. * used.
  594. */
  595. var EventBus = (function EventBusClosure() {
  596. function EventBus() {
  597. this._listeners = Object.create(null);
  598. }
  599. EventBus.prototype = {
  600. on: function EventBus_on(eventName, listener) {
  601. var eventListeners = this._listeners[eventName];
  602. if (!eventListeners) {
  603. eventListeners = [];
  604. this._listeners[eventName] = eventListeners;
  605. }
  606. eventListeners.push(listener);
  607. },
  608. off: function EventBus_on(eventName, listener) {
  609. var eventListeners = this._listeners[eventName];
  610. var i;
  611. if (!eventListeners || ((i = eventListeners.indexOf(listener)) < 0)) {
  612. return;
  613. }
  614. eventListeners.splice(i, 1);
  615. },
  616. dispatch: function EventBus_dispath(eventName) {
  617. var eventListeners = this._listeners[eventName];
  618. if (!eventListeners || eventListeners.length === 0) {
  619. return;
  620. }
  621. // Passing all arguments after the eventName to the listeners.
  622. var args = Array.prototype.slice.call(arguments, 1);
  623. // Making copy of the listeners array in case if it will be modified
  624. // during dispatch.
  625. eventListeners.slice(0).forEach(function (listener) {
  626. listener.apply(null, args);
  627. });
  628. }
  629. };
  630. return EventBus;
  631. })();
  632. var ProgressBar = (function ProgressBarClosure() {
  633. function clamp(v, min, max) {
  634. return Math.min(Math.max(v, min), max);
  635. }
  636. function ProgressBar(id, opts) {
  637. this.visible = true;
  638. // Fetch the sub-elements for later.
  639. this.div = document.querySelector(id + ' .progress');
  640. // Get the loading bar element, so it can be resized to fit the viewer.
  641. this.bar = this.div.parentNode;
  642. // Get options, with sensible defaults.
  643. this.height = opts.height || 100;
  644. this.width = opts.width || 100;
  645. this.units = opts.units || '%';
  646. // Initialize heights.
  647. this.div.style.height = this.height + this.units;
  648. this.percent = 0;
  649. }
  650. ProgressBar.prototype = {
  651. updateBar: function ProgressBar_updateBar() {
  652. if (this._indeterminate) {
  653. this.div.classList.add('indeterminate');
  654. this.div.style.width = this.width + this.units;
  655. return;
  656. }
  657. this.div.classList.remove('indeterminate');
  658. var progressSize = this.width * this._percent / 100;
  659. this.div.style.width = progressSize + this.units;
  660. },
  661. get percent() {
  662. return this._percent;
  663. },
  664. set percent(val) {
  665. this._indeterminate = isNaN(val);
  666. this._percent = clamp(val, 0, 100);
  667. this.updateBar();
  668. },
  669. setWidth: function ProgressBar_setWidth(viewer) {
  670. if (viewer) {
  671. var container = viewer.parentNode;
  672. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  673. if (scrollbarWidth > 0) {
  674. this.bar.setAttribute('style', 'width: calc(100% - ' +
  675. scrollbarWidth + 'px);');
  676. }
  677. }
  678. },
  679. hide: function ProgressBar_hide() {
  680. if (!this.visible) {
  681. return;
  682. }
  683. this.visible = false;
  684. this.bar.classList.add('hidden');
  685. document.body.classList.remove('loadingInProgress');
  686. },
  687. show: function ProgressBar_show() {
  688. if (this.visible) {
  689. return;
  690. }
  691. this.visible = true;
  692. document.body.classList.add('loadingInProgress');
  693. this.bar.classList.remove('hidden');
  694. }
  695. };
  696. return ProgressBar;
  697. })();
  698. exports.CSS_UNITS = CSS_UNITS;
  699. exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
  700. exports.DEFAULT_SCALE = DEFAULT_SCALE;
  701. exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
  702. exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
  703. exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
  704. exports.VERTICAL_PADDING = VERTICAL_PADDING;
  705. exports.mozL10n = mozL10n;
  706. exports.EventBus = EventBus;
  707. exports.ProgressBar = ProgressBar;
  708. exports.getPDFFileNameFromURL = getPDFFileNameFromURL;
  709. exports.noContextMenuHandler = noContextMenuHandler;
  710. exports.parseQueryString = parseQueryString;
  711. exports.getVisibleElements = getVisibleElements;
  712. exports.roundToDivide = roundToDivide;
  713. exports.approximateFraction = approximateFraction;
  714. exports.getOutputScale = getOutputScale;
  715. exports.scrollIntoView = scrollIntoView;
  716. exports.watchScroll = watchScroll;
  717. exports.binarySearchFirstItem = binarySearchFirstItem;
  718. }));
  719. (function (root, factory) {
  720. {
  721. factory((root.pdfjsWebDOMEvents = {}), root.pdfjsWebUIUtils);
  722. }
  723. }(this, function (exports, uiUtils) {
  724. var EventBus = uiUtils.EventBus;
  725. // Attaching to the application event bus to dispatch events to the DOM for
  726. // backwards viewer API compatibility.
  727. function attachDOMEventsToEventBus(eventBus) {
  728. eventBus.on('documentload', function () {
  729. var event = document.createEvent('CustomEvent');
  730. event.initCustomEvent('documentload', true, true, {});
  731. window.dispatchEvent(event);
  732. });
  733. eventBus.on('pagerendered', function (e) {
  734. var event = document.createEvent('CustomEvent');
  735. event.initCustomEvent('pagerendered', true, true, {
  736. pageNumber: e.pageNumber,
  737. cssTransform: e.cssTransform,
  738. });
  739. e.source.div.dispatchEvent(event);
  740. });
  741. eventBus.on('textlayerrendered', function (e) {
  742. var event = document.createEvent('CustomEvent');
  743. event.initCustomEvent('textlayerrendered', true, true, {
  744. pageNumber: e.pageNumber
  745. });
  746. e.source.textLayerDiv.dispatchEvent(event);
  747. });
  748. eventBus.on('pagechange', function (e) {
  749. var event = document.createEvent('UIEvents');
  750. event.initUIEvent('pagechange', true, true, window, 0);
  751. event.pageNumber = e.pageNumber;
  752. event.previousPageNumber = e.previousPageNumber;
  753. e.source.container.dispatchEvent(event);
  754. });
  755. eventBus.on('pagesinit', function (e) {
  756. var event = document.createEvent('CustomEvent');
  757. event.initCustomEvent('pagesinit', true, true, null);
  758. e.source.container.dispatchEvent(event);
  759. });
  760. eventBus.on('pagesloaded', function (e) {
  761. var event = document.createEvent('CustomEvent');
  762. event.initCustomEvent('pagesloaded', true, true, {
  763. pagesCount: e.pagesCount
  764. });
  765. e.source.container.dispatchEvent(event);
  766. });
  767. eventBus.on('scalechange', function (e) {
  768. var event = document.createEvent('UIEvents');
  769. event.initUIEvent('scalechange', true, true, window, 0);
  770. event.scale = e.scale;
  771. event.presetValue = e.presetValue;
  772. e.source.container.dispatchEvent(event);
  773. });
  774. eventBus.on('updateviewarea', function (e) {
  775. var event = document.createEvent('UIEvents');
  776. event.initUIEvent('updateviewarea', true, true, window, 0);
  777. event.location = e.location;
  778. e.source.container.dispatchEvent(event);
  779. });
  780. eventBus.on('find', function (e) {
  781. if (e.source === window) {
  782. return; // event comes from FirefoxCom, no need to replicate
  783. }
  784. var event = document.createEvent('CustomEvent');
  785. event.initCustomEvent('find' + e.type, true, true, {
  786. query: e.query,
  787. phraseSearch: e.phraseSearch,
  788. caseSensitive: e.caseSensitive,
  789. highlightAll: e.highlightAll,
  790. findPrevious: e.findPrevious
  791. });
  792. window.dispatchEvent(event);
  793. });
  794. eventBus.on('attachmentsloaded', function (e) {
  795. var event = document.createEvent('CustomEvent');
  796. event.initCustomEvent('attachmentsloaded', true, true, {
  797. attachmentsCount: e.attachmentsCount
  798. });
  799. e.source.container.dispatchEvent(event);
  800. });
  801. eventBus.on('sidebarviewchanged', function (e) {
  802. var event = document.createEvent('CustomEvent');
  803. event.initCustomEvent('sidebarviewchanged', true, true, {
  804. view: e.view,
  805. });
  806. e.source.outerContainer.dispatchEvent(event);
  807. });
  808. eventBus.on('pagemode', function (e) {
  809. var event = document.createEvent('CustomEvent');
  810. event.initCustomEvent('pagemode', true, true, {
  811. mode: e.mode,
  812. });
  813. e.source.pdfViewer.container.dispatchEvent(event);
  814. });
  815. eventBus.on('namedaction', function (e) {
  816. var event = document.createEvent('CustomEvent');
  817. event.initCustomEvent('namedaction', true, true, {
  818. action: e.action
  819. });
  820. e.source.pdfViewer.container.dispatchEvent(event);
  821. });
  822. eventBus.on('presentationmodechanged', function (e) {
  823. var event = document.createEvent('CustomEvent');
  824. event.initCustomEvent('presentationmodechanged', true, true, {
  825. active: e.active,
  826. switchInProgress: e.switchInProgress
  827. });
  828. window.dispatchEvent(event);
  829. });
  830. eventBus.on('outlineloaded', function (e) {
  831. var event = document.createEvent('CustomEvent');
  832. event.initCustomEvent('outlineloaded', true, true, {
  833. outlineCount: e.outlineCount
  834. });
  835. e.source.container.dispatchEvent(event);
  836. });
  837. }
  838. var globalEventBus = null;
  839. function getGlobalEventBus() {
  840. if (globalEventBus) {
  841. return globalEventBus;
  842. }
  843. globalEventBus = new EventBus();
  844. attachDOMEventsToEventBus(globalEventBus);
  845. return globalEventBus;
  846. }
  847. exports.attachDOMEventsToEventBus = attachDOMEventsToEventBus;
  848. exports.getGlobalEventBus = getGlobalEventBus;
  849. }));
  850. (function (root, factory) {
  851. {
  852. factory((root.pdfjsWebPDFFindController = {}), root.pdfjsWebUIUtils);
  853. }
  854. }(this, function (exports, uiUtils) {
  855. var scrollIntoView = uiUtils.scrollIntoView;
  856. var FindStates = {
  857. FIND_FOUND: 0,
  858. FIND_NOTFOUND: 1,
  859. FIND_WRAPPED: 2,
  860. FIND_PENDING: 3
  861. };
  862. var FIND_SCROLL_OFFSET_TOP = -50;
  863. var FIND_SCROLL_OFFSET_LEFT = -400;
  864. var CHARACTERS_TO_NORMALIZE = {
  865. '\u2018': '\'', // Left single quotation mark
  866. '\u2019': '\'', // Right single quotation mark
  867. '\u201A': '\'', // Single low-9 quotation mark
  868. '\u201B': '\'', // Single high-reversed-9 quotation mark
  869. '\u201C': '"', // Left double quotation mark
  870. '\u201D': '"', // Right double quotation mark
  871. '\u201E': '"', // Double low-9 quotation mark
  872. '\u201F': '"', // Double high-reversed-9 quotation mark
  873. '\u00BC': '1/4', // Vulgar fraction one quarter
  874. '\u00BD': '1/2', // Vulgar fraction one half
  875. '\u00BE': '3/4', // Vulgar fraction three quarters
  876. };
  877. /**
  878. * Provides "search" or "find" functionality for the PDF.
  879. * This object actually performs the search for a given string.
  880. */
  881. var PDFFindController = (function PDFFindControllerClosure() {
  882. function PDFFindController(options) {
  883. this.pdfViewer = options.pdfViewer || null;
  884. this.onUpdateResultsCount = null;
  885. this.onUpdateState = null;
  886. this.reset();
  887. // Compile the regular expression for text normalization once.
  888. var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join('');
  889. this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
  890. }
  891. PDFFindController.prototype = {
  892. reset: function PDFFindController_reset() {
  893. this.startedTextExtraction = false;
  894. this.extractTextPromises = [];
  895. this.pendingFindMatches = Object.create(null);
  896. this.active = false; // If active, find results will be highlighted.
  897. this.pageContents = []; // Stores the text for each page.
  898. this.pageMatches = [];
  899. this.pageMatchesLength = null;
  900. this.matchCount = 0;
  901. this.selected = { // Currently selected match.
  902. pageIdx: -1,
  903. matchIdx: -1
  904. };
  905. this.offset = { // Where the find algorithm currently is in the document.
  906. pageIdx: null,
  907. matchIdx: null
  908. };
  909. this.pagesToSearch = null;
  910. this.resumePageIdx = null;
  911. this.state = null;
  912. this.dirtyMatch = false;
  913. this.findTimeout = null;
  914. this.firstPagePromise = new Promise(function (resolve) {
  915. this.resolveFirstPage = resolve;
  916. }.bind(this));
  917. },
  918. normalize: function PDFFindController_normalize(text) {
  919. return text.replace(this.normalizationRegex, function (ch) {
  920. return CHARACTERS_TO_NORMALIZE[ch];
  921. });
  922. },
  923. // Helper for multiple search - fills matchesWithLength array
  924. // and takes into account cases when one search term
  925. // include another search term (for example, "tamed tame" or "this is").
  926. // Looking for intersecting terms in the 'matches' and
  927. // leave elements with a longer match-length.
  928. _prepareMatches: function PDFFindController_prepareMatches(
  929. matchesWithLength, matches, matchesLength) {
  930. function isSubTerm(matchesWithLength, currentIndex) {
  931. var currentElem, prevElem, nextElem;
  932. currentElem = matchesWithLength[currentIndex];
  933. nextElem = matchesWithLength[currentIndex + 1];
  934. // checking for cases like "TAMEd TAME"
  935. if (currentIndex < matchesWithLength.length - 1 &&
  936. currentElem.match === nextElem.match) {
  937. currentElem.skipped = true;
  938. return true;
  939. }
  940. // checking for cases like "thIS IS"
  941. for (var i = currentIndex - 1; i >= 0; i--) {
  942. prevElem = matchesWithLength[i];
  943. if (prevElem.skipped) {
  944. continue;
  945. }
  946. if (prevElem.match + prevElem.matchLength < currentElem.match) {
  947. break;
  948. }
  949. if (prevElem.match + prevElem.matchLength >=
  950. currentElem.match + currentElem.matchLength) {
  951. currentElem.skipped = true;
  952. return true;
  953. }
  954. }
  955. return false;
  956. }
  957. var i, len;
  958. // Sorting array of objects { match: <match>, matchLength: <matchLength> }
  959. // in increasing index first and then the lengths.
  960. matchesWithLength.sort(function(a, b) {
  961. return a.match === b.match ?
  962. a.matchLength - b.matchLength : a.match - b.match;
  963. });
  964. for (i = 0, len = matchesWithLength.length; i < len; i++) {
  965. if (isSubTerm(matchesWithLength, i)) {
  966. continue;
  967. }
  968. matches.push(matchesWithLength[i].match);
  969. matchesLength.push(matchesWithLength[i].matchLength);
  970. }
  971. },
  972. calcFindPhraseMatch: function PDFFindController_calcFindPhraseMatch(
  973. query, pageIndex, pageContent) {
  974. var matches = [];
  975. var queryLen = query.length;
  976. var matchIdx = -queryLen;
  977. while (true) {
  978. matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
  979. if (matchIdx === -1) {
  980. break;
  981. }
  982. matches.push(matchIdx);
  983. }
  984. this.pageMatches[pageIndex] = matches;
  985. },
  986. calcFindWordMatch: function PDFFindController_calcFindWordMatch(
  987. query, pageIndex, pageContent) {
  988. var matchesWithLength = [];
  989. // Divide the query into pieces and search for text on each piece.
  990. var queryArray = query.match(/\S+/g);
  991. var subquery, subqueryLen, matchIdx;
  992. for (var i = 0, len = queryArray.length; i < len; i++) {
  993. subquery = queryArray[i];
  994. subqueryLen = subquery.length;
  995. matchIdx = -subqueryLen;
  996. while (true) {
  997. matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen);
  998. if (matchIdx === -1) {
  999. break;
  1000. }
  1001. // Other searches do not, so we store the length.
  1002. matchesWithLength.push({
  1003. match: matchIdx,
  1004. matchLength: subqueryLen,
  1005. skipped: false
  1006. });
  1007. }
  1008. }
  1009. // Prepare arrays for store the matches.
  1010. if (!this.pageMatchesLength) {
  1011. this.pageMatchesLength = [];
  1012. }
  1013. this.pageMatchesLength[pageIndex] = [];
  1014. this.pageMatches[pageIndex] = [];
  1015. // Sort matchesWithLength, clean up intersecting terms
  1016. // and put the result into the two arrays.
  1017. this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex],
  1018. this.pageMatchesLength[pageIndex]);
  1019. },
  1020. calcFindMatch: function PDFFindController_calcFindMatch(pageIndex) {
  1021. var pageContent = this.normalize(this.pageContents[pageIndex]);
  1022. var query = this.normalize(this.state.query);
  1023. var caseSensitive = this.state.caseSensitive;
  1024. var phraseSearch = this.state.phraseSearch;
  1025. var queryLen = query.length;
  1026. if (queryLen === 0) {
  1027. // Do nothing: the matches should be wiped out already.
  1028. return;
  1029. }
  1030. if (!caseSensitive) {
  1031. pageContent = pageContent.toLowerCase();
  1032. query = query.toLowerCase();
  1033. }
  1034. if (phraseSearch) {
  1035. this.calcFindPhraseMatch(query, pageIndex, pageContent);
  1036. } else {
  1037. this.calcFindWordMatch(query, pageIndex, pageContent);
  1038. }
  1039. this.updatePage(pageIndex);
  1040. if (this.resumePageIdx === pageIndex) {
  1041. this.resumePageIdx = null;
  1042. this.nextPageMatch();
  1043. }
  1044. // Update the matches count
  1045. if (this.pageMatches[pageIndex].length > 0) {
  1046. this.matchCount += this.pageMatches[pageIndex].length;
  1047. this.updateUIResultsCount();
  1048. }
  1049. },
  1050. extractText: function PDFFindController_extractText() {
  1051. if (this.startedTextExtraction) {
  1052. return;
  1053. }
  1054. this.startedTextExtraction = true;
  1055. this.pageContents = [];
  1056. var extractTextPromisesResolves = [];
  1057. var numPages = this.pdfViewer.pagesCount;
  1058. for (var i = 0; i < numPages; i++) {
  1059. this.extractTextPromises.push(new Promise(function (resolve) {
  1060. extractTextPromisesResolves.push(resolve);
  1061. }));
  1062. }
  1063. var self = this;
  1064. function extractPageText(pageIndex) {
  1065. self.pdfViewer.getPageTextContent(pageIndex).then(
  1066. function textContentResolved(textContent) {
  1067. var textItems = textContent.items;
  1068. var str = [];
  1069. for (var i = 0, len = textItems.length; i < len; i++) {
  1070. str.push(textItems[i].str);
  1071. }
  1072. // Store the pageContent as a string.
  1073. self.pageContents.push(str.join(''));
  1074. extractTextPromisesResolves[pageIndex](pageIndex);
  1075. if ((pageIndex + 1) < self.pdfViewer.pagesCount) {
  1076. extractPageText(pageIndex + 1);
  1077. }
  1078. }
  1079. );
  1080. }
  1081. extractPageText(0);
  1082. },
  1083. executeCommand: function PDFFindController_executeCommand(cmd, state) {
  1084. if (this.state === null || cmd !== 'findagain') {
  1085. this.dirtyMatch = true;
  1086. }
  1087. this.state = state;
  1088. this.updateUIState(FindStates.FIND_PENDING);
  1089. this.firstPagePromise.then(function() {
  1090. this.extractText();
  1091. clearTimeout(this.findTimeout);
  1092. if (cmd === 'find') {
  1093. // Only trigger the find action after 250ms of silence.
  1094. this.findTimeout = setTimeout(this.nextMatch.bind(this), 250);
  1095. } else {
  1096. this.nextMatch();
  1097. }
  1098. }.bind(this));
  1099. },
  1100. updatePage: function PDFFindController_updatePage(index) {
  1101. if (this.selected.pageIdx === index) {
  1102. // If the page is selected, scroll the page into view, which triggers
  1103. // rendering the page, which adds the textLayer. Once the textLayer is
  1104. // build, it will scroll onto the selected match.
  1105. this.pdfViewer.scrollPageIntoView(index + 1);
  1106. }
  1107. var page = this.pdfViewer.getPageView(index);
  1108. if (page.textLayer) {
  1109. page.textLayer.updateMatches();
  1110. }
  1111. },
  1112. nextMatch: function PDFFindController_nextMatch() {
  1113. var previous = this.state.findPrevious;
  1114. var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
  1115. var numPages = this.pdfViewer.pagesCount;
  1116. this.active = true;
  1117. if (this.dirtyMatch) {
  1118. // Need to recalculate the matches, reset everything.
  1119. this.dirtyMatch = false;
  1120. this.selected.pageIdx = this.selected.matchIdx = -1;
  1121. this.offset.pageIdx = currentPageIndex;
  1122. this.offset.matchIdx = null;
  1123. this.hadMatch = false;
  1124. this.resumePageIdx = null;
  1125. this.pageMatches = [];
  1126. this.matchCount = 0;
  1127. this.pageMatchesLength = null;
  1128. var self = this;
  1129. for (var i = 0; i < numPages; i++) {
  1130. // Wipe out any previous highlighted matches.
  1131. this.updatePage(i);
  1132. // As soon as the text is extracted start finding the matches.
  1133. if (!(i in this.pendingFindMatches)) {
  1134. this.pendingFindMatches[i] = true;
  1135. this.extractTextPromises[i].then(function(pageIdx) {
  1136. delete self.pendingFindMatches[pageIdx];
  1137. self.calcFindMatch(pageIdx);
  1138. });
  1139. }
  1140. }
  1141. }
  1142. // If there's no query there's no point in searching.
  1143. if (this.state.query === '') {
  1144. this.updateUIState(FindStates.FIND_FOUND);
  1145. return;
  1146. }
  1147. // If we're waiting on a page, we return since we can't do anything else.
  1148. if (this.resumePageIdx) {
  1149. return;
  1150. }
  1151. var offset = this.offset;
  1152. // Keep track of how many pages we should maximally iterate through.
  1153. this.pagesToSearch = numPages;
  1154. // If there's already a matchIdx that means we are iterating through a
  1155. // page's matches.
  1156. if (offset.matchIdx !== null) {
  1157. var numPageMatches = this.pageMatches[offset.pageIdx].length;
  1158. if ((!previous && offset.matchIdx + 1 < numPageMatches) ||
  1159. (previous && offset.matchIdx > 0)) {
  1160. // The simple case; we just have advance the matchIdx to select
  1161. // the next match on the page.
  1162. this.hadMatch = true;
  1163. offset.matchIdx = (previous ? offset.matchIdx - 1 :
  1164. offset.matchIdx + 1);
  1165. this.updateMatch(true);
  1166. return;
  1167. }
  1168. // We went beyond the current page's matches, so we advance to
  1169. // the next page.
  1170. this.advanceOffsetPage(previous);
  1171. }
  1172. // Start searching through the page.
  1173. this.nextPageMatch();
  1174. },
  1175. matchesReady: function PDFFindController_matchesReady(matches) {
  1176. var offset = this.offset;
  1177. var numMatches = matches.length;
  1178. var previous = this.state.findPrevious;
  1179. if (numMatches) {
  1180. // There were matches for the page, so initialize the matchIdx.
  1181. this.hadMatch = true;
  1182. offset.matchIdx = (previous ? numMatches - 1 : 0);
  1183. this.updateMatch(true);
  1184. return true;
  1185. } else {
  1186. // No matches, so attempt to search the next page.
  1187. this.advanceOffsetPage(previous);
  1188. if (offset.wrapped) {
  1189. offset.matchIdx = null;
  1190. if (this.pagesToSearch < 0) {
  1191. // No point in wrapping again, there were no matches.
  1192. this.updateMatch(false);
  1193. // while matches were not found, searching for a page
  1194. // with matches should nevertheless halt.
  1195. return true;
  1196. }
  1197. }
  1198. // Matches were not found (and searching is not done).
  1199. return false;
  1200. }
  1201. },
  1202. /**
  1203. * The method is called back from the text layer when match presentation
  1204. * is updated.
  1205. * @param {number} pageIndex - page index.
  1206. * @param {number} index - match index.
  1207. * @param {Array} elements - text layer div elements array.
  1208. * @param {number} beginIdx - start index of the div array for the match.
  1209. */
  1210. updateMatchPosition: function PDFFindController_updateMatchPosition(
  1211. pageIndex, index, elements, beginIdx) {
  1212. if (this.selected.matchIdx === index &&
  1213. this.selected.pageIdx === pageIndex) {
  1214. var spot = {
  1215. top: FIND_SCROLL_OFFSET_TOP,
  1216. left: FIND_SCROLL_OFFSET_LEFT
  1217. };
  1218. scrollIntoView(elements[beginIdx], spot,
  1219. /* skipOverflowHiddenElements = */ true);
  1220. }
  1221. },
  1222. nextPageMatch: function PDFFindController_nextPageMatch() {
  1223. if (this.resumePageIdx !== null) {
  1224. console.error('There can only be one pending page.');
  1225. }
  1226. do {
  1227. var pageIdx = this.offset.pageIdx;
  1228. var matches = this.pageMatches[pageIdx];
  1229. if (!matches) {
  1230. // The matches don't exist yet for processing by "matchesReady",
  1231. // so set a resume point for when they do exist.
  1232. this.resumePageIdx = pageIdx;
  1233. break;
  1234. }
  1235. } while (!this.matchesReady(matches));
  1236. },
  1237. advanceOffsetPage: function PDFFindController_advanceOffsetPage(previous) {
  1238. var offset = this.offset;
  1239. var numPages = this.extractTextPromises.length;
  1240. offset.pageIdx = (previous ? offset.pageIdx - 1 : offset.pageIdx + 1);
  1241. offset.matchIdx = null;
  1242. this.pagesToSearch--;
  1243. if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
  1244. offset.pageIdx = (previous ? numPages - 1 : 0);
  1245. offset.wrapped = true;
  1246. }
  1247. },
  1248. updateMatch: function PDFFindController_updateMatch(found) {
  1249. var state = FindStates.FIND_NOTFOUND;
  1250. var wrapped = this.offset.wrapped;
  1251. this.offset.wrapped = false;
  1252. if (found) {
  1253. var previousPage = this.selected.pageIdx;
  1254. this.selected.pageIdx = this.offset.pageIdx;
  1255. this.selected.matchIdx = this.offset.matchIdx;
  1256. state = (wrapped ? FindStates.FIND_WRAPPED : FindStates.FIND_FOUND);
  1257. // Update the currently selected page to wipe out any selected matches.
  1258. if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
  1259. this.updatePage(previousPage);
  1260. }
  1261. }
  1262. this.updateUIState(state, this.state.findPrevious);
  1263. if (this.selected.pageIdx !== -1) {
  1264. this.updatePage(this.selected.pageIdx);
  1265. }
  1266. },
  1267. updateUIResultsCount:
  1268. function PDFFindController_updateUIResultsCount() {
  1269. if (this.onUpdateResultsCount) {
  1270. this.onUpdateResultsCount(this.matchCount);
  1271. }
  1272. },
  1273. updateUIState: function PDFFindController_updateUIState(state, previous) {
  1274. if (this.onUpdateState) {
  1275. this.onUpdateState(state, previous, this.matchCount);
  1276. }
  1277. }
  1278. };
  1279. return PDFFindController;
  1280. })();
  1281. exports.FindStates = FindStates;
  1282. exports.PDFFindController = PDFFindController;
  1283. }));
  1284. (function (root, factory) {
  1285. {
  1286. factory((root.pdfjsWebPDFHistory = {}), root.pdfjsWebDOMEvents);
  1287. }
  1288. }(this, function (exports, domEvents) {
  1289. function PDFHistory(options) {
  1290. this.linkService = options.linkService;
  1291. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  1292. this.initialized = false;
  1293. this.initialDestination = null;
  1294. this.initialBookmark = null;
  1295. }
  1296. PDFHistory.prototype = {
  1297. /**
  1298. * @param {string} fingerprint
  1299. */
  1300. initialize: function pdfHistoryInitialize(fingerprint) {
  1301. this.initialized = true;
  1302. this.reInitialized = false;
  1303. this.allowHashChange = true;
  1304. this.historyUnlocked = true;
  1305. this.isViewerInPresentationMode = false;
  1306. this.previousHash = window.location.hash.substring(1);
  1307. this.currentBookmark = '';
  1308. this.currentPage = 0;
  1309. this.updatePreviousBookmark = false;
  1310. this.previousBookmark = '';
  1311. this.previousPage = 0;
  1312. this.nextHashParam = '';
  1313. this.fingerprint = fingerprint;
  1314. this.currentUid = this.uid = 0;
  1315. this.current = {};
  1316. var state = window.history.state;
  1317. if (this._isStateObjectDefined(state)) {
  1318. // This corresponds to navigating back to the document
  1319. // from another page in the browser history.
  1320. if (state.target.dest) {
  1321. this.initialDestination = state.target.dest;
  1322. } else {
  1323. this.initialBookmark = state.target.hash;
  1324. }
  1325. this.currentUid = state.uid;
  1326. this.uid = state.uid + 1;
  1327. this.current = state.target;
  1328. } else {
  1329. // This corresponds to the loading of a new document.
  1330. if (state && state.fingerprint &&
  1331. this.fingerprint !== state.fingerprint) {
  1332. // Reinitialize the browsing history when a new document
  1333. // is opened in the web viewer.
  1334. this.reInitialized = true;
  1335. }
  1336. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  1337. }
  1338. var self = this;
  1339. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  1340. if (!self.historyUnlocked) {
  1341. return;
  1342. }
  1343. if (evt.state) {
  1344. // Move back/forward in the history.
  1345. self._goTo(evt.state);
  1346. return;
  1347. }
  1348. // If the state is not set, then the user tried to navigate to a
  1349. // different hash by manually editing the URL and pressing Enter, or by
  1350. // clicking on an in-page link (e.g. the "current view" link).
  1351. // Save the current view state to the browser history.
  1352. // Note: In Firefox, history.null could also be null after an in-page
  1353. // navigation to the same URL, and without dispatching the popstate
  1354. // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
  1355. if (self.uid === 0) {
  1356. // Replace the previous state if it was not explicitly set.
  1357. var previousParams = (self.previousHash && self.currentBookmark &&
  1358. self.previousHash !== self.currentBookmark) ?
  1359. {hash: self.currentBookmark, page: self.currentPage} :
  1360. {page: 1};
  1361. replacePreviousHistoryState(previousParams, function() {
  1362. updateHistoryWithCurrentHash();
  1363. });
  1364. } else {
  1365. updateHistoryWithCurrentHash();
  1366. }
  1367. }, false);
  1368. function updateHistoryWithCurrentHash() {
  1369. self.previousHash = window.location.hash.slice(1);
  1370. self._pushToHistory({hash: self.previousHash}, false, true);
  1371. self._updatePreviousBookmark();
  1372. }
  1373. function replacePreviousHistoryState(params, callback) {
  1374. // To modify the previous history entry, the following happens:
  1375. // 1. history.back()
  1376. // 2. _pushToHistory, which calls history.replaceState( ... )
  1377. // 3. history.forward()
  1378. // Because a navigation via the history API does not immediately update
  1379. // the history state, the popstate event is used for synchronization.
  1380. self.historyUnlocked = false;
  1381. // Suppress the hashchange event to avoid side effects caused by
  1382. // navigating back and forward.
  1383. self.allowHashChange = false;
  1384. window.addEventListener('popstate', rewriteHistoryAfterBack);
  1385. history.back();
  1386. function rewriteHistoryAfterBack() {
  1387. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  1388. window.addEventListener('popstate', rewriteHistoryAfterForward);
  1389. self._pushToHistory(params, false, true);
  1390. history.forward();
  1391. }
  1392. function rewriteHistoryAfterForward() {
  1393. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  1394. self.allowHashChange = true;
  1395. self.historyUnlocked = true;
  1396. callback();
  1397. }
  1398. }
  1399. function pdfHistoryBeforeUnload() {
  1400. var previousParams = self._getPreviousParams(null, true);
  1401. if (previousParams) {
  1402. var replacePrevious = (!self.current.dest &&
  1403. self.current.hash !== self.previousHash);
  1404. self._pushToHistory(previousParams, false, replacePrevious);
  1405. self._updatePreviousBookmark();
  1406. }
  1407. // Remove the event listener when navigating away from the document,
  1408. // since 'beforeunload' prevents Firefox from caching the document.
  1409. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  1410. false);
  1411. }
  1412. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1413. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  1414. // If the entire viewer (including the PDF file) is cached in
  1415. // the browser, we need to reattach the 'beforeunload' event listener
  1416. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  1417. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1418. }, false);
  1419. self.eventBus.on('presentationmodechanged', function(e) {
  1420. self.isViewerInPresentationMode = e.active;
  1421. });
  1422. },
  1423. clearHistoryState: function pdfHistory_clearHistoryState() {
  1424. this._pushOrReplaceState(null, true);
  1425. },
  1426. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  1427. return (state && state.uid >= 0 &&
  1428. state.fingerprint && this.fingerprint === state.fingerprint &&
  1429. state.target && state.target.hash) ? true : false;
  1430. },
  1431. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  1432. replace) {
  1433. if (replace) {
  1434. window.history.replaceState(stateObj, '', document.URL);
  1435. } else {
  1436. window.history.pushState(stateObj, '', document.URL);
  1437. }
  1438. },
  1439. get isHashChangeUnlocked() {
  1440. if (!this.initialized) {
  1441. return true;
  1442. }
  1443. return this.allowHashChange;
  1444. },
  1445. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  1446. if (this.updatePreviousBookmark &&
  1447. this.currentBookmark && this.currentPage) {
  1448. this.previousBookmark = this.currentBookmark;
  1449. this.previousPage = this.currentPage;
  1450. this.updatePreviousBookmark = false;
  1451. }
  1452. },
  1453. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  1454. pageNum) {
  1455. if (this.initialized) {
  1456. this.currentBookmark = bookmark.substring(1);
  1457. this.currentPage = pageNum | 0;
  1458. this._updatePreviousBookmark();
  1459. }
  1460. },
  1461. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  1462. if (this.initialized) {
  1463. this.nextHashParam = param;
  1464. }
  1465. },
  1466. push: function pdfHistoryPush(params, isInitialBookmark) {
  1467. if (!(this.initialized && this.historyUnlocked)) {
  1468. return;
  1469. }
  1470. if (params.dest && !params.hash) {
  1471. params.hash = (this.current.hash && this.current.dest &&
  1472. this.current.dest === params.dest) ?
  1473. this.current.hash :
  1474. this.linkService.getDestinationHash(params.dest).split('#')[1];
  1475. }
  1476. if (params.page) {
  1477. params.page |= 0;
  1478. }
  1479. if (isInitialBookmark) {
  1480. var target = window.history.state.target;
  1481. if (!target) {
  1482. // Invoked when the user specifies an initial bookmark,
  1483. // thus setting initialBookmark, when the document is loaded.
  1484. this._pushToHistory(params, false);
  1485. this.previousHash = window.location.hash.substring(1);
  1486. }
  1487. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  1488. if (target) {
  1489. // If the current document is reloaded,
  1490. // avoid creating duplicate entries in the history.
  1491. this._updatePreviousBookmark();
  1492. }
  1493. return;
  1494. }
  1495. if (this.nextHashParam) {
  1496. if (this.nextHashParam === params.hash) {
  1497. this.nextHashParam = null;
  1498. this.updatePreviousBookmark = true;
  1499. return;
  1500. } else {
  1501. this.nextHashParam = null;
  1502. }
  1503. }
  1504. if (params.hash) {
  1505. if (this.current.hash) {
  1506. if (this.current.hash !== params.hash) {
  1507. this._pushToHistory(params, true);
  1508. } else {
  1509. if (!this.current.page && params.page) {
  1510. this._pushToHistory(params, false, true);
  1511. }
  1512. this.updatePreviousBookmark = true;
  1513. }
  1514. } else {
  1515. this._pushToHistory(params, true);
  1516. }
  1517. } else if (this.current.page && params.page &&
  1518. this.current.page !== params.page) {
  1519. this._pushToHistory(params, true);
  1520. }
  1521. },
  1522. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  1523. beforeUnload) {
  1524. if (!(this.currentBookmark && this.currentPage)) {
  1525. return null;
  1526. } else if (this.updatePreviousBookmark) {
  1527. this.updatePreviousBookmark = false;
  1528. }
  1529. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  1530. // Prevent the history from getting stuck in the current state,
  1531. // effectively preventing the user from going back/forward in
  1532. // the history.
  1533. //
  1534. // This happens if the current position in the document didn't change
  1535. // when the history was previously updated. The reasons for this are
  1536. // either:
  1537. // 1. The current zoom value is such that the document does not need to,
  1538. // or cannot, be scrolled to display the destination.
  1539. // 2. The previous destination is broken, and doesn't actally point to a
  1540. // position within the document.
  1541. // (This is either due to a bad PDF generator, or the user making a
  1542. // mistake when entering a destination in the hash parameters.)
  1543. return null;
  1544. }
  1545. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  1546. if (this.previousBookmark === this.currentBookmark) {
  1547. return null;
  1548. }
  1549. } else if (this.current.page || onlyCheckPage) {
  1550. if (this.previousPage === this.currentPage) {
  1551. return null;
  1552. }
  1553. } else {
  1554. return null;
  1555. }
  1556. var params = {hash: this.currentBookmark, page: this.currentPage};
  1557. if (this.isViewerInPresentationMode) {
  1558. params.hash = null;
  1559. }
  1560. return params;
  1561. },
  1562. _stateObj: function pdfHistory_stateObj(params) {
  1563. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  1564. },
  1565. _pushToHistory: function pdfHistory_pushToHistory(params,
  1566. addPrevious, overwrite) {
  1567. if (!this.initialized) {
  1568. return;
  1569. }
  1570. if (!params.hash && params.page) {
  1571. params.hash = ('page=' + params.page);
  1572. }
  1573. if (addPrevious && !overwrite) {
  1574. var previousParams = this._getPreviousParams();
  1575. if (previousParams) {
  1576. var replacePrevious = (!this.current.dest &&
  1577. this.current.hash !== this.previousHash);
  1578. this._pushToHistory(previousParams, false, replacePrevious);
  1579. }
  1580. }
  1581. this._pushOrReplaceState(this._stateObj(params),
  1582. (overwrite || this.uid === 0));
  1583. this.currentUid = this.uid++;
  1584. this.current = params;
  1585. this.updatePreviousBookmark = true;
  1586. },
  1587. _goTo: function pdfHistory_goTo(state) {
  1588. if (!(this.initialized && this.historyUnlocked &&
  1589. this._isStateObjectDefined(state))) {
  1590. return;
  1591. }
  1592. if (!this.reInitialized && state.uid < this.currentUid) {
  1593. var previousParams = this._getPreviousParams(true);
  1594. if (previousParams) {
  1595. this._pushToHistory(this.current, false);
  1596. this._pushToHistory(previousParams, false);
  1597. this.currentUid = state.uid;
  1598. window.history.back();
  1599. return;
  1600. }
  1601. }
  1602. this.historyUnlocked = false;
  1603. if (state.target.dest) {
  1604. this.linkService.navigateTo(state.target.dest);
  1605. } else {
  1606. this.linkService.setHash(state.target.hash);
  1607. }
  1608. this.currentUid = state.uid;
  1609. if (state.uid > this.uid) {
  1610. this.uid = state.uid;
  1611. }
  1612. this.current = state.target;
  1613. this.updatePreviousBookmark = true;
  1614. var currentHash = window.location.hash.substring(1);
  1615. if (this.previousHash !== currentHash) {
  1616. this.allowHashChange = false;
  1617. }
  1618. this.previousHash = currentHash;
  1619. this.historyUnlocked = true;
  1620. },
  1621. back: function pdfHistoryBack() {
  1622. this.go(-1);
  1623. },
  1624. forward: function pdfHistoryForward() {
  1625. this.go(1);
  1626. },
  1627. go: function pdfHistoryGo(direction) {
  1628. if (this.initialized && this.historyUnlocked) {
  1629. var state = window.history.state;
  1630. if (direction === -1 && state && state.uid > 0) {
  1631. window.history.back();
  1632. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  1633. window.history.forward();
  1634. }
  1635. }
  1636. }
  1637. };
  1638. exports.PDFHistory = PDFHistory;
  1639. }));
  1640. (function (root, factory) {
  1641. {
  1642. factory((root.pdfjsWebPDFLinkService = {}), root.pdfjsWebUIUtils,
  1643. root.pdfjsWebDOMEvents);
  1644. }
  1645. }(this, function (exports, uiUtils, domEvents) {
  1646. var parseQueryString = uiUtils.parseQueryString;
  1647. var PageNumberRegExp = /^\d+$/;
  1648. function isPageNumber(str) {
  1649. return PageNumberRegExp.test(str);
  1650. }
  1651. /**
  1652. * @typedef {Object} PDFLinkServiceOptions
  1653. * @property {EventBus} eventBus - The application event bus.
  1654. */
  1655. /**
  1656. * Performs navigation functions inside PDF, such as opening specified page,
  1657. * or destination.
  1658. * @class
  1659. * @implements {IPDFLinkService}
  1660. */
  1661. var PDFLinkService = (function PDFLinkServiceClosure() {
  1662. /**
  1663. * @constructs PDFLinkService
  1664. * @param {PDFLinkServiceOptions} options
  1665. */
  1666. function PDFLinkService(options) {
  1667. options = options || {};
  1668. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  1669. this.baseUrl = null;
  1670. this.pdfDocument = null;
  1671. this.pdfViewer = null;
  1672. this.pdfHistory = null;
  1673. this._pagesRefCache = null;
  1674. }
  1675. PDFLinkService.prototype = {
  1676. setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
  1677. this.baseUrl = baseUrl;
  1678. this.pdfDocument = pdfDocument;
  1679. this._pagesRefCache = Object.create(null);
  1680. },
  1681. setViewer: function PDFLinkService_setViewer(pdfViewer) {
  1682. this.pdfViewer = pdfViewer;
  1683. },
  1684. setHistory: function PDFLinkService_setHistory(pdfHistory) {
  1685. this.pdfHistory = pdfHistory;
  1686. },
  1687. /**
  1688. * @returns {number}
  1689. */
  1690. get pagesCount() {
  1691. return this.pdfDocument.numPages;
  1692. },
  1693. /**
  1694. * @returns {number}
  1695. */
  1696. get page() {
  1697. return this.pdfViewer.currentPageNumber;
  1698. },
  1699. /**
  1700. * @param {number} value
  1701. */
  1702. set page(value) {
  1703. this.pdfViewer.currentPageNumber = value;
  1704. },
  1705. /**
  1706. * @param dest - The PDF destination object.
  1707. */
  1708. navigateTo: function PDFLinkService_navigateTo(dest) {
  1709. var destString = '';
  1710. var self = this;
  1711. var goToDestination = function(destRef) {
  1712. // dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
  1713. var pageNumber = destRef instanceof Object ?
  1714. self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  1715. (destRef + 1);
  1716. if (pageNumber) {
  1717. if (pageNumber > self.pagesCount) {
  1718. pageNumber = self.pagesCount;
  1719. }
  1720. self.pdfViewer.scrollPageIntoView(pageNumber, dest);
  1721. if (self.pdfHistory) {
  1722. // Update the browsing history.
  1723. self.pdfHistory.push({
  1724. dest: dest,
  1725. hash: destString,
  1726. page: pageNumber
  1727. });
  1728. }
  1729. } else {
  1730. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  1731. var pageNum = pageIndex + 1;
  1732. var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
  1733. self._pagesRefCache[cacheKey] = pageNum;
  1734. goToDestination(destRef);
  1735. });
  1736. }
  1737. };
  1738. var destinationPromise;
  1739. if (typeof dest === 'string') {
  1740. destString = dest;
  1741. destinationPromise = this.pdfDocument.getDestination(dest);
  1742. } else {
  1743. destinationPromise = Promise.resolve(dest);
  1744. }
  1745. destinationPromise.then(function(destination) {
  1746. dest = destination;
  1747. if (!(destination instanceof Array)) {
  1748. return; // invalid destination
  1749. }
  1750. goToDestination(destination[0]);
  1751. });
  1752. },
  1753. /**
  1754. * @param dest - The PDF destination object.
  1755. * @returns {string} The hyperlink to the PDF object.
  1756. */
  1757. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  1758. if (typeof dest === 'string') {
  1759. // In practice, a named destination may contain only a number.
  1760. // If that happens, use the '#nameddest=' form to avoid the link
  1761. // redirecting to a page, instead of the correct destination.
  1762. return this.getAnchorUrl(
  1763. '#' + (isPageNumber(dest) ? 'nameddest=' : '') + escape(dest));
  1764. }
  1765. if (dest instanceof Array) {
  1766. var str = JSON.stringify(dest);
  1767. return this.getAnchorUrl('#' + escape(str));
  1768. }
  1769. return this.getAnchorUrl('');
  1770. },
  1771. /**
  1772. * Prefix the full url on anchor links to make sure that links are resolved
  1773. * relative to the current URL instead of the one defined in <base href>.
  1774. * @param {String} anchor The anchor hash, including the #.
  1775. * @returns {string} The hyperlink to the PDF object.
  1776. */
  1777. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  1778. return (this.baseUrl || '') + anchor;
  1779. },
  1780. /**
  1781. * @param {string} hash
  1782. */
  1783. setHash: function PDFLinkService_setHash(hash) {
  1784. var pageNumber, dest;
  1785. if (hash.indexOf('=') >= 0) {
  1786. var params = parseQueryString(hash);
  1787. if ('search' in params) {
  1788. this.eventBus.dispatch('findfromurlhash', {
  1789. source: this,
  1790. query: params['search'].replace(/"/g, ''),
  1791. phraseSearch: (params['phrase'] === 'true')
  1792. });
  1793. }
  1794. // borrowing syntax from "Parameters for Opening PDF Files"
  1795. if ('nameddest' in params) {
  1796. if (this.pdfHistory) {
  1797. this.pdfHistory.updateNextHashParam(params.nameddest);
  1798. }
  1799. this.navigateTo(params.nameddest);
  1800. return;
  1801. }
  1802. if ('page' in params) {
  1803. pageNumber = (params.page | 0) || 1;
  1804. }
  1805. if ('zoom' in params) {
  1806. // Build the destination array.
  1807. var zoomArgs = params.zoom.split(','); // scale,left,top
  1808. var zoomArg = zoomArgs[0];
  1809. var zoomArgNumber = parseFloat(zoomArg);
  1810. if (zoomArg.indexOf('Fit') === -1) {
  1811. // If the zoomArg is a number, it has to get divided by 100. If it's
  1812. // a string, it should stay as it is.
  1813. dest = [null, { name: 'XYZ' },
  1814. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
  1815. zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
  1816. (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
  1817. } else {
  1818. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  1819. dest = [null, { name: zoomArg }];
  1820. } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
  1821. (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  1822. dest = [null, { name: zoomArg },
  1823. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
  1824. } else if (zoomArg === 'FitR') {
  1825. if (zoomArgs.length !== 5) {
  1826. console.error('PDFLinkService_setHash: ' +
  1827. 'Not enough parameters for \'FitR\'.');
  1828. } else {
  1829. dest = [null, { name: zoomArg },
  1830. (zoomArgs[1] | 0), (zoomArgs[2] | 0),
  1831. (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
  1832. }
  1833. } else {
  1834. console.error('PDFLinkService_setHash: \'' + zoomArg +
  1835. '\' is not a valid zoom value.');
  1836. }
  1837. }
  1838. }
  1839. if (dest) {
  1840. this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
  1841. } else if (pageNumber) {
  1842. this.page = pageNumber; // simple page
  1843. }
  1844. if ('pagemode' in params) {
  1845. this.eventBus.dispatch('pagemode', {
  1846. source: this,
  1847. mode: params.pagemode
  1848. });
  1849. }
  1850. } else if (isPageNumber(hash)) { // Page number.
  1851. this.page = hash | 0;
  1852. } else { // Named (or explicit) destination.
  1853. dest = unescape(hash);
  1854. try {
  1855. dest = JSON.parse(dest);
  1856. } catch (ex) {}
  1857. if (typeof dest === 'string' || isValidExplicitDestination(dest)) {
  1858. if (this.pdfHistory) {
  1859. this.pdfHistory.updateNextHashParam(dest);
  1860. }
  1861. this.navigateTo(dest);
  1862. return;
  1863. }
  1864. console.error('PDFLinkService_setHash: \'' + unescape(hash) +
  1865. '\' is not a valid destination.');
  1866. }
  1867. },
  1868. /**
  1869. * @param {string} action
  1870. */
  1871. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  1872. // See PDF reference, table 8.45 - Named action
  1873. switch (action) {
  1874. case 'GoBack':
  1875. if (this.pdfHistory) {
  1876. this.pdfHistory.back();
  1877. }
  1878. break;
  1879. case 'GoForward':
  1880. if (this.pdfHistory) {
  1881. this.pdfHistory.forward();
  1882. }
  1883. break;
  1884. case 'NextPage':
  1885. this.page++;
  1886. break;
  1887. case 'PrevPage':
  1888. this.page--;
  1889. break;
  1890. case 'LastPage':
  1891. this.page = this.pagesCount;
  1892. break;
  1893. case 'FirstPage':
  1894. this.page = 1;
  1895. break;
  1896. default:
  1897. break; // No action according to spec
  1898. }
  1899. this.eventBus.dispatch('namedaction', {
  1900. source: this,
  1901. action: action
  1902. });
  1903. },
  1904. /**
  1905. * @param {number} pageNum - page number.
  1906. * @param {Object} pageRef - reference to the page.
  1907. */
  1908. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  1909. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  1910. this._pagesRefCache[refStr] = pageNum;
  1911. }
  1912. };
  1913. function isValidExplicitDestination(dest) {
  1914. if (!(dest instanceof Array)) {
  1915. return false;
  1916. }
  1917. var destLength = dest.length, allowNull = true;
  1918. if (destLength < 2) {
  1919. return false;
  1920. }
  1921. var page = dest[0];
  1922. if (!(typeof page === 'object' &&
  1923. typeof page.num === 'number' && (page.num | 0) === page.num &&
  1924. typeof page.gen === 'number' && (page.gen | 0) === page.gen) &&
  1925. !(typeof page === 'number' && (page | 0) === page && page >= 0)) {
  1926. return false;
  1927. }
  1928. var zoom = dest[1];
  1929. if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) {
  1930. return false;
  1931. }
  1932. switch (zoom.name) {
  1933. case 'XYZ':
  1934. if (destLength !== 5) {
  1935. return false;
  1936. }
  1937. break;
  1938. case 'Fit':
  1939. case 'FitB':
  1940. return destLength === 2;
  1941. case 'FitH':
  1942. case 'FitBH':
  1943. case 'FitV':
  1944. case 'FitBV':
  1945. if (destLength !== 3) {
  1946. return false;
  1947. }
  1948. break;
  1949. case 'FitR':
  1950. if (destLength !== 6) {
  1951. return false;
  1952. }
  1953. allowNull = false;
  1954. break;
  1955. default:
  1956. return false;
  1957. }
  1958. for (var i = 2; i < destLength; i++) {
  1959. var param = dest[i];
  1960. if (!(typeof param === 'number' || (allowNull && param === null))) {
  1961. return false;
  1962. }
  1963. }
  1964. return true;
  1965. }
  1966. return PDFLinkService;
  1967. })();
  1968. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  1969. function SimpleLinkService() {}
  1970. SimpleLinkService.prototype = {
  1971. /**
  1972. * @returns {number}
  1973. */
  1974. get page() {
  1975. return 0;
  1976. },
  1977. /**
  1978. * @param {number} value
  1979. */
  1980. set page(value) {},
  1981. /**
  1982. * @param dest - The PDF destination object.
  1983. */
  1984. navigateTo: function (dest) {},
  1985. /**
  1986. * @param dest - The PDF destination object.
  1987. * @returns {string} The hyperlink to the PDF object.
  1988. */
  1989. getDestinationHash: function (dest) {
  1990. return '#';
  1991. },
  1992. /**
  1993. * @param hash - The PDF parameters/hash.
  1994. * @returns {string} The hyperlink to the PDF object.
  1995. */
  1996. getAnchorUrl: function (hash) {
  1997. return '#';
  1998. },
  1999. /**
  2000. * @param {string} hash
  2001. */
  2002. setHash: function (hash) {},
  2003. /**
  2004. * @param {string} action
  2005. */
  2006. executeNamedAction: function (action) {},
  2007. /**
  2008. * @param {number} pageNum - page number.
  2009. * @param {Object} pageRef - reference to the page.
  2010. */
  2011. cachePageRef: function (pageNum, pageRef) {}
  2012. };
  2013. return SimpleLinkService;
  2014. })();
  2015. exports.PDFLinkService = PDFLinkService;
  2016. exports.SimpleLinkService = SimpleLinkService;
  2017. }));
  2018. (function (root, factory) {
  2019. {
  2020. factory((root.pdfjsWebPDFPageView = {}), root.pdfjsWebUIUtils,
  2021. root.pdfjsWebPDFRenderingQueue, root.pdfjsWebDOMEvents,
  2022. root.pdfjsWebPDFJS);
  2023. }
  2024. }(this, function (exports, uiUtils, pdfRenderingQueue, domEvents, pdfjsLib) {
  2025. var CSS_UNITS = uiUtils.CSS_UNITS;
  2026. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2027. var getOutputScale = uiUtils.getOutputScale;
  2028. var approximateFraction = uiUtils.approximateFraction;
  2029. var roundToDivide = uiUtils.roundToDivide;
  2030. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2031. var TEXT_LAYER_RENDER_DELAY = 200; // ms
  2032. /**
  2033. * @typedef {Object} PDFPageViewOptions
  2034. * @property {HTMLDivElement} container - The viewer element.
  2035. * @property {EventBus} eventBus - The application event bus.
  2036. * @property {number} id - The page unique ID (normally its number).
  2037. * @property {number} scale - The page scale display.
  2038. * @property {PageViewport} defaultViewport - The page viewport.
  2039. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  2040. * @property {IPDFTextLayerFactory} textLayerFactory
  2041. * @property {IPDFAnnotationLayerFactory} annotationLayerFactory
  2042. */
  2043. /**
  2044. * @class
  2045. * @implements {IRenderableView}
  2046. */
  2047. var PDFPageView = (function PDFPageViewClosure() {
  2048. /**
  2049. * @constructs PDFPageView
  2050. * @param {PDFPageViewOptions} options
  2051. */
  2052. function PDFPageView(options) {
  2053. var container = options.container;
  2054. var id = options.id;
  2055. var scale = options.scale;
  2056. var defaultViewport = options.defaultViewport;
  2057. var renderingQueue = options.renderingQueue;
  2058. var textLayerFactory = options.textLayerFactory;
  2059. var annotationLayerFactory = options.annotationLayerFactory;
  2060. this.id = id;
  2061. this.renderingId = 'page' + id;
  2062. this.rotation = 0;
  2063. this.scale = scale || DEFAULT_SCALE;
  2064. this.viewport = defaultViewport;
  2065. this.pdfPageRotate = defaultViewport.rotation;
  2066. this.hasRestrictedScaling = false;
  2067. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2068. this.renderingQueue = renderingQueue;
  2069. this.textLayerFactory = textLayerFactory;
  2070. this.annotationLayerFactory = annotationLayerFactory;
  2071. this.renderingState = RenderingStates.INITIAL;
  2072. this.resume = null;
  2073. this.onBeforeDraw = null;
  2074. this.onAfterDraw = null;
  2075. this.textLayer = null;
  2076. this.zoomLayer = null;
  2077. this.annotationLayer = null;
  2078. var div = document.createElement('div');
  2079. div.id = 'pageContainer' + this.id;
  2080. div.className = 'page';
  2081. div.style.width = Math.floor(this.viewport.width) + 'px';
  2082. div.style.height = Math.floor(this.viewport.height) + 'px';
  2083. div.setAttribute('data-page-number', this.id);
  2084. this.div = div;
  2085. container.appendChild(div);
  2086. }
  2087. PDFPageView.prototype = {
  2088. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  2089. this.pdfPage = pdfPage;
  2090. this.pdfPageRotate = pdfPage.rotate;
  2091. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2092. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
  2093. totalRotation);
  2094. this.stats = pdfPage.stats;
  2095. this.reset();
  2096. },
  2097. destroy: function PDFPageView_destroy() {
  2098. this.zoomLayer = null;
  2099. this.reset();
  2100. if (this.pdfPage) {
  2101. this.pdfPage.cleanup();
  2102. }
  2103. },
  2104. reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
  2105. if (this.renderTask) {
  2106. this.renderTask.cancel();
  2107. }
  2108. this.resume = null;
  2109. this.renderingState = RenderingStates.INITIAL;
  2110. var div = this.div;
  2111. div.style.width = Math.floor(this.viewport.width) + 'px';
  2112. div.style.height = Math.floor(this.viewport.height) + 'px';
  2113. var childNodes = div.childNodes;
  2114. var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
  2115. var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
  2116. this.annotationLayer.div) || null;
  2117. for (var i = childNodes.length - 1; i >= 0; i--) {
  2118. var node = childNodes[i];
  2119. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  2120. continue;
  2121. }
  2122. div.removeChild(node);
  2123. }
  2124. div.removeAttribute('data-loaded');
  2125. if (currentAnnotationNode) {
  2126. // Hide annotationLayer until all elements are resized
  2127. // so they are not displayed on the already-resized page
  2128. this.annotationLayer.hide();
  2129. } else {
  2130. this.annotationLayer = null;
  2131. }
  2132. if (this.canvas && !currentZoomLayerNode) {
  2133. // Zeroing the width and height causes Firefox to release graphics
  2134. // resources immediately, which can greatly reduce memory consumption.
  2135. this.canvas.width = 0;
  2136. this.canvas.height = 0;
  2137. delete this.canvas;
  2138. }
  2139. this.loadingIconDiv = document.createElement('div');
  2140. this.loadingIconDiv.className = 'loadingIcon';
  2141. div.appendChild(this.loadingIconDiv);
  2142. },
  2143. update: function PDFPageView_update(scale, rotation) {
  2144. this.scale = scale || this.scale;
  2145. if (typeof rotation !== 'undefined') {
  2146. this.rotation = rotation;
  2147. }
  2148. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  2149. this.viewport = this.viewport.clone({
  2150. scale: this.scale * CSS_UNITS,
  2151. rotation: totalRotation
  2152. });
  2153. var isScalingRestricted = false;
  2154. if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2155. var outputScale = this.outputScale;
  2156. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  2157. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  2158. pdfjsLib.PDFJS.maxCanvasPixels) {
  2159. isScalingRestricted = true;
  2160. }
  2161. }
  2162. if (this.canvas) {
  2163. if (pdfjsLib.PDFJS.useOnlyCssZoom ||
  2164. (this.hasRestrictedScaling && isScalingRestricted)) {
  2165. this.cssTransform(this.canvas, true);
  2166. this.eventBus.dispatch('pagerendered', {
  2167. source: this,
  2168. pageNumber: this.id,
  2169. cssTransform: true,
  2170. });
  2171. return;
  2172. }
  2173. if (!this.zoomLayer) {
  2174. this.zoomLayer = this.canvas.parentNode;
  2175. this.zoomLayer.style.position = 'absolute';
  2176. }
  2177. }
  2178. if (this.zoomLayer) {
  2179. this.cssTransform(this.zoomLayer.firstChild);
  2180. }
  2181. this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
  2182. },
  2183. /**
  2184. * Called when moved in the parent's container.
  2185. */
  2186. updatePosition: function PDFPageView_updatePosition() {
  2187. if (this.textLayer) {
  2188. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2189. }
  2190. },
  2191. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  2192. var CustomStyle = pdfjsLib.CustomStyle;
  2193. // Scale canvas, canvas wrapper, and page container.
  2194. var width = this.viewport.width;
  2195. var height = this.viewport.height;
  2196. var div = this.div;
  2197. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  2198. Math.floor(width) + 'px';
  2199. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  2200. Math.floor(height) + 'px';
  2201. // The canvas may have been originally rotated, rotate relative to that.
  2202. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  2203. var absRotation = Math.abs(relativeRotation);
  2204. var scaleX = 1, scaleY = 1;
  2205. if (absRotation === 90 || absRotation === 270) {
  2206. // Scale x and y because of the rotation.
  2207. scaleX = height / width;
  2208. scaleY = width / height;
  2209. }
  2210. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  2211. 'scale(' + scaleX + ',' + scaleY + ')';
  2212. CustomStyle.setProp('transform', canvas, cssTransform);
  2213. if (this.textLayer) {
  2214. // Rotating the text layer is more complicated since the divs inside the
  2215. // the text layer are rotated.
  2216. // TODO: This could probably be simplified by drawing the text layer in
  2217. // one orientation then rotating overall.
  2218. var textLayerViewport = this.textLayer.viewport;
  2219. var textRelativeRotation = this.viewport.rotation -
  2220. textLayerViewport.rotation;
  2221. var textAbsRotation = Math.abs(textRelativeRotation);
  2222. var scale = width / textLayerViewport.width;
  2223. if (textAbsRotation === 90 || textAbsRotation === 270) {
  2224. scale = width / textLayerViewport.height;
  2225. }
  2226. var textLayerDiv = this.textLayer.textLayerDiv;
  2227. var transX, transY;
  2228. switch (textAbsRotation) {
  2229. case 0:
  2230. transX = transY = 0;
  2231. break;
  2232. case 90:
  2233. transX = 0;
  2234. transY = '-' + textLayerDiv.style.height;
  2235. break;
  2236. case 180:
  2237. transX = '-' + textLayerDiv.style.width;
  2238. transY = '-' + textLayerDiv.style.height;
  2239. break;
  2240. case 270:
  2241. transX = '-' + textLayerDiv.style.width;
  2242. transY = 0;
  2243. break;
  2244. default:
  2245. console.error('Bad rotation value.');
  2246. break;
  2247. }
  2248. CustomStyle.setProp('transform', textLayerDiv,
  2249. 'rotate(' + textAbsRotation + 'deg) ' +
  2250. 'scale(' + scale + ', ' + scale + ') ' +
  2251. 'translate(' + transX + ', ' + transY + ')');
  2252. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  2253. }
  2254. if (redrawAnnotations && this.annotationLayer) {
  2255. this.annotationLayer.render(this.viewport, 'display');
  2256. }
  2257. },
  2258. get width() {
  2259. return this.viewport.width;
  2260. },
  2261. get height() {
  2262. return this.viewport.height;
  2263. },
  2264. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  2265. return this.viewport.convertToPdfPoint(x, y);
  2266. },
  2267. draw: function PDFPageView_draw() {
  2268. if (this.renderingState !== RenderingStates.INITIAL) {
  2269. console.error('Must be in new state before drawing');
  2270. }
  2271. this.renderingState = RenderingStates.RUNNING;
  2272. var pdfPage = this.pdfPage;
  2273. var viewport = this.viewport;
  2274. var div = this.div;
  2275. // Wrap the canvas so if it has a css transform for highdpi the overflow
  2276. // will be hidden in FF.
  2277. var canvasWrapper = document.createElement('div');
  2278. canvasWrapper.style.width = div.style.width;
  2279. canvasWrapper.style.height = div.style.height;
  2280. canvasWrapper.classList.add('canvasWrapper');
  2281. var canvas = document.createElement('canvas');
  2282. canvas.id = 'page' + this.id;
  2283. // Keep the canvas hidden until the first draw callback, or until drawing
  2284. // is complete when `!this.renderingQueue`, to prevent black flickering.
  2285. canvas.setAttribute('hidden', 'hidden');
  2286. var isCanvasHidden = true;
  2287. canvasWrapper.appendChild(canvas);
  2288. if (this.annotationLayer && this.annotationLayer.div) {
  2289. // annotationLayer needs to stay on top
  2290. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  2291. } else {
  2292. div.appendChild(canvasWrapper);
  2293. }
  2294. this.canvas = canvas;
  2295. canvas.mozOpaque = true;
  2296. var ctx = canvas.getContext('2d', {alpha: false});
  2297. var outputScale = getOutputScale(ctx);
  2298. this.outputScale = outputScale;
  2299. if (pdfjsLib.PDFJS.useOnlyCssZoom) {
  2300. var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
  2301. // Use a scale that will make the canvas be the original intended size
  2302. // of the page.
  2303. outputScale.sx *= actualSizeViewport.width / viewport.width;
  2304. outputScale.sy *= actualSizeViewport.height / viewport.height;
  2305. outputScale.scaled = true;
  2306. }
  2307. if (pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2308. var pixelsInViewport = viewport.width * viewport.height;
  2309. var maxScale =
  2310. Math.sqrt(pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport);
  2311. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  2312. outputScale.sx = maxScale;
  2313. outputScale.sy = maxScale;
  2314. outputScale.scaled = true;
  2315. this.hasRestrictedScaling = true;
  2316. } else {
  2317. this.hasRestrictedScaling = false;
  2318. }
  2319. }
  2320. var sfx = approximateFraction(outputScale.sx);
  2321. var sfy = approximateFraction(outputScale.sy);
  2322. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  2323. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  2324. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  2325. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  2326. // Add the viewport so it's known what it was originally drawn with.
  2327. canvas._viewport = viewport;
  2328. var textLayerDiv = null;
  2329. var textLayer = null;
  2330. if (this.textLayerFactory) {
  2331. textLayerDiv = document.createElement('div');
  2332. textLayerDiv.className = 'textLayer';
  2333. textLayerDiv.style.width = canvasWrapper.style.width;
  2334. textLayerDiv.style.height = canvasWrapper.style.height;
  2335. if (this.annotationLayer && this.annotationLayer.div) {
  2336. // annotationLayer needs to stay on top
  2337. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  2338. } else {
  2339. div.appendChild(textLayerDiv);
  2340. }
  2341. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
  2342. this.id - 1,
  2343. this.viewport);
  2344. }
  2345. this.textLayer = textLayer;
  2346. var resolveRenderPromise, rejectRenderPromise;
  2347. var promise = new Promise(function (resolve, reject) {
  2348. resolveRenderPromise = resolve;
  2349. rejectRenderPromise = reject;
  2350. });
  2351. // Rendering area
  2352. var self = this;
  2353. function pageViewDrawCallback(error) {
  2354. // The renderTask may have been replaced by a new one, so only remove
  2355. // the reference to the renderTask if it matches the one that is
  2356. // triggering this callback.
  2357. if (renderTask === self.renderTask) {
  2358. self.renderTask = null;
  2359. }
  2360. if (error === 'cancelled') {
  2361. rejectRenderPromise(error);
  2362. return;
  2363. }
  2364. self.renderingState = RenderingStates.FINISHED;
  2365. if (isCanvasHidden) {
  2366. self.canvas.removeAttribute('hidden');
  2367. isCanvasHidden = false;
  2368. }
  2369. if (self.loadingIconDiv) {
  2370. div.removeChild(self.loadingIconDiv);
  2371. delete self.loadingIconDiv;
  2372. }
  2373. if (self.zoomLayer) {
  2374. // Zeroing the width and height causes Firefox to release graphics
  2375. // resources immediately, which can greatly reduce memory consumption.
  2376. var zoomLayerCanvas = self.zoomLayer.firstChild;
  2377. zoomLayerCanvas.width = 0;
  2378. zoomLayerCanvas.height = 0;
  2379. if (div.contains(self.zoomLayer)) {
  2380. // Prevent "Node was not found" errors if the `zoomLayer` was
  2381. // already removed. This may occur intermittently if the scale
  2382. // changes many times in very quick succession.
  2383. div.removeChild(self.zoomLayer);
  2384. }
  2385. self.zoomLayer = null;
  2386. }
  2387. self.error = error;
  2388. self.stats = pdfPage.stats;
  2389. if (self.onAfterDraw) {
  2390. self.onAfterDraw();
  2391. }
  2392. self.eventBus.dispatch('pagerendered', {
  2393. source: self,
  2394. pageNumber: self.id,
  2395. cssTransform: false,
  2396. });
  2397. if (!error) {
  2398. resolveRenderPromise(undefined);
  2399. } else {
  2400. rejectRenderPromise(error);
  2401. }
  2402. }
  2403. var renderContinueCallback = null;
  2404. if (this.renderingQueue) {
  2405. renderContinueCallback = function renderContinueCallback(cont) {
  2406. if (!self.renderingQueue.isHighestPriority(self)) {
  2407. self.renderingState = RenderingStates.PAUSED;
  2408. self.resume = function resumeCallback() {
  2409. self.renderingState = RenderingStates.RUNNING;
  2410. cont();
  2411. };
  2412. return;
  2413. }
  2414. if (isCanvasHidden) {
  2415. self.canvas.removeAttribute('hidden');
  2416. isCanvasHidden = false;
  2417. }
  2418. cont();
  2419. };
  2420. }
  2421. var transform = !outputScale.scaled ? null :
  2422. [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  2423. var renderContext = {
  2424. canvasContext: ctx,
  2425. transform: transform,
  2426. viewport: this.viewport,
  2427. // intent: 'default', // === 'display'
  2428. };
  2429. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  2430. renderTask.onContinue = renderContinueCallback;
  2431. this.renderTask.promise.then(
  2432. function pdfPageRenderCallback() {
  2433. pageViewDrawCallback(null);
  2434. if (textLayer) {
  2435. self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(
  2436. function textContentResolved(textContent) {
  2437. textLayer.setTextContent(textContent);
  2438. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2439. }
  2440. );
  2441. }
  2442. },
  2443. function pdfPageRenderError(error) {
  2444. pageViewDrawCallback(error);
  2445. }
  2446. );
  2447. if (this.annotationLayerFactory) {
  2448. if (!this.annotationLayer) {
  2449. this.annotationLayer = this.annotationLayerFactory.
  2450. createAnnotationLayerBuilder(div, this.pdfPage);
  2451. }
  2452. this.annotationLayer.render(this.viewport, 'display');
  2453. }
  2454. div.setAttribute('data-loaded', true);
  2455. if (self.onBeforeDraw) {
  2456. self.onBeforeDraw();
  2457. }
  2458. return promise;
  2459. },
  2460. beforePrint: function PDFPageView_beforePrint(printContainer) {
  2461. var CustomStyle = pdfjsLib.CustomStyle;
  2462. var pdfPage = this.pdfPage;
  2463. var viewport = pdfPage.getViewport(1);
  2464. // Use the same hack we use for high dpi displays for printing to get
  2465. // better output until bug 811002 is fixed in FF.
  2466. var PRINT_OUTPUT_SCALE = 2;
  2467. var canvas = document.createElement('canvas');
  2468. // The logical size of the canvas.
  2469. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  2470. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  2471. // The rendered size of the canvas, relative to the size of canvasWrapper.
  2472. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
  2473. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  2474. (1 / PRINT_OUTPUT_SCALE) + ')';
  2475. CustomStyle.setProp('transform' , canvas, cssScale);
  2476. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  2477. var canvasWrapper = document.createElement('div');
  2478. canvasWrapper.appendChild(canvas);
  2479. printContainer.appendChild(canvasWrapper);
  2480. canvas.mozPrintCallback = function(obj) {
  2481. var ctx = obj.context;
  2482. ctx.save();
  2483. ctx.fillStyle = 'rgb(255, 255, 255)';
  2484. ctx.fillRect(0, 0, canvas.width, canvas.height);
  2485. ctx.restore();
  2486. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  2487. ctx._transformMatrix =
  2488. [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
  2489. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  2490. var renderContext = {
  2491. canvasContext: ctx,
  2492. viewport: viewport,
  2493. intent: 'print'
  2494. };
  2495. pdfPage.render(renderContext).promise.then(function() {
  2496. // Tell the printEngine that rendering this canvas/page has finished.
  2497. obj.done();
  2498. }, function(error) {
  2499. console.error(error);
  2500. // Tell the printEngine that rendering this canvas/page has failed.
  2501. // This will make the print proces stop.
  2502. if ('abort' in obj) {
  2503. obj.abort();
  2504. } else {
  2505. obj.done();
  2506. }
  2507. });
  2508. };
  2509. },
  2510. };
  2511. return PDFPageView;
  2512. })();
  2513. exports.PDFPageView = PDFPageView;
  2514. }));
  2515. (function (root, factory) {
  2516. {
  2517. factory((root.pdfjsWebTextLayerBuilder = {}), root.pdfjsWebDOMEvents,
  2518. root.pdfjsWebPDFJS);
  2519. }
  2520. }(this, function (exports, domEvents, pdfjsLib) {
  2521. /**
  2522. * @typedef {Object} TextLayerBuilderOptions
  2523. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  2524. * @property {EventBus} eventBus - The application event bus.
  2525. * @property {number} pageIndex - The page index.
  2526. * @property {PageViewport} viewport - The viewport of the text layer.
  2527. * @property {PDFFindController} findController
  2528. */
  2529. /**
  2530. * TextLayerBuilder provides text-selection functionality for the PDF.
  2531. * It does this by creating overlay divs over the PDF text. These divs
  2532. * contain text that matches the PDF text they are overlaying. This object
  2533. * also provides a way to highlight text that is being searched for.
  2534. * @class
  2535. */
  2536. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  2537. function TextLayerBuilder(options) {
  2538. this.textLayerDiv = options.textLayerDiv;
  2539. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2540. this.renderingDone = false;
  2541. this.divContentDone = false;
  2542. this.pageIdx = options.pageIndex;
  2543. this.pageNumber = this.pageIdx + 1;
  2544. this.matches = [];
  2545. this.viewport = options.viewport;
  2546. this.textDivs = [];
  2547. this.findController = options.findController || null;
  2548. this.textLayerRenderTask = null;
  2549. this._bindMouse();
  2550. }
  2551. TextLayerBuilder.prototype = {
  2552. _finishRendering: function TextLayerBuilder_finishRendering() {
  2553. this.renderingDone = true;
  2554. var endOfContent = document.createElement('div');
  2555. endOfContent.className = 'endOfContent';
  2556. this.textLayerDiv.appendChild(endOfContent);
  2557. this.eventBus.dispatch('textlayerrendered', {
  2558. source: this,
  2559. pageNumber: this.pageNumber
  2560. });
  2561. },
  2562. /**
  2563. * Renders the text layer.
  2564. * @param {number} timeout (optional) if specified, the rendering waits
  2565. * for specified amount of ms.
  2566. */
  2567. render: function TextLayerBuilder_render(timeout) {
  2568. if (!this.divContentDone || this.renderingDone) {
  2569. return;
  2570. }
  2571. if (this.textLayerRenderTask) {
  2572. this.textLayerRenderTask.cancel();
  2573. this.textLayerRenderTask = null;
  2574. }
  2575. this.textDivs = [];
  2576. var textLayerFrag = document.createDocumentFragment();
  2577. this.textLayerRenderTask = pdfjsLib.renderTextLayer({
  2578. textContent: this.textContent,
  2579. container: textLayerFrag,
  2580. viewport: this.viewport,
  2581. textDivs: this.textDivs,
  2582. timeout: timeout
  2583. });
  2584. this.textLayerRenderTask.promise.then(function () {
  2585. this.textLayerDiv.appendChild(textLayerFrag);
  2586. this._finishRendering();
  2587. this.updateMatches();
  2588. }.bind(this), function (reason) {
  2589. // canceled or failed to render text layer -- skipping errors
  2590. });
  2591. },
  2592. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  2593. if (this.textLayerRenderTask) {
  2594. this.textLayerRenderTask.cancel();
  2595. this.textLayerRenderTask = null;
  2596. }
  2597. this.textContent = textContent;
  2598. this.divContentDone = true;
  2599. },
  2600. convertMatches: function TextLayerBuilder_convertMatches(matches,
  2601. matchesLength) {
  2602. var i = 0;
  2603. var iIndex = 0;
  2604. var bidiTexts = this.textContent.items;
  2605. var end = bidiTexts.length - 1;
  2606. var queryLen = (this.findController === null ?
  2607. 0 : this.findController.state.query.length);
  2608. var ret = [];
  2609. if (!matches) {
  2610. return ret;
  2611. }
  2612. for (var m = 0, len = matches.length; m < len; m++) {
  2613. // Calculate the start position.
  2614. var matchIdx = matches[m];
  2615. // Loop over the divIdxs.
  2616. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  2617. iIndex += bidiTexts[i].str.length;
  2618. i++;
  2619. }
  2620. if (i === bidiTexts.length) {
  2621. console.error('Could not find a matching mapping');
  2622. }
  2623. var match = {
  2624. begin: {
  2625. divIdx: i,
  2626. offset: matchIdx - iIndex
  2627. }
  2628. };
  2629. // Calculate the end position.
  2630. if (matchesLength) { // multiterm search
  2631. matchIdx += matchesLength[m];
  2632. } else { // phrase search
  2633. matchIdx += queryLen;
  2634. }
  2635. // Somewhat the same array as above, but use > instead of >= to get
  2636. // the end position right.
  2637. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  2638. iIndex += bidiTexts[i].str.length;
  2639. i++;
  2640. }
  2641. match.end = {
  2642. divIdx: i,
  2643. offset: matchIdx - iIndex
  2644. };
  2645. ret.push(match);
  2646. }
  2647. return ret;
  2648. },
  2649. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  2650. // Early exit if there is nothing to render.
  2651. if (matches.length === 0) {
  2652. return;
  2653. }
  2654. var bidiTexts = this.textContent.items;
  2655. var textDivs = this.textDivs;
  2656. var prevEnd = null;
  2657. var pageIdx = this.pageIdx;
  2658. var isSelectedPage = (this.findController === null ?
  2659. false : (pageIdx === this.findController.selected.pageIdx));
  2660. var selectedMatchIdx = (this.findController === null ?
  2661. -1 : this.findController.selected.matchIdx);
  2662. var highlightAll = (this.findController === null ?
  2663. false : this.findController.state.highlightAll);
  2664. var infinity = {
  2665. divIdx: -1,
  2666. offset: undefined
  2667. };
  2668. function beginText(begin, className) {
  2669. var divIdx = begin.divIdx;
  2670. textDivs[divIdx].textContent = '';
  2671. appendTextToDiv(divIdx, 0, begin.offset, className);
  2672. }
  2673. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  2674. var div = textDivs[divIdx];
  2675. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  2676. var node = document.createTextNode(content);
  2677. if (className) {
  2678. var span = document.createElement('span');
  2679. span.className = className;
  2680. span.appendChild(node);
  2681. div.appendChild(span);
  2682. return;
  2683. }
  2684. div.appendChild(node);
  2685. }
  2686. var i0 = selectedMatchIdx, i1 = i0 + 1;
  2687. if (highlightAll) {
  2688. i0 = 0;
  2689. i1 = matches.length;
  2690. } else if (!isSelectedPage) {
  2691. // Not highlighting all and this isn't the selected page, so do nothing.
  2692. return;
  2693. }
  2694. for (var i = i0; i < i1; i++) {
  2695. var match = matches[i];
  2696. var begin = match.begin;
  2697. var end = match.end;
  2698. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  2699. var highlightSuffix = (isSelected ? ' selected' : '');
  2700. if (this.findController) {
  2701. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  2702. begin.divIdx);
  2703. }
  2704. // Match inside new div.
  2705. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  2706. // If there was a previous div, then add the text at the end.
  2707. if (prevEnd !== null) {
  2708. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2709. }
  2710. // Clear the divs and set the content until the starting point.
  2711. beginText(begin);
  2712. } else {
  2713. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  2714. }
  2715. if (begin.divIdx === end.divIdx) {
  2716. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  2717. 'highlight' + highlightSuffix);
  2718. } else {
  2719. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  2720. 'highlight begin' + highlightSuffix);
  2721. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  2722. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  2723. }
  2724. beginText(end, 'highlight end' + highlightSuffix);
  2725. }
  2726. prevEnd = end;
  2727. }
  2728. if (prevEnd) {
  2729. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2730. }
  2731. },
  2732. updateMatches: function TextLayerBuilder_updateMatches() {
  2733. // Only show matches when all rendering is done.
  2734. if (!this.renderingDone) {
  2735. return;
  2736. }
  2737. // Clear all matches.
  2738. var matches = this.matches;
  2739. var textDivs = this.textDivs;
  2740. var bidiTexts = this.textContent.items;
  2741. var clearedUntilDivIdx = -1;
  2742. // Clear all current matches.
  2743. for (var i = 0, len = matches.length; i < len; i++) {
  2744. var match = matches[i];
  2745. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  2746. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  2747. var div = textDivs[n];
  2748. div.textContent = bidiTexts[n].str;
  2749. div.className = '';
  2750. }
  2751. clearedUntilDivIdx = match.end.divIdx + 1;
  2752. }
  2753. if (this.findController === null || !this.findController.active) {
  2754. return;
  2755. }
  2756. // Convert the matches on the page controller into the match format
  2757. // used for the textLayer.
  2758. var pageMatches, pageMatchesLength;
  2759. if (this.findController !== null) {
  2760. pageMatches = this.findController.pageMatches[this.pageIdx] || null;
  2761. pageMatchesLength = (this.findController.pageMatchesLength) ?
  2762. this.findController.pageMatchesLength[this.pageIdx] || null : null;
  2763. }
  2764. this.matches = this.convertMatches(pageMatches, pageMatchesLength);
  2765. this.renderMatches(this.matches);
  2766. },
  2767. /**
  2768. * Fixes text selection: adds additional div where mouse was clicked.
  2769. * This reduces flickering of the content if mouse slowly dragged down/up.
  2770. * @private
  2771. */
  2772. _bindMouse: function TextLayerBuilder_bindMouse() {
  2773. var div = this.textLayerDiv;
  2774. div.addEventListener('mousedown', function (e) {
  2775. var end = div.querySelector('.endOfContent');
  2776. if (!end) {
  2777. return;
  2778. }
  2779. // On non-Firefox browsers, the selection will feel better if the height
  2780. // of the endOfContent div will be adjusted to start at mouse click
  2781. // location -- this will avoid flickering when selections moves up.
  2782. // However it does not work when selection started on empty space.
  2783. var adjustTop = e.target !== div;
  2784. adjustTop = adjustTop && window.getComputedStyle(end).
  2785. getPropertyValue('-moz-user-select') !== 'none';
  2786. if (adjustTop) {
  2787. var divBounds = div.getBoundingClientRect();
  2788. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  2789. end.style.top = (r * 100).toFixed(2) + '%';
  2790. }
  2791. end.classList.add('active');
  2792. });
  2793. div.addEventListener('mouseup', function (e) {
  2794. var end = div.querySelector('.endOfContent');
  2795. if (!end) {
  2796. return;
  2797. }
  2798. end.style.top = '';
  2799. end.classList.remove('active');
  2800. });
  2801. },
  2802. };
  2803. return TextLayerBuilder;
  2804. })();
  2805. /**
  2806. * @constructor
  2807. * @implements IPDFTextLayerFactory
  2808. */
  2809. function DefaultTextLayerFactory() {}
  2810. DefaultTextLayerFactory.prototype = {
  2811. /**
  2812. * @param {HTMLDivElement} textLayerDiv
  2813. * @param {number} pageIndex
  2814. * @param {PageViewport} viewport
  2815. * @returns {TextLayerBuilder}
  2816. */
  2817. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  2818. return new TextLayerBuilder({
  2819. textLayerDiv: textLayerDiv,
  2820. pageIndex: pageIndex,
  2821. viewport: viewport
  2822. });
  2823. }
  2824. };
  2825. exports.TextLayerBuilder = TextLayerBuilder;
  2826. exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2827. }));
  2828. (function (root, factory) {
  2829. {
  2830. factory((root.pdfjsWebAnnotationLayerBuilder = {}), root.pdfjsWebUIUtils,
  2831. root.pdfjsWebPDFLinkService, root.pdfjsWebPDFJS);
  2832. }
  2833. }(this, function (exports, uiUtils, pdfLinkService, pdfjsLib) {
  2834. var mozL10n = uiUtils.mozL10n;
  2835. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2836. /**
  2837. * @typedef {Object} AnnotationLayerBuilderOptions
  2838. * @property {HTMLDivElement} pageDiv
  2839. * @property {PDFPage} pdfPage
  2840. * @property {IPDFLinkService} linkService
  2841. * @property {DownloadManager} downloadManager
  2842. */
  2843. /**
  2844. * @class
  2845. */
  2846. var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
  2847. /**
  2848. * @param {AnnotationLayerBuilderOptions} options
  2849. * @constructs AnnotationLayerBuilder
  2850. */
  2851. function AnnotationLayerBuilder(options) {
  2852. this.pageDiv = options.pageDiv;
  2853. this.pdfPage = options.pdfPage;
  2854. this.linkService = options.linkService;
  2855. this.downloadManager = options.downloadManager;
  2856. this.div = null;
  2857. }
  2858. AnnotationLayerBuilder.prototype =
  2859. /** @lends AnnotationLayerBuilder.prototype */ {
  2860. /**
  2861. * @param {PageViewport} viewport
  2862. * @param {string} intent (default value is 'display')
  2863. */
  2864. render: function AnnotationLayerBuilder_render(viewport, intent) {
  2865. var self = this;
  2866. var parameters = {
  2867. intent: (intent === undefined ? 'display' : intent),
  2868. };
  2869. this.pdfPage.getAnnotations(parameters).then(function (annotations) {
  2870. viewport = viewport.clone({ dontFlip: true });
  2871. parameters = {
  2872. viewport: viewport,
  2873. div: self.div,
  2874. annotations: annotations,
  2875. page: self.pdfPage,
  2876. linkService: self.linkService,
  2877. downloadManager: self.downloadManager
  2878. };
  2879. if (self.div) {
  2880. // If an annotationLayer already exists, refresh its children's
  2881. // transformation matrices.
  2882. pdfjsLib.AnnotationLayer.update(parameters);
  2883. } else {
  2884. // Create an annotation layer div and render the annotations
  2885. // if there is at least one annotation.
  2886. if (annotations.length === 0) {
  2887. return;
  2888. }
  2889. self.div = document.createElement('div');
  2890. self.div.className = 'annotationLayer';
  2891. self.pageDiv.appendChild(self.div);
  2892. parameters.div = self.div;
  2893. pdfjsLib.AnnotationLayer.render(parameters);
  2894. if (typeof mozL10n !== 'undefined') {
  2895. mozL10n.translate(self.div);
  2896. }
  2897. }
  2898. });
  2899. },
  2900. hide: function AnnotationLayerBuilder_hide() {
  2901. if (!this.div) {
  2902. return;
  2903. }
  2904. this.div.setAttribute('hidden', 'true');
  2905. }
  2906. };
  2907. return AnnotationLayerBuilder;
  2908. })();
  2909. /**
  2910. * @constructor
  2911. * @implements IPDFAnnotationLayerFactory
  2912. */
  2913. function DefaultAnnotationLayerFactory() {}
  2914. DefaultAnnotationLayerFactory.prototype = {
  2915. /**
  2916. * @param {HTMLDivElement} pageDiv
  2917. * @param {PDFPage} pdfPage
  2918. * @returns {AnnotationLayerBuilder}
  2919. */
  2920. createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
  2921. return new AnnotationLayerBuilder({
  2922. pageDiv: pageDiv,
  2923. pdfPage: pdfPage,
  2924. linkService: new SimpleLinkService(),
  2925. });
  2926. }
  2927. };
  2928. exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
  2929. exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
  2930. }));
  2931. (function (root, factory) {
  2932. {
  2933. factory((root.pdfjsWebPDFViewer = {}), root.pdfjsWebUIUtils,
  2934. root.pdfjsWebPDFPageView, root.pdfjsWebPDFRenderingQueue,
  2935. root.pdfjsWebTextLayerBuilder, root.pdfjsWebAnnotationLayerBuilder,
  2936. root.pdfjsWebPDFLinkService, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2937. }
  2938. }(this, function (exports, uiUtils, pdfPageView, pdfRenderingQueue,
  2939. textLayerBuilder, annotationLayerBuilder, pdfLinkService,
  2940. domEvents, pdfjsLib) {
  2941. var UNKNOWN_SCALE = uiUtils.UNKNOWN_SCALE;
  2942. var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING;
  2943. var VERTICAL_PADDING = uiUtils.VERTICAL_PADDING;
  2944. var MAX_AUTO_SCALE = uiUtils.MAX_AUTO_SCALE;
  2945. var CSS_UNITS = uiUtils.CSS_UNITS;
  2946. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2947. var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE;
  2948. var scrollIntoView = uiUtils.scrollIntoView;
  2949. var watchScroll = uiUtils.watchScroll;
  2950. var getVisibleElements = uiUtils.getVisibleElements;
  2951. var PDFPageView = pdfPageView.PDFPageView;
  2952. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2953. var PDFRenderingQueue = pdfRenderingQueue.PDFRenderingQueue;
  2954. var TextLayerBuilder = textLayerBuilder.TextLayerBuilder;
  2955. var AnnotationLayerBuilder = annotationLayerBuilder.AnnotationLayerBuilder;
  2956. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2957. var PresentationModeState = {
  2958. UNKNOWN: 0,
  2959. NORMAL: 1,
  2960. CHANGING: 2,
  2961. FULLSCREEN: 3,
  2962. };
  2963. var DEFAULT_CACHE_SIZE = 10;
  2964. /**
  2965. * @typedef {Object} PDFViewerOptions
  2966. * @property {HTMLDivElement} container - The container for the viewer element.
  2967. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  2968. * @property {EventBus} eventBus - The application event bus.
  2969. * @property {IPDFLinkService} linkService - The navigation/linking service.
  2970. * @property {DownloadManager} downloadManager - (optional) The download
  2971. * manager component.
  2972. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  2973. * queue object.
  2974. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  2975. * around the pages. The default is false.
  2976. */
  2977. /**
  2978. * Simple viewer control to display PDF content/pages.
  2979. * @class
  2980. * @implements {IRenderableView}
  2981. */
  2982. var PDFViewer = (function pdfViewer() {
  2983. function PDFPageViewBuffer(size) {
  2984. var data = [];
  2985. this.push = function cachePush(view) {
  2986. var i = data.indexOf(view);
  2987. if (i >= 0) {
  2988. data.splice(i, 1);
  2989. }
  2990. data.push(view);
  2991. if (data.length > size) {
  2992. data.shift().destroy();
  2993. }
  2994. };
  2995. this.resize = function (newSize) {
  2996. size = newSize;
  2997. while (data.length > size) {
  2998. data.shift().destroy();
  2999. }
  3000. };
  3001. }
  3002. function isSameScale(oldScale, newScale) {
  3003. if (newScale === oldScale) {
  3004. return true;
  3005. }
  3006. if (Math.abs(newScale - oldScale) < 1e-15) {
  3007. // Prevent unnecessary re-rendering of all pages when the scale
  3008. // changes only because of limited numerical precision.
  3009. return true;
  3010. }
  3011. return false;
  3012. }
  3013. /**
  3014. * @constructs PDFViewer
  3015. * @param {PDFViewerOptions} options
  3016. */
  3017. function PDFViewer(options) {
  3018. this.container = options.container;
  3019. this.viewer = options.viewer || options.container.firstElementChild;
  3020. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  3021. this.linkService = options.linkService || new SimpleLinkService();
  3022. this.downloadManager = options.downloadManager || null;
  3023. this.removePageBorders = options.removePageBorders || false;
  3024. this.defaultRenderingQueue = !options.renderingQueue;
  3025. if (this.defaultRenderingQueue) {
  3026. // Custom rendering queue is not specified, using default one
  3027. this.renderingQueue = new PDFRenderingQueue();
  3028. this.renderingQueue.setViewer(this);
  3029. } else {
  3030. this.renderingQueue = options.renderingQueue;
  3031. }
  3032. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  3033. this.presentationModeState = PresentationModeState.UNKNOWN;
  3034. this._resetView();
  3035. if (this.removePageBorders) {
  3036. this.viewer.classList.add('removePageBorders');
  3037. }
  3038. }
  3039. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  3040. get pagesCount() {
  3041. return this._pages.length;
  3042. },
  3043. getPageView: function (index) {
  3044. return this._pages[index];
  3045. },
  3046. get currentPageNumber() {
  3047. return this._currentPageNumber;
  3048. },
  3049. set currentPageNumber(val) {
  3050. if (!this.pdfDocument) {
  3051. this._currentPageNumber = val;
  3052. return;
  3053. }
  3054. this._setCurrentPageNumber(val);
  3055. // The intent can be to just reset a scroll position and/or scale.
  3056. this._resetCurrentPageView();
  3057. },
  3058. _setCurrentPageNumber: function pdfViewer_setCurrentPageNumber(val) {
  3059. if (this._currentPageNumber === val) {
  3060. return;
  3061. }
  3062. var arg;
  3063. if (!(0 < val && val <= this.pagesCount)) {
  3064. arg = {
  3065. source: this,
  3066. pageNumber: this._currentPageNumber,
  3067. previousPageNumber: val
  3068. };
  3069. this.eventBus.dispatch('pagechanging', arg);
  3070. this.eventBus.dispatch('pagechange', arg);
  3071. return;
  3072. }
  3073. arg = {
  3074. source: this,
  3075. pageNumber: val,
  3076. previousPageNumber: this._currentPageNumber
  3077. };
  3078. this._currentPageNumber = val;
  3079. this.eventBus.dispatch('pagechanging', arg);
  3080. this.eventBus.dispatch('pagechange', arg);
  3081. },
  3082. /**
  3083. * @returns {number}
  3084. */
  3085. get currentScale() {
  3086. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  3087. DEFAULT_SCALE;
  3088. },
  3089. /**
  3090. * @param {number} val - Scale of the pages in percents.
  3091. */
  3092. set currentScale(val) {
  3093. if (isNaN(val)) {
  3094. throw new Error('Invalid numeric scale');
  3095. }
  3096. if (!this.pdfDocument) {
  3097. this._currentScale = val;
  3098. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  3099. return;
  3100. }
  3101. this._setScale(val, false);
  3102. },
  3103. /**
  3104. * @returns {string}
  3105. */
  3106. get currentScaleValue() {
  3107. return this._currentScaleValue;
  3108. },
  3109. /**
  3110. * @param val - The scale of the pages (in percent or predefined value).
  3111. */
  3112. set currentScaleValue(val) {
  3113. if (!this.pdfDocument) {
  3114. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  3115. this._currentScaleValue = val.toString();
  3116. return;
  3117. }
  3118. this._setScale(val, false);
  3119. },
  3120. /**
  3121. * @returns {number}
  3122. */
  3123. get pagesRotation() {
  3124. return this._pagesRotation;
  3125. },
  3126. /**
  3127. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  3128. */
  3129. set pagesRotation(rotation) {
  3130. this._pagesRotation = rotation;
  3131. for (var i = 0, l = this._pages.length; i < l; i++) {
  3132. var pageView = this._pages[i];
  3133. pageView.update(pageView.scale, rotation);
  3134. }
  3135. this._setScale(this._currentScaleValue, true);
  3136. if (this.defaultRenderingQueue) {
  3137. this.update();
  3138. }
  3139. },
  3140. /**
  3141. * @param pdfDocument {PDFDocument}
  3142. */
  3143. setDocument: function (pdfDocument) {
  3144. if (this.pdfDocument) {
  3145. this._resetView();
  3146. }
  3147. this.pdfDocument = pdfDocument;
  3148. if (!pdfDocument) {
  3149. return;
  3150. }
  3151. var pagesCount = pdfDocument.numPages;
  3152. var self = this;
  3153. var resolvePagesPromise;
  3154. var pagesPromise = new Promise(function (resolve) {
  3155. resolvePagesPromise = resolve;
  3156. });
  3157. this.pagesPromise = pagesPromise;
  3158. pagesPromise.then(function () {
  3159. self.eventBus.dispatch('pagesloaded', {
  3160. source: self,
  3161. pagesCount: pagesCount
  3162. });
  3163. });
  3164. var isOnePageRenderedResolved = false;
  3165. var resolveOnePageRendered = null;
  3166. var onePageRendered = new Promise(function (resolve) {
  3167. resolveOnePageRendered = resolve;
  3168. });
  3169. this.onePageRendered = onePageRendered;
  3170. var bindOnAfterAndBeforeDraw = function (pageView) {
  3171. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  3172. // Add the page to the buffer at the start of drawing. That way it can
  3173. // be evicted from the buffer and destroyed even if we pause its
  3174. // rendering.
  3175. self._buffer.push(this);
  3176. };
  3177. // when page is painted, using the image as thumbnail base
  3178. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  3179. if (!isOnePageRenderedResolved) {
  3180. isOnePageRenderedResolved = true;
  3181. resolveOnePageRendered();
  3182. }
  3183. };
  3184. };
  3185. var firstPagePromise = pdfDocument.getPage(1);
  3186. this.firstPagePromise = firstPagePromise;
  3187. // Fetch a single page so we can get a viewport that will be the default
  3188. // viewport for all pages
  3189. return firstPagePromise.then(function(pdfPage) {
  3190. var scale = this.currentScale;
  3191. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  3192. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3193. var textLayerFactory = null;
  3194. if (!pdfjsLib.PDFJS.disableTextLayer) {
  3195. textLayerFactory = this;
  3196. }
  3197. var pageView = new PDFPageView({
  3198. container: this.viewer,
  3199. eventBus: this.eventBus,
  3200. id: pageNum,
  3201. scale: scale,
  3202. defaultViewport: viewport.clone(),
  3203. renderingQueue: this.renderingQueue,
  3204. textLayerFactory: textLayerFactory,
  3205. annotationLayerFactory: this
  3206. });
  3207. bindOnAfterAndBeforeDraw(pageView);
  3208. this._pages.push(pageView);
  3209. }
  3210. var linkService = this.linkService;
  3211. // Fetch all the pages since the viewport is needed before printing
  3212. // starts to create the correct size canvas. Wait until one page is
  3213. // rendered so we don't tie up too many resources early on.
  3214. onePageRendered.then(function () {
  3215. if (!pdfjsLib.PDFJS.disableAutoFetch) {
  3216. var getPagesLeft = pagesCount;
  3217. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3218. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  3219. var pageView = self._pages[pageNum - 1];
  3220. if (!pageView.pdfPage) {
  3221. pageView.setPdfPage(pdfPage);
  3222. }
  3223. linkService.cachePageRef(pageNum, pdfPage.ref);
  3224. getPagesLeft--;
  3225. if (!getPagesLeft) {
  3226. resolvePagesPromise();
  3227. }
  3228. }.bind(null, pageNum));
  3229. }
  3230. } else {
  3231. // XXX: Printing is semi-broken with auto fetch disabled.
  3232. resolvePagesPromise();
  3233. }
  3234. });
  3235. self.eventBus.dispatch('pagesinit', {source: self});
  3236. if (this.defaultRenderingQueue) {
  3237. this.update();
  3238. }
  3239. if (this.findController) {
  3240. this.findController.resolveFirstPage();
  3241. }
  3242. }.bind(this));
  3243. },
  3244. _resetView: function () {
  3245. this._pages = [];
  3246. this._currentPageNumber = 1;
  3247. this._currentScale = UNKNOWN_SCALE;
  3248. this._currentScaleValue = null;
  3249. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  3250. this._location = null;
  3251. this._pagesRotation = 0;
  3252. this._pagesRequests = [];
  3253. var container = this.viewer;
  3254. while (container.hasChildNodes()) {
  3255. container.removeChild(container.lastChild);
  3256. }
  3257. },
  3258. _scrollUpdate: function PDFViewer_scrollUpdate() {
  3259. if (this.pagesCount === 0) {
  3260. return;
  3261. }
  3262. this.update();
  3263. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3264. this._pages[i].updatePosition();
  3265. }
  3266. },
  3267. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  3268. newScale, newValue, preset) {
  3269. var arg = {
  3270. source: this,
  3271. scale: newScale,
  3272. presetValue: preset ? newValue : undefined
  3273. };
  3274. this.eventBus.dispatch('scalechanging', arg);
  3275. this.eventBus.dispatch('scalechange', arg);
  3276. },
  3277. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  3278. newScale, newValue, noScroll, preset) {
  3279. this._currentScaleValue = newValue.toString();
  3280. if (isSameScale(this._currentScale, newScale)) {
  3281. if (preset) {
  3282. this._setScaleDispatchEvent(newScale, newValue, true);
  3283. }
  3284. return;
  3285. }
  3286. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3287. this._pages[i].update(newScale);
  3288. }
  3289. this._currentScale = newScale;
  3290. if (!noScroll) {
  3291. var page = this._currentPageNumber, dest;
  3292. if (this._location && !pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom &&
  3293. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  3294. page = this._location.pageNumber;
  3295. dest = [null, { name: 'XYZ' }, this._location.left,
  3296. this._location.top, null];
  3297. }
  3298. this.scrollPageIntoView(page, dest);
  3299. }
  3300. this._setScaleDispatchEvent(newScale, newValue, preset);
  3301. if (this.defaultRenderingQueue) {
  3302. this.update();
  3303. }
  3304. },
  3305. _setScale: function pdfViewer_setScale(value, noScroll) {
  3306. var scale = parseFloat(value);
  3307. if (scale > 0) {
  3308. this._setScaleUpdatePages(scale, value, noScroll, false);
  3309. } else {
  3310. var currentPage = this._pages[this._currentPageNumber - 1];
  3311. if (!currentPage) {
  3312. return;
  3313. }
  3314. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  3315. 0 : SCROLLBAR_PADDING;
  3316. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  3317. 0 : VERTICAL_PADDING;
  3318. var pageWidthScale = (this.container.clientWidth - hPadding) /
  3319. currentPage.width * currentPage.scale;
  3320. var pageHeightScale = (this.container.clientHeight - vPadding) /
  3321. currentPage.height * currentPage.scale;
  3322. switch (value) {
  3323. case 'page-actual':
  3324. scale = 1;
  3325. break;
  3326. case 'page-width':
  3327. scale = pageWidthScale;
  3328. break;
  3329. case 'page-height':
  3330. scale = pageHeightScale;
  3331. break;
  3332. case 'page-fit':
  3333. scale = Math.min(pageWidthScale, pageHeightScale);
  3334. break;
  3335. case 'auto':
  3336. var isLandscape = (currentPage.width > currentPage.height);
  3337. // For pages in landscape mode, fit the page height to the viewer
  3338. // *unless* the page would thus become too wide to fit horizontally.
  3339. var horizontalScale = isLandscape ?
  3340. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  3341. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  3342. break;
  3343. default:
  3344. console.error('pdfViewSetScale: \'' + value +
  3345. '\' is an unknown zoom value.');
  3346. return;
  3347. }
  3348. this._setScaleUpdatePages(scale, value, noScroll, true);
  3349. }
  3350. },
  3351. /**
  3352. * Refreshes page view: scrolls to the current page and updates the scale.
  3353. */
  3354. _resetCurrentPageView: function () {
  3355. if (this.isInPresentationMode) {
  3356. // Fixes the case when PDF has different page sizes.
  3357. this._setScale(this._currentScaleValue, true);
  3358. }
  3359. var pageView = this._pages[this._currentPageNumber - 1];
  3360. scrollIntoView(pageView.div);
  3361. },
  3362. /**
  3363. * Scrolls page into view.
  3364. * @param {number} pageNumber
  3365. * @param {Array} dest - (optional) original PDF destination array:
  3366. * <page-ref> </XYZ|FitXXX> <args..>
  3367. */
  3368. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  3369. dest) {
  3370. if (!this.pdfDocument) {
  3371. return;
  3372. }
  3373. if (this.isInPresentationMode || !dest) {
  3374. this._setCurrentPageNumber(pageNumber);
  3375. this._resetCurrentPageView();
  3376. return;
  3377. }
  3378. var pageView = this._pages[pageNumber - 1];
  3379. var x = 0, y = 0;
  3380. var width = 0, height = 0, widthScale, heightScale;
  3381. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  3382. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  3383. pageView.scale / CSS_UNITS;
  3384. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  3385. pageView.scale / CSS_UNITS;
  3386. var scale = 0;
  3387. switch (dest[1].name) {
  3388. case 'XYZ':
  3389. x = dest[2];
  3390. y = dest[3];
  3391. scale = dest[4];
  3392. // If x and/or y coordinates are not supplied, default to
  3393. // _top_ left of the page (not the obvious bottom left,
  3394. // since aligning the bottom of the intended page with the
  3395. // top of the window is rarely helpful).
  3396. x = x !== null ? x : 0;
  3397. y = y !== null ? y : pageHeight;
  3398. break;
  3399. case 'Fit':
  3400. case 'FitB':
  3401. scale = 'page-fit';
  3402. break;
  3403. case 'FitH':
  3404. case 'FitBH':
  3405. y = dest[2];
  3406. scale = 'page-width';
  3407. // According to the PDF spec, section 12.3.2.2, a `null` value in the
  3408. // parameter should maintain the position relative to the new page.
  3409. if (y === null && this._location) {
  3410. x = this._location.left;
  3411. y = this._location.top;
  3412. }
  3413. break;
  3414. case 'FitV':
  3415. case 'FitBV':
  3416. x = dest[2];
  3417. width = pageWidth;
  3418. height = pageHeight;
  3419. scale = 'page-height';
  3420. break;
  3421. case 'FitR':
  3422. x = dest[2];
  3423. y = dest[3];
  3424. width = dest[4] - x;
  3425. height = dest[5] - y;
  3426. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  3427. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  3428. widthScale = (this.container.clientWidth - hPadding) /
  3429. width / CSS_UNITS;
  3430. heightScale = (this.container.clientHeight - vPadding) /
  3431. height / CSS_UNITS;
  3432. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  3433. break;
  3434. default:
  3435. console.error('PDFViewer_scrollPageIntoView: \'' + dest[1].name +
  3436. '\' is not a valid destination type.');
  3437. return;
  3438. }
  3439. if (scale && scale !== this._currentScale) {
  3440. this.currentScaleValue = scale;
  3441. } else if (this._currentScale === UNKNOWN_SCALE) {
  3442. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  3443. }
  3444. if (scale === 'page-fit' && !dest[4]) {
  3445. scrollIntoView(pageView.div);
  3446. return;
  3447. }
  3448. var boundingRect = [
  3449. pageView.viewport.convertToViewportPoint(x, y),
  3450. pageView.viewport.convertToViewportPoint(x + width, y + height)
  3451. ];
  3452. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  3453. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  3454. scrollIntoView(pageView.div, { left: left, top: top });
  3455. },
  3456. _updateLocation: function (firstPage) {
  3457. var currentScale = this._currentScale;
  3458. var currentScaleValue = this._currentScaleValue;
  3459. var normalizedScaleValue =
  3460. parseFloat(currentScaleValue) === currentScale ?
  3461. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  3462. var pageNumber = firstPage.id;
  3463. var pdfOpenParams = '#page=' + pageNumber;
  3464. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  3465. var currentPageView = this._pages[pageNumber - 1];
  3466. var container = this.container;
  3467. var topLeft = currentPageView.getPagePoint(
  3468. (container.scrollLeft - firstPage.x),
  3469. (container.scrollTop - firstPage.y));
  3470. var intLeft = Math.round(topLeft[0]);
  3471. var intTop = Math.round(topLeft[1]);
  3472. pdfOpenParams += ',' + intLeft + ',' + intTop;
  3473. this._location = {
  3474. pageNumber: pageNumber,
  3475. scale: normalizedScaleValue,
  3476. top: intTop,
  3477. left: intLeft,
  3478. pdfOpenParams: pdfOpenParams
  3479. };
  3480. },
  3481. update: function PDFViewer_update() {
  3482. var visible = this._getVisiblePages();
  3483. var visiblePages = visible.views;
  3484. if (visiblePages.length === 0) {
  3485. return;
  3486. }
  3487. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  3488. 2 * visiblePages.length + 1);
  3489. this._buffer.resize(suggestedCacheSize);
  3490. this.renderingQueue.renderHighestPriority(visible);
  3491. var currentId = this._currentPageNumber;
  3492. var firstPage = visible.first;
  3493. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  3494. i < ii; ++i) {
  3495. var page = visiblePages[i];
  3496. if (page.percent < 100) {
  3497. break;
  3498. }
  3499. if (page.id === currentId) {
  3500. stillFullyVisible = true;
  3501. break;
  3502. }
  3503. }
  3504. if (!stillFullyVisible) {
  3505. currentId = visiblePages[0].id;
  3506. }
  3507. if (!this.isInPresentationMode) {
  3508. this._setCurrentPageNumber(currentId);
  3509. }
  3510. this._updateLocation(firstPage);
  3511. this.eventBus.dispatch('updateviewarea', {
  3512. source: this,
  3513. location: this._location
  3514. });
  3515. },
  3516. containsElement: function (element) {
  3517. return this.container.contains(element);
  3518. },
  3519. focus: function () {
  3520. this.container.focus();
  3521. },
  3522. get isInPresentationMode() {
  3523. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  3524. },
  3525. get isChangingPresentationMode() {
  3526. return this.presentationModeState === PresentationModeState.CHANGING;
  3527. },
  3528. get isHorizontalScrollbarEnabled() {
  3529. return (this.isInPresentationMode ?
  3530. false : (this.container.scrollWidth > this.container.clientWidth));
  3531. },
  3532. _getVisiblePages: function () {
  3533. if (!this.isInPresentationMode) {
  3534. return getVisibleElements(this.container, this._pages, true);
  3535. } else {
  3536. // The algorithm in getVisibleElements doesn't work in all browsers and
  3537. // configurations when presentation mode is active.
  3538. var visible = [];
  3539. var currentPage = this._pages[this._currentPageNumber - 1];
  3540. visible.push({ id: currentPage.id, view: currentPage });
  3541. return { first: currentPage, last: currentPage, views: visible };
  3542. }
  3543. },
  3544. cleanup: function () {
  3545. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3546. if (this._pages[i] &&
  3547. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  3548. this._pages[i].reset();
  3549. }
  3550. }
  3551. },
  3552. /**
  3553. * @param {PDFPageView} pageView
  3554. * @returns {PDFPage}
  3555. * @private
  3556. */
  3557. _ensurePdfPageLoaded: function (pageView) {
  3558. if (pageView.pdfPage) {
  3559. return Promise.resolve(pageView.pdfPage);
  3560. }
  3561. var pageNumber = pageView.id;
  3562. if (this._pagesRequests[pageNumber]) {
  3563. return this._pagesRequests[pageNumber];
  3564. }
  3565. var promise = this.pdfDocument.getPage(pageNumber).then(
  3566. function (pdfPage) {
  3567. pageView.setPdfPage(pdfPage);
  3568. this._pagesRequests[pageNumber] = null;
  3569. return pdfPage;
  3570. }.bind(this));
  3571. this._pagesRequests[pageNumber] = promise;
  3572. return promise;
  3573. },
  3574. forceRendering: function (currentlyVisiblePages) {
  3575. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  3576. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  3577. this._pages,
  3578. this.scroll.down);
  3579. if (pageView) {
  3580. this._ensurePdfPageLoaded(pageView).then(function () {
  3581. this.renderingQueue.renderView(pageView);
  3582. }.bind(this));
  3583. return true;
  3584. }
  3585. return false;
  3586. },
  3587. getPageTextContent: function (pageIndex) {
  3588. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  3589. return page.getTextContent({ normalizeWhitespace: true });
  3590. });
  3591. },
  3592. /**
  3593. * @param {HTMLDivElement} textLayerDiv
  3594. * @param {number} pageIndex
  3595. * @param {PageViewport} viewport
  3596. * @returns {TextLayerBuilder}
  3597. */
  3598. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  3599. return new TextLayerBuilder({
  3600. textLayerDiv: textLayerDiv,
  3601. eventBus: this.eventBus,
  3602. pageIndex: pageIndex,
  3603. viewport: viewport,
  3604. findController: this.isInPresentationMode ? null : this.findController
  3605. });
  3606. },
  3607. /**
  3608. * @param {HTMLDivElement} pageDiv
  3609. * @param {PDFPage} pdfPage
  3610. * @returns {AnnotationLayerBuilder}
  3611. */
  3612. createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
  3613. return new AnnotationLayerBuilder({
  3614. pageDiv: pageDiv,
  3615. pdfPage: pdfPage,
  3616. linkService: this.linkService,
  3617. downloadManager: this.downloadManager
  3618. });
  3619. },
  3620. setFindController: function (findController) {
  3621. this.findController = findController;
  3622. },
  3623. };
  3624. return PDFViewer;
  3625. })();
  3626. exports.PresentationModeState = PresentationModeState;
  3627. exports.PDFViewer = PDFViewer;
  3628. }));
  3629. }).call(pdfViewerLibs);
  3630. var PDFJS = pdfjsLib.PDFJS;
  3631. PDFJS.PDFViewer = pdfViewerLibs.pdfjsWebPDFViewer.PDFViewer;
  3632. PDFJS.PDFPageView = pdfViewerLibs.pdfjsWebPDFPageView.PDFPageView;
  3633. PDFJS.PDFLinkService = pdfViewerLibs.pdfjsWebPDFLinkService.PDFLinkService;
  3634. PDFJS.TextLayerBuilder =
  3635. pdfViewerLibs.pdfjsWebTextLayerBuilder.TextLayerBuilder;
  3636. PDFJS.DefaultTextLayerFactory =
  3637. pdfViewerLibs.pdfjsWebTextLayerBuilder.DefaultTextLayerFactory;
  3638. PDFJS.AnnotationLayerBuilder =
  3639. pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.AnnotationLayerBuilder;
  3640. PDFJS.DefaultAnnotationLayerFactory =
  3641. pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.DefaultAnnotationLayerFactory;
  3642. PDFJS.PDFHistory = pdfViewerLibs.pdfjsWebPDFHistory.PDFHistory;
  3643. PDFJS.PDFFindController =
  3644. pdfViewerLibs.pdfjsWebPDFFindController.PDFFindController;
  3645. PDFJS.EventBus = pdfViewerLibs.pdfjsWebUIUtils.EventBus;
  3646. PDFJS.DownloadManager = pdfViewerLibs.pdfjsWebDownloadManager.DownloadManager;
  3647. PDFJS.ProgressBar = pdfViewerLibs.pdfjsWebUIUtils.ProgressBar;
  3648. exports.PDFJS = PDFJS;
  3649. }));