pdf_viewer.js 124 KB

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