pdf_viewer.js 136 KB

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