pdf_viewer.js 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928
  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. */
  1206. initialize: function pdfHistoryInitialize(fingerprint) {
  1207. this.initialized = true;
  1208. this.reInitialized = false;
  1209. this.allowHashChange = true;
  1210. this.historyUnlocked = true;
  1211. this.isViewerInPresentationMode = false;
  1212. this.previousHash = window.location.hash.substring(1);
  1213. this.currentBookmark = '';
  1214. this.currentPage = 0;
  1215. this.updatePreviousBookmark = false;
  1216. this.previousBookmark = '';
  1217. this.previousPage = 0;
  1218. this.nextHashParam = '';
  1219. this.fingerprint = fingerprint;
  1220. this.currentUid = this.uid = 0;
  1221. this.current = {};
  1222. var state = window.history.state;
  1223. if (this._isStateObjectDefined(state)) {
  1224. // This corresponds to navigating back to the document
  1225. // from another page in the browser history.
  1226. if (state.target.dest) {
  1227. this.initialDestination = state.target.dest;
  1228. } else {
  1229. this.initialBookmark = state.target.hash;
  1230. }
  1231. this.currentUid = state.uid;
  1232. this.uid = state.uid + 1;
  1233. this.current = state.target;
  1234. } else {
  1235. // This corresponds to the loading of a new document.
  1236. if (state && state.fingerprint &&
  1237. this.fingerprint !== state.fingerprint) {
  1238. // Reinitialize the browsing history when a new document
  1239. // is opened in the web viewer.
  1240. this.reInitialized = true;
  1241. }
  1242. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  1243. }
  1244. var self = this;
  1245. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  1246. if (!self.historyUnlocked) {
  1247. return;
  1248. }
  1249. if (evt.state) {
  1250. // Move back/forward in the history.
  1251. self._goTo(evt.state);
  1252. return;
  1253. }
  1254. // If the state is not set, then the user tried to navigate to a
  1255. // different hash by manually editing the URL and pressing Enter, or by
  1256. // clicking on an in-page link (e.g. the "current view" link).
  1257. // Save the current view state to the browser history.
  1258. // Note: In Firefox, history.null could also be null after an in-page
  1259. // navigation to the same URL, and without dispatching the popstate
  1260. // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
  1261. if (self.uid === 0) {
  1262. // Replace the previous state if it was not explicitly set.
  1263. var previousParams = (self.previousHash && self.currentBookmark &&
  1264. self.previousHash !== self.currentBookmark) ?
  1265. {hash: self.currentBookmark, page: self.currentPage} :
  1266. {page: 1};
  1267. replacePreviousHistoryState(previousParams, function() {
  1268. updateHistoryWithCurrentHash();
  1269. });
  1270. } else {
  1271. updateHistoryWithCurrentHash();
  1272. }
  1273. }, false);
  1274. function updateHistoryWithCurrentHash() {
  1275. self.previousHash = window.location.hash.slice(1);
  1276. self._pushToHistory({hash: self.previousHash}, false, true);
  1277. self._updatePreviousBookmark();
  1278. }
  1279. function replacePreviousHistoryState(params, callback) {
  1280. // To modify the previous history entry, the following happens:
  1281. // 1. history.back()
  1282. // 2. _pushToHistory, which calls history.replaceState( ... )
  1283. // 3. history.forward()
  1284. // Because a navigation via the history API does not immediately update
  1285. // the history state, the popstate event is used for synchronization.
  1286. self.historyUnlocked = false;
  1287. // Suppress the hashchange event to avoid side effects caused by
  1288. // navigating back and forward.
  1289. self.allowHashChange = false;
  1290. window.addEventListener('popstate', rewriteHistoryAfterBack);
  1291. history.back();
  1292. function rewriteHistoryAfterBack() {
  1293. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  1294. window.addEventListener('popstate', rewriteHistoryAfterForward);
  1295. self._pushToHistory(params, false, true);
  1296. history.forward();
  1297. }
  1298. function rewriteHistoryAfterForward() {
  1299. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  1300. self.allowHashChange = true;
  1301. self.historyUnlocked = true;
  1302. callback();
  1303. }
  1304. }
  1305. function pdfHistoryBeforeUnload() {
  1306. var previousParams = self._getPreviousParams(null, true);
  1307. if (previousParams) {
  1308. var replacePrevious = (!self.current.dest &&
  1309. self.current.hash !== self.previousHash);
  1310. self._pushToHistory(previousParams, false, replacePrevious);
  1311. self._updatePreviousBookmark();
  1312. }
  1313. // Remove the event listener when navigating away from the document,
  1314. // since 'beforeunload' prevents Firefox from caching the document.
  1315. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  1316. false);
  1317. }
  1318. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1319. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  1320. // If the entire viewer (including the PDF file) is cached in
  1321. // the browser, we need to reattach the 'beforeunload' event listener
  1322. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  1323. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  1324. }, false);
  1325. self.eventBus.on('presentationmodechanged', function(e) {
  1326. self.isViewerInPresentationMode = e.active;
  1327. });
  1328. },
  1329. clearHistoryState: function pdfHistory_clearHistoryState() {
  1330. this._pushOrReplaceState(null, true);
  1331. },
  1332. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  1333. return (state && state.uid >= 0 &&
  1334. state.fingerprint && this.fingerprint === state.fingerprint &&
  1335. state.target && state.target.hash) ? true : false;
  1336. },
  1337. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  1338. replace) {
  1339. if (replace) {
  1340. window.history.replaceState(stateObj, '', document.URL);
  1341. } else {
  1342. window.history.pushState(stateObj, '', document.URL);
  1343. }
  1344. },
  1345. get isHashChangeUnlocked() {
  1346. if (!this.initialized) {
  1347. return true;
  1348. }
  1349. return this.allowHashChange;
  1350. },
  1351. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  1352. if (this.updatePreviousBookmark &&
  1353. this.currentBookmark && this.currentPage) {
  1354. this.previousBookmark = this.currentBookmark;
  1355. this.previousPage = this.currentPage;
  1356. this.updatePreviousBookmark = false;
  1357. }
  1358. },
  1359. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  1360. pageNum) {
  1361. if (this.initialized) {
  1362. this.currentBookmark = bookmark.substring(1);
  1363. this.currentPage = pageNum | 0;
  1364. this._updatePreviousBookmark();
  1365. }
  1366. },
  1367. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  1368. if (this.initialized) {
  1369. this.nextHashParam = param;
  1370. }
  1371. },
  1372. push: function pdfHistoryPush(params, isInitialBookmark) {
  1373. if (!(this.initialized && this.historyUnlocked)) {
  1374. return;
  1375. }
  1376. if (params.dest && !params.hash) {
  1377. params.hash = (this.current.hash && this.current.dest &&
  1378. this.current.dest === params.dest) ?
  1379. this.current.hash :
  1380. this.linkService.getDestinationHash(params.dest).split('#')[1];
  1381. }
  1382. if (params.page) {
  1383. params.page |= 0;
  1384. }
  1385. if (isInitialBookmark) {
  1386. var target = window.history.state.target;
  1387. if (!target) {
  1388. // Invoked when the user specifies an initial bookmark,
  1389. // thus setting initialBookmark, when the document is loaded.
  1390. this._pushToHistory(params, false);
  1391. this.previousHash = window.location.hash.substring(1);
  1392. }
  1393. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  1394. if (target) {
  1395. // If the current document is reloaded,
  1396. // avoid creating duplicate entries in the history.
  1397. this._updatePreviousBookmark();
  1398. }
  1399. return;
  1400. }
  1401. if (this.nextHashParam) {
  1402. if (this.nextHashParam === params.hash) {
  1403. this.nextHashParam = null;
  1404. this.updatePreviousBookmark = true;
  1405. return;
  1406. } else {
  1407. this.nextHashParam = null;
  1408. }
  1409. }
  1410. if (params.hash) {
  1411. if (this.current.hash) {
  1412. if (this.current.hash !== params.hash) {
  1413. this._pushToHistory(params, true);
  1414. } else {
  1415. if (!this.current.page && params.page) {
  1416. this._pushToHistory(params, false, true);
  1417. }
  1418. this.updatePreviousBookmark = true;
  1419. }
  1420. } else {
  1421. this._pushToHistory(params, true);
  1422. }
  1423. } else if (this.current.page && params.page &&
  1424. this.current.page !== params.page) {
  1425. this._pushToHistory(params, true);
  1426. }
  1427. },
  1428. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  1429. beforeUnload) {
  1430. if (!(this.currentBookmark && this.currentPage)) {
  1431. return null;
  1432. } else if (this.updatePreviousBookmark) {
  1433. this.updatePreviousBookmark = false;
  1434. }
  1435. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  1436. // Prevent the history from getting stuck in the current state,
  1437. // effectively preventing the user from going back/forward in
  1438. // the history.
  1439. //
  1440. // This happens if the current position in the document didn't change
  1441. // when the history was previously updated. The reasons for this are
  1442. // either:
  1443. // 1. The current zoom value is such that the document does not need to,
  1444. // or cannot, be scrolled to display the destination.
  1445. // 2. The previous destination is broken, and doesn't actally point to a
  1446. // position within the document.
  1447. // (This is either due to a bad PDF generator, or the user making a
  1448. // mistake when entering a destination in the hash parameters.)
  1449. return null;
  1450. }
  1451. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  1452. if (this.previousBookmark === this.currentBookmark) {
  1453. return null;
  1454. }
  1455. } else if (this.current.page || onlyCheckPage) {
  1456. if (this.previousPage === this.currentPage) {
  1457. return null;
  1458. }
  1459. } else {
  1460. return null;
  1461. }
  1462. var params = {hash: this.currentBookmark, page: this.currentPage};
  1463. if (this.isViewerInPresentationMode) {
  1464. params.hash = null;
  1465. }
  1466. return params;
  1467. },
  1468. _stateObj: function pdfHistory_stateObj(params) {
  1469. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  1470. },
  1471. _pushToHistory: function pdfHistory_pushToHistory(params,
  1472. addPrevious, overwrite) {
  1473. if (!this.initialized) {
  1474. return;
  1475. }
  1476. if (!params.hash && params.page) {
  1477. params.hash = ('page=' + params.page);
  1478. }
  1479. if (addPrevious && !overwrite) {
  1480. var previousParams = this._getPreviousParams();
  1481. if (previousParams) {
  1482. var replacePrevious = (!this.current.dest &&
  1483. this.current.hash !== this.previousHash);
  1484. this._pushToHistory(previousParams, false, replacePrevious);
  1485. }
  1486. }
  1487. this._pushOrReplaceState(this._stateObj(params),
  1488. (overwrite || this.uid === 0));
  1489. this.currentUid = this.uid++;
  1490. this.current = params;
  1491. this.updatePreviousBookmark = true;
  1492. },
  1493. _goTo: function pdfHistory_goTo(state) {
  1494. if (!(this.initialized && this.historyUnlocked &&
  1495. this._isStateObjectDefined(state))) {
  1496. return;
  1497. }
  1498. if (!this.reInitialized && state.uid < this.currentUid) {
  1499. var previousParams = this._getPreviousParams(true);
  1500. if (previousParams) {
  1501. this._pushToHistory(this.current, false);
  1502. this._pushToHistory(previousParams, false);
  1503. this.currentUid = state.uid;
  1504. window.history.back();
  1505. return;
  1506. }
  1507. }
  1508. this.historyUnlocked = false;
  1509. if (state.target.dest) {
  1510. this.linkService.navigateTo(state.target.dest);
  1511. } else {
  1512. this.linkService.setHash(state.target.hash);
  1513. }
  1514. this.currentUid = state.uid;
  1515. if (state.uid > this.uid) {
  1516. this.uid = state.uid;
  1517. }
  1518. this.current = state.target;
  1519. this.updatePreviousBookmark = true;
  1520. var currentHash = window.location.hash.substring(1);
  1521. if (this.previousHash !== currentHash) {
  1522. this.allowHashChange = false;
  1523. }
  1524. this.previousHash = currentHash;
  1525. this.historyUnlocked = true;
  1526. },
  1527. back: function pdfHistoryBack() {
  1528. this.go(-1);
  1529. },
  1530. forward: function pdfHistoryForward() {
  1531. this.go(1);
  1532. },
  1533. go: function pdfHistoryGo(direction) {
  1534. if (this.initialized && this.historyUnlocked) {
  1535. var state = window.history.state;
  1536. if (direction === -1 && state && state.uid > 0) {
  1537. window.history.back();
  1538. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  1539. window.history.forward();
  1540. }
  1541. }
  1542. }
  1543. };
  1544. exports.PDFHistory = PDFHistory;
  1545. }));
  1546. (function (root, factory) {
  1547. {
  1548. factory((root.pdfjsWebPDFLinkService = {}), root.pdfjsWebUIUtils,
  1549. root.pdfjsWebDOMEvents);
  1550. }
  1551. }(this, function (exports, uiUtils, domEvents) {
  1552. var parseQueryString = uiUtils.parseQueryString;
  1553. /**
  1554. * @typedef {Object} PDFLinkServiceOptions
  1555. * @property {EventBus} eventBus - The application event bus.
  1556. */
  1557. /**
  1558. * Performs navigation functions inside PDF, such as opening specified page,
  1559. * or destination.
  1560. * @class
  1561. * @implements {IPDFLinkService}
  1562. */
  1563. var PDFLinkService = (function () {
  1564. /**
  1565. * @constructs PDFLinkService
  1566. * @param {PDFLinkServiceOptions} options
  1567. */
  1568. function PDFLinkService(options) {
  1569. options = options || {};
  1570. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  1571. this.baseUrl = null;
  1572. this.pdfDocument = null;
  1573. this.pdfViewer = null;
  1574. this.pdfHistory = null;
  1575. this._pagesRefCache = null;
  1576. }
  1577. PDFLinkService.prototype = {
  1578. setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
  1579. this.baseUrl = baseUrl;
  1580. this.pdfDocument = pdfDocument;
  1581. this._pagesRefCache = Object.create(null);
  1582. },
  1583. setViewer: function PDFLinkService_setViewer(pdfViewer) {
  1584. this.pdfViewer = pdfViewer;
  1585. },
  1586. setHistory: function PDFLinkService_setHistory(pdfHistory) {
  1587. this.pdfHistory = pdfHistory;
  1588. },
  1589. /**
  1590. * @returns {number}
  1591. */
  1592. get pagesCount() {
  1593. return this.pdfDocument.numPages;
  1594. },
  1595. /**
  1596. * @returns {number}
  1597. */
  1598. get page() {
  1599. return this.pdfViewer.currentPageNumber;
  1600. },
  1601. /**
  1602. * @param {number} value
  1603. */
  1604. set page(value) {
  1605. this.pdfViewer.currentPageNumber = value;
  1606. },
  1607. /**
  1608. * @param dest - The PDF destination object.
  1609. */
  1610. navigateTo: function PDFLinkService_navigateTo(dest) {
  1611. var destString = '';
  1612. var self = this;
  1613. var goToDestination = function(destRef) {
  1614. // dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
  1615. var pageNumber = destRef instanceof Object ?
  1616. self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  1617. (destRef + 1);
  1618. if (pageNumber) {
  1619. if (pageNumber > self.pagesCount) {
  1620. pageNumber = self.pagesCount;
  1621. }
  1622. self.pdfViewer.scrollPageIntoView(pageNumber, dest);
  1623. if (self.pdfHistory) {
  1624. // Update the browsing history.
  1625. self.pdfHistory.push({
  1626. dest: dest,
  1627. hash: destString,
  1628. page: pageNumber
  1629. });
  1630. }
  1631. } else {
  1632. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  1633. var pageNum = pageIndex + 1;
  1634. var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
  1635. self._pagesRefCache[cacheKey] = pageNum;
  1636. goToDestination(destRef);
  1637. });
  1638. }
  1639. };
  1640. var destinationPromise;
  1641. if (typeof dest === 'string') {
  1642. destString = dest;
  1643. destinationPromise = this.pdfDocument.getDestination(dest);
  1644. } else {
  1645. destinationPromise = Promise.resolve(dest);
  1646. }
  1647. destinationPromise.then(function(destination) {
  1648. dest = destination;
  1649. if (!(destination instanceof Array)) {
  1650. return; // invalid destination
  1651. }
  1652. goToDestination(destination[0]);
  1653. });
  1654. },
  1655. /**
  1656. * @param dest - The PDF destination object.
  1657. * @returns {string} The hyperlink to the PDF object.
  1658. */
  1659. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  1660. if (typeof dest === 'string') {
  1661. return this.getAnchorUrl('#' + escape(dest));
  1662. }
  1663. if (dest instanceof Array) {
  1664. var destRef = dest[0]; // see navigateTo method for dest format
  1665. var pageNumber = destRef instanceof Object ?
  1666. this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  1667. (destRef + 1);
  1668. if (pageNumber) {
  1669. var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
  1670. var destKind = dest[1];
  1671. if (typeof destKind === 'object' && 'name' in destKind &&
  1672. destKind.name === 'XYZ') {
  1673. var scale = (dest[4] || this.pdfViewer.currentScaleValue);
  1674. var scaleNumber = parseFloat(scale);
  1675. if (scaleNumber) {
  1676. scale = scaleNumber * 100;
  1677. }
  1678. pdfOpenParams += '&zoom=' + scale;
  1679. if (dest[2] || dest[3]) {
  1680. pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
  1681. }
  1682. }
  1683. return pdfOpenParams;
  1684. }
  1685. }
  1686. return this.getAnchorUrl('');
  1687. },
  1688. /**
  1689. * Prefix the full url on anchor links to make sure that links are resolved
  1690. * relative to the current URL instead of the one defined in <base href>.
  1691. * @param {String} anchor The anchor hash, including the #.
  1692. * @returns {string} The hyperlink to the PDF object.
  1693. */
  1694. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  1695. return (this.baseUrl || '') + anchor;
  1696. },
  1697. /**
  1698. * @param {string} hash
  1699. */
  1700. setHash: function PDFLinkService_setHash(hash) {
  1701. if (hash.indexOf('=') >= 0) {
  1702. var params = parseQueryString(hash);
  1703. // borrowing syntax from "Parameters for Opening PDF Files"
  1704. if ('nameddest' in params) {
  1705. if (this.pdfHistory) {
  1706. this.pdfHistory.updateNextHashParam(params.nameddest);
  1707. }
  1708. this.navigateTo(params.nameddest);
  1709. return;
  1710. }
  1711. var pageNumber, dest;
  1712. if ('page' in params) {
  1713. pageNumber = (params.page | 0) || 1;
  1714. }
  1715. if ('zoom' in params) {
  1716. // Build the destination array.
  1717. var zoomArgs = params.zoom.split(','); // scale,left,top
  1718. var zoomArg = zoomArgs[0];
  1719. var zoomArgNumber = parseFloat(zoomArg);
  1720. if (zoomArg.indexOf('Fit') === -1) {
  1721. // If the zoomArg is a number, it has to get divided by 100. If it's
  1722. // a string, it should stay as it is.
  1723. dest = [null, { name: 'XYZ' },
  1724. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
  1725. zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
  1726. (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
  1727. } else {
  1728. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  1729. dest = [null, { name: zoomArg }];
  1730. } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
  1731. (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  1732. dest = [null, { name: zoomArg },
  1733. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
  1734. } else if (zoomArg === 'FitR') {
  1735. if (zoomArgs.length !== 5) {
  1736. console.error('PDFLinkService_setHash: ' +
  1737. 'Not enough parameters for \'FitR\'.');
  1738. } else {
  1739. dest = [null, { name: zoomArg },
  1740. (zoomArgs[1] | 0), (zoomArgs[2] | 0),
  1741. (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
  1742. }
  1743. } else {
  1744. console.error('PDFLinkService_setHash: \'' + zoomArg +
  1745. '\' is not a valid zoom value.');
  1746. }
  1747. }
  1748. }
  1749. if (dest) {
  1750. this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
  1751. } else if (pageNumber) {
  1752. this.page = pageNumber; // simple page
  1753. }
  1754. if ('pagemode' in params) {
  1755. this.eventBus.dispatch('pagemode', {
  1756. source: this,
  1757. mode: params.pagemode
  1758. });
  1759. }
  1760. } else if (/^\d+$/.test(hash)) { // page number
  1761. this.page = hash;
  1762. } else { // named destination
  1763. if (this.pdfHistory) {
  1764. this.pdfHistory.updateNextHashParam(unescape(hash));
  1765. }
  1766. this.navigateTo(unescape(hash));
  1767. }
  1768. },
  1769. /**
  1770. * @param {string} action
  1771. */
  1772. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  1773. // See PDF reference, table 8.45 - Named action
  1774. switch (action) {
  1775. case 'GoBack':
  1776. if (this.pdfHistory) {
  1777. this.pdfHistory.back();
  1778. }
  1779. break;
  1780. case 'GoForward':
  1781. if (this.pdfHistory) {
  1782. this.pdfHistory.forward();
  1783. }
  1784. break;
  1785. case 'NextPage':
  1786. this.page++;
  1787. break;
  1788. case 'PrevPage':
  1789. this.page--;
  1790. break;
  1791. case 'LastPage':
  1792. this.page = this.pagesCount;
  1793. break;
  1794. case 'FirstPage':
  1795. this.page = 1;
  1796. break;
  1797. default:
  1798. break; // No action according to spec
  1799. }
  1800. this.eventBus.dispatch('namedaction', {
  1801. source: this,
  1802. action: action
  1803. });
  1804. },
  1805. /**
  1806. * @param {number} pageNum - page number.
  1807. * @param {Object} pageRef - reference to the page.
  1808. */
  1809. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  1810. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  1811. this._pagesRefCache[refStr] = pageNum;
  1812. }
  1813. };
  1814. return PDFLinkService;
  1815. })();
  1816. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  1817. function SimpleLinkService() {}
  1818. SimpleLinkService.prototype = {
  1819. /**
  1820. * @returns {number}
  1821. */
  1822. get page() {
  1823. return 0;
  1824. },
  1825. /**
  1826. * @param {number} value
  1827. */
  1828. set page(value) {},
  1829. /**
  1830. * @param dest - The PDF destination object.
  1831. */
  1832. navigateTo: function (dest) {},
  1833. /**
  1834. * @param dest - The PDF destination object.
  1835. * @returns {string} The hyperlink to the PDF object.
  1836. */
  1837. getDestinationHash: function (dest) {
  1838. return '#';
  1839. },
  1840. /**
  1841. * @param hash - The PDF parameters/hash.
  1842. * @returns {string} The hyperlink to the PDF object.
  1843. */
  1844. getAnchorUrl: function (hash) {
  1845. return '#';
  1846. },
  1847. /**
  1848. * @param {string} hash
  1849. */
  1850. setHash: function (hash) {},
  1851. /**
  1852. * @param {string} action
  1853. */
  1854. executeNamedAction: function (action) {},
  1855. /**
  1856. * @param {number} pageNum - page number.
  1857. * @param {Object} pageRef - reference to the page.
  1858. */
  1859. cachePageRef: function (pageNum, pageRef) {}
  1860. };
  1861. return SimpleLinkService;
  1862. })();
  1863. exports.PDFLinkService = PDFLinkService;
  1864. exports.SimpleLinkService = SimpleLinkService;
  1865. }));
  1866. (function (root, factory) {
  1867. {
  1868. factory((root.pdfjsWebPDFPageView = {}), root.pdfjsWebUIUtils,
  1869. root.pdfjsWebPDFRenderingQueue, root.pdfjsWebDOMEvents,
  1870. root.pdfjsWebPDFJS);
  1871. }
  1872. }(this, function (exports, uiUtils, pdfRenderingQueue, domEvents, pdfjsLib) {
  1873. var CSS_UNITS = uiUtils.CSS_UNITS;
  1874. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  1875. var getOutputScale = uiUtils.getOutputScale;
  1876. var approximateFraction = uiUtils.approximateFraction;
  1877. var roundToDivide = uiUtils.roundToDivide;
  1878. var RenderingStates = pdfRenderingQueue.RenderingStates;
  1879. var TEXT_LAYER_RENDER_DELAY = 200; // ms
  1880. /**
  1881. * @typedef {Object} PDFPageViewOptions
  1882. * @property {HTMLDivElement} container - The viewer element.
  1883. * @property {EventBus} eventBus - The application event bus.
  1884. * @property {number} id - The page unique ID (normally its number).
  1885. * @property {number} scale - The page scale display.
  1886. * @property {PageViewport} defaultViewport - The page viewport.
  1887. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  1888. * @property {IPDFTextLayerFactory} textLayerFactory
  1889. * @property {IPDFAnnotationLayerFactory} annotationLayerFactory
  1890. */
  1891. /**
  1892. * @class
  1893. * @implements {IRenderableView}
  1894. */
  1895. var PDFPageView = (function PDFPageViewClosure() {
  1896. /**
  1897. * @constructs PDFPageView
  1898. * @param {PDFPageViewOptions} options
  1899. */
  1900. function PDFPageView(options) {
  1901. var container = options.container;
  1902. var id = options.id;
  1903. var scale = options.scale;
  1904. var defaultViewport = options.defaultViewport;
  1905. var renderingQueue = options.renderingQueue;
  1906. var textLayerFactory = options.textLayerFactory;
  1907. var annotationLayerFactory = options.annotationLayerFactory;
  1908. this.id = id;
  1909. this.renderingId = 'page' + id;
  1910. this.rotation = 0;
  1911. this.scale = scale || DEFAULT_SCALE;
  1912. this.viewport = defaultViewport;
  1913. this.pdfPageRotate = defaultViewport.rotation;
  1914. this.hasRestrictedScaling = false;
  1915. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  1916. this.renderingQueue = renderingQueue;
  1917. this.textLayerFactory = textLayerFactory;
  1918. this.annotationLayerFactory = annotationLayerFactory;
  1919. this.renderingState = RenderingStates.INITIAL;
  1920. this.resume = null;
  1921. this.onBeforeDraw = null;
  1922. this.onAfterDraw = null;
  1923. this.textLayer = null;
  1924. this.zoomLayer = null;
  1925. this.annotationLayer = null;
  1926. var div = document.createElement('div');
  1927. div.id = 'pageContainer' + this.id;
  1928. div.className = 'page';
  1929. div.style.width = Math.floor(this.viewport.width) + 'px';
  1930. div.style.height = Math.floor(this.viewport.height) + 'px';
  1931. div.setAttribute('data-page-number', this.id);
  1932. this.div = div;
  1933. container.appendChild(div);
  1934. }
  1935. PDFPageView.prototype = {
  1936. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  1937. this.pdfPage = pdfPage;
  1938. this.pdfPageRotate = pdfPage.rotate;
  1939. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  1940. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
  1941. totalRotation);
  1942. this.stats = pdfPage.stats;
  1943. this.reset();
  1944. },
  1945. destroy: function PDFPageView_destroy() {
  1946. this.zoomLayer = null;
  1947. this.reset();
  1948. if (this.pdfPage) {
  1949. this.pdfPage.cleanup();
  1950. }
  1951. },
  1952. reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
  1953. if (this.renderTask) {
  1954. this.renderTask.cancel();
  1955. }
  1956. this.resume = null;
  1957. this.renderingState = RenderingStates.INITIAL;
  1958. var div = this.div;
  1959. div.style.width = Math.floor(this.viewport.width) + 'px';
  1960. div.style.height = Math.floor(this.viewport.height) + 'px';
  1961. var childNodes = div.childNodes;
  1962. var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
  1963. var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
  1964. this.annotationLayer.div) || null;
  1965. for (var i = childNodes.length - 1; i >= 0; i--) {
  1966. var node = childNodes[i];
  1967. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  1968. continue;
  1969. }
  1970. div.removeChild(node);
  1971. }
  1972. div.removeAttribute('data-loaded');
  1973. if (currentAnnotationNode) {
  1974. // Hide annotationLayer until all elements are resized
  1975. // so they are not displayed on the already-resized page
  1976. this.annotationLayer.hide();
  1977. } else {
  1978. this.annotationLayer = null;
  1979. }
  1980. if (this.canvas && !currentZoomLayerNode) {
  1981. // Zeroing the width and height causes Firefox to release graphics
  1982. // resources immediately, which can greatly reduce memory consumption.
  1983. this.canvas.width = 0;
  1984. this.canvas.height = 0;
  1985. delete this.canvas;
  1986. }
  1987. this.loadingIconDiv = document.createElement('div');
  1988. this.loadingIconDiv.className = 'loadingIcon';
  1989. div.appendChild(this.loadingIconDiv);
  1990. },
  1991. update: function PDFPageView_update(scale, rotation) {
  1992. this.scale = scale || this.scale;
  1993. if (typeof rotation !== 'undefined') {
  1994. this.rotation = rotation;
  1995. }
  1996. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  1997. this.viewport = this.viewport.clone({
  1998. scale: this.scale * CSS_UNITS,
  1999. rotation: totalRotation
  2000. });
  2001. var isScalingRestricted = false;
  2002. if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2003. var outputScale = this.outputScale;
  2004. var pixelsInViewport = this.viewport.width * this.viewport.height;
  2005. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  2006. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  2007. pdfjsLib.PDFJS.maxCanvasPixels) {
  2008. isScalingRestricted = true;
  2009. }
  2010. }
  2011. if (this.canvas) {
  2012. if (pdfjsLib.PDFJS.useOnlyCssZoom ||
  2013. (this.hasRestrictedScaling && isScalingRestricted)) {
  2014. this.cssTransform(this.canvas, true);
  2015. this.eventBus.dispatch('pagerendered', {
  2016. source: this,
  2017. pageNumber: this.id,
  2018. cssTransform: true,
  2019. });
  2020. return;
  2021. }
  2022. if (!this.zoomLayer) {
  2023. this.zoomLayer = this.canvas.parentNode;
  2024. this.zoomLayer.style.position = 'absolute';
  2025. }
  2026. }
  2027. if (this.zoomLayer) {
  2028. this.cssTransform(this.zoomLayer.firstChild);
  2029. }
  2030. this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
  2031. },
  2032. /**
  2033. * Called when moved in the parent's container.
  2034. */
  2035. updatePosition: function PDFPageView_updatePosition() {
  2036. if (this.textLayer) {
  2037. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2038. }
  2039. },
  2040. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  2041. var CustomStyle = pdfjsLib.CustomStyle;
  2042. // Scale canvas, canvas wrapper, and page container.
  2043. var width = this.viewport.width;
  2044. var height = this.viewport.height;
  2045. var div = this.div;
  2046. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  2047. Math.floor(width) + 'px';
  2048. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  2049. Math.floor(height) + 'px';
  2050. // The canvas may have been originally rotated, rotate relative to that.
  2051. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  2052. var absRotation = Math.abs(relativeRotation);
  2053. var scaleX = 1, scaleY = 1;
  2054. if (absRotation === 90 || absRotation === 270) {
  2055. // Scale x and y because of the rotation.
  2056. scaleX = height / width;
  2057. scaleY = width / height;
  2058. }
  2059. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  2060. 'scale(' + scaleX + ',' + scaleY + ')';
  2061. CustomStyle.setProp('transform', canvas, cssTransform);
  2062. if (this.textLayer) {
  2063. // Rotating the text layer is more complicated since the divs inside the
  2064. // the text layer are rotated.
  2065. // TODO: This could probably be simplified by drawing the text layer in
  2066. // one orientation then rotating overall.
  2067. var textLayerViewport = this.textLayer.viewport;
  2068. var textRelativeRotation = this.viewport.rotation -
  2069. textLayerViewport.rotation;
  2070. var textAbsRotation = Math.abs(textRelativeRotation);
  2071. var scale = width / textLayerViewport.width;
  2072. if (textAbsRotation === 90 || textAbsRotation === 270) {
  2073. scale = width / textLayerViewport.height;
  2074. }
  2075. var textLayerDiv = this.textLayer.textLayerDiv;
  2076. var transX, transY;
  2077. switch (textAbsRotation) {
  2078. case 0:
  2079. transX = transY = 0;
  2080. break;
  2081. case 90:
  2082. transX = 0;
  2083. transY = '-' + textLayerDiv.style.height;
  2084. break;
  2085. case 180:
  2086. transX = '-' + textLayerDiv.style.width;
  2087. transY = '-' + textLayerDiv.style.height;
  2088. break;
  2089. case 270:
  2090. transX = '-' + textLayerDiv.style.width;
  2091. transY = 0;
  2092. break;
  2093. default:
  2094. console.error('Bad rotation value.');
  2095. break;
  2096. }
  2097. CustomStyle.setProp('transform', textLayerDiv,
  2098. 'rotate(' + textAbsRotation + 'deg) ' +
  2099. 'scale(' + scale + ', ' + scale + ') ' +
  2100. 'translate(' + transX + ', ' + transY + ')');
  2101. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  2102. }
  2103. if (redrawAnnotations && this.annotationLayer) {
  2104. this.annotationLayer.render(this.viewport, 'display');
  2105. }
  2106. },
  2107. get width() {
  2108. return this.viewport.width;
  2109. },
  2110. get height() {
  2111. return this.viewport.height;
  2112. },
  2113. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  2114. return this.viewport.convertToPdfPoint(x, y);
  2115. },
  2116. draw: function PDFPageView_draw() {
  2117. if (this.renderingState !== RenderingStates.INITIAL) {
  2118. console.error('Must be in new state before drawing');
  2119. }
  2120. this.renderingState = RenderingStates.RUNNING;
  2121. var pdfPage = this.pdfPage;
  2122. var viewport = this.viewport;
  2123. var div = this.div;
  2124. // Wrap the canvas so if it has a css transform for highdpi the overflow
  2125. // will be hidden in FF.
  2126. var canvasWrapper = document.createElement('div');
  2127. canvasWrapper.style.width = div.style.width;
  2128. canvasWrapper.style.height = div.style.height;
  2129. canvasWrapper.classList.add('canvasWrapper');
  2130. var canvas = document.createElement('canvas');
  2131. canvas.id = 'page' + this.id;
  2132. // Keep the canvas hidden until the first draw callback, or until drawing
  2133. // is complete when `!this.renderingQueue`, to prevent black flickering.
  2134. canvas.setAttribute('hidden', 'hidden');
  2135. var isCanvasHidden = true;
  2136. canvasWrapper.appendChild(canvas);
  2137. if (this.annotationLayer && this.annotationLayer.div) {
  2138. // annotationLayer needs to stay on top
  2139. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  2140. } else {
  2141. div.appendChild(canvasWrapper);
  2142. }
  2143. this.canvas = canvas;
  2144. canvas.mozOpaque = true;
  2145. var ctx = canvas.getContext('2d', {alpha: false});
  2146. var outputScale = getOutputScale(ctx);
  2147. this.outputScale = outputScale;
  2148. if (pdfjsLib.PDFJS.useOnlyCssZoom) {
  2149. var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
  2150. // Use a scale that will make the canvas be the original intended size
  2151. // of the page.
  2152. outputScale.sx *= actualSizeViewport.width / viewport.width;
  2153. outputScale.sy *= actualSizeViewport.height / viewport.height;
  2154. outputScale.scaled = true;
  2155. }
  2156. if (pdfjsLib.PDFJS.maxCanvasPixels > 0) {
  2157. var pixelsInViewport = viewport.width * viewport.height;
  2158. var maxScale =
  2159. Math.sqrt(pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport);
  2160. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  2161. outputScale.sx = maxScale;
  2162. outputScale.sy = maxScale;
  2163. outputScale.scaled = true;
  2164. this.hasRestrictedScaling = true;
  2165. } else {
  2166. this.hasRestrictedScaling = false;
  2167. }
  2168. }
  2169. var sfx = approximateFraction(outputScale.sx);
  2170. var sfy = approximateFraction(outputScale.sy);
  2171. canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
  2172. canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
  2173. canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
  2174. canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
  2175. // Add the viewport so it's known what it was originally drawn with.
  2176. canvas._viewport = viewport;
  2177. var textLayerDiv = null;
  2178. var textLayer = null;
  2179. if (this.textLayerFactory) {
  2180. textLayerDiv = document.createElement('div');
  2181. textLayerDiv.className = 'textLayer';
  2182. textLayerDiv.style.width = canvasWrapper.style.width;
  2183. textLayerDiv.style.height = canvasWrapper.style.height;
  2184. if (this.annotationLayer && this.annotationLayer.div) {
  2185. // annotationLayer needs to stay on top
  2186. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  2187. } else {
  2188. div.appendChild(textLayerDiv);
  2189. }
  2190. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
  2191. this.id - 1,
  2192. this.viewport);
  2193. }
  2194. this.textLayer = textLayer;
  2195. var resolveRenderPromise, rejectRenderPromise;
  2196. var promise = new Promise(function (resolve, reject) {
  2197. resolveRenderPromise = resolve;
  2198. rejectRenderPromise = reject;
  2199. });
  2200. // Rendering area
  2201. var self = this;
  2202. function pageViewDrawCallback(error) {
  2203. // The renderTask may have been replaced by a new one, so only remove
  2204. // the reference to the renderTask if it matches the one that is
  2205. // triggering this callback.
  2206. if (renderTask === self.renderTask) {
  2207. self.renderTask = null;
  2208. }
  2209. if (error === 'cancelled') {
  2210. rejectRenderPromise(error);
  2211. return;
  2212. }
  2213. self.renderingState = RenderingStates.FINISHED;
  2214. if (isCanvasHidden) {
  2215. self.canvas.removeAttribute('hidden');
  2216. isCanvasHidden = false;
  2217. }
  2218. if (self.loadingIconDiv) {
  2219. div.removeChild(self.loadingIconDiv);
  2220. delete self.loadingIconDiv;
  2221. }
  2222. if (self.zoomLayer) {
  2223. // Zeroing the width and height causes Firefox to release graphics
  2224. // resources immediately, which can greatly reduce memory consumption.
  2225. var zoomLayerCanvas = self.zoomLayer.firstChild;
  2226. zoomLayerCanvas.width = 0;
  2227. zoomLayerCanvas.height = 0;
  2228. if (div.contains(self.zoomLayer)) {
  2229. // Prevent "Node was not found" errors if the `zoomLayer` was
  2230. // already removed. This may occur intermittently if the scale
  2231. // changes many times in very quick succession.
  2232. div.removeChild(self.zoomLayer);
  2233. }
  2234. self.zoomLayer = null;
  2235. }
  2236. self.error = error;
  2237. self.stats = pdfPage.stats;
  2238. if (self.onAfterDraw) {
  2239. self.onAfterDraw();
  2240. }
  2241. self.eventBus.dispatch('pagerendered', {
  2242. source: self,
  2243. pageNumber: self.id,
  2244. cssTransform: false,
  2245. });
  2246. if (!error) {
  2247. resolveRenderPromise(undefined);
  2248. } else {
  2249. rejectRenderPromise(error);
  2250. }
  2251. }
  2252. var renderContinueCallback = null;
  2253. if (this.renderingQueue) {
  2254. renderContinueCallback = function renderContinueCallback(cont) {
  2255. if (!self.renderingQueue.isHighestPriority(self)) {
  2256. self.renderingState = RenderingStates.PAUSED;
  2257. self.resume = function resumeCallback() {
  2258. self.renderingState = RenderingStates.RUNNING;
  2259. cont();
  2260. };
  2261. return;
  2262. }
  2263. if (isCanvasHidden) {
  2264. self.canvas.removeAttribute('hidden');
  2265. isCanvasHidden = false;
  2266. }
  2267. cont();
  2268. };
  2269. }
  2270. var transform = !outputScale.scaled ? null :
  2271. [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  2272. var renderContext = {
  2273. canvasContext: ctx,
  2274. transform: transform,
  2275. viewport: this.viewport,
  2276. // intent: 'default', // === 'display'
  2277. };
  2278. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  2279. renderTask.onContinue = renderContinueCallback;
  2280. this.renderTask.promise.then(
  2281. function pdfPageRenderCallback() {
  2282. pageViewDrawCallback(null);
  2283. if (textLayer) {
  2284. self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(
  2285. function textContentResolved(textContent) {
  2286. textLayer.setTextContent(textContent);
  2287. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  2288. }
  2289. );
  2290. }
  2291. },
  2292. function pdfPageRenderError(error) {
  2293. pageViewDrawCallback(error);
  2294. }
  2295. );
  2296. if (this.annotationLayerFactory) {
  2297. if (!this.annotationLayer) {
  2298. this.annotationLayer = this.annotationLayerFactory.
  2299. createAnnotationLayerBuilder(div, this.pdfPage);
  2300. }
  2301. this.annotationLayer.render(this.viewport, 'display');
  2302. }
  2303. div.setAttribute('data-loaded', true);
  2304. if (self.onBeforeDraw) {
  2305. self.onBeforeDraw();
  2306. }
  2307. return promise;
  2308. },
  2309. beforePrint: function PDFPageView_beforePrint(printContainer) {
  2310. var CustomStyle = pdfjsLib.CustomStyle;
  2311. var pdfPage = this.pdfPage;
  2312. var viewport = pdfPage.getViewport(1);
  2313. // Use the same hack we use for high dpi displays for printing to get
  2314. // better output until bug 811002 is fixed in FF.
  2315. var PRINT_OUTPUT_SCALE = 2;
  2316. var canvas = document.createElement('canvas');
  2317. // The logical size of the canvas.
  2318. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  2319. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  2320. // The rendered size of the canvas, relative to the size of canvasWrapper.
  2321. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
  2322. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  2323. (1 / PRINT_OUTPUT_SCALE) + ')';
  2324. CustomStyle.setProp('transform' , canvas, cssScale);
  2325. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  2326. var canvasWrapper = document.createElement('div');
  2327. canvasWrapper.appendChild(canvas);
  2328. printContainer.appendChild(canvasWrapper);
  2329. canvas.mozPrintCallback = function(obj) {
  2330. var ctx = obj.context;
  2331. ctx.save();
  2332. ctx.fillStyle = 'rgb(255, 255, 255)';
  2333. ctx.fillRect(0, 0, canvas.width, canvas.height);
  2334. ctx.restore();
  2335. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  2336. ctx._transformMatrix =
  2337. [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
  2338. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  2339. var renderContext = {
  2340. canvasContext: ctx,
  2341. viewport: viewport,
  2342. intent: 'print'
  2343. };
  2344. pdfPage.render(renderContext).promise.then(function() {
  2345. // Tell the printEngine that rendering this canvas/page has finished.
  2346. obj.done();
  2347. }, function(error) {
  2348. console.error(error);
  2349. // Tell the printEngine that rendering this canvas/page has failed.
  2350. // This will make the print proces stop.
  2351. if ('abort' in obj) {
  2352. obj.abort();
  2353. } else {
  2354. obj.done();
  2355. }
  2356. });
  2357. };
  2358. },
  2359. };
  2360. return PDFPageView;
  2361. })();
  2362. exports.PDFPageView = PDFPageView;
  2363. }));
  2364. (function (root, factory) {
  2365. {
  2366. factory((root.pdfjsWebTextLayerBuilder = {}), root.pdfjsWebDOMEvents,
  2367. root.pdfjsWebPDFJS);
  2368. }
  2369. }(this, function (exports, domEvents, pdfjsLib) {
  2370. /**
  2371. * @typedef {Object} TextLayerBuilderOptions
  2372. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  2373. * @property {EventBus} eventBus - The application event bus.
  2374. * @property {number} pageIndex - The page index.
  2375. * @property {PageViewport} viewport - The viewport of the text layer.
  2376. * @property {PDFFindController} findController
  2377. */
  2378. /**
  2379. * TextLayerBuilder provides text-selection functionality for the PDF.
  2380. * It does this by creating overlay divs over the PDF text. These divs
  2381. * contain text that matches the PDF text they are overlaying. This object
  2382. * also provides a way to highlight text that is being searched for.
  2383. * @class
  2384. */
  2385. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  2386. function TextLayerBuilder(options) {
  2387. this.textLayerDiv = options.textLayerDiv;
  2388. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2389. this.renderingDone = false;
  2390. this.divContentDone = false;
  2391. this.pageIdx = options.pageIndex;
  2392. this.pageNumber = this.pageIdx + 1;
  2393. this.matches = [];
  2394. this.viewport = options.viewport;
  2395. this.textDivs = [];
  2396. this.findController = options.findController || null;
  2397. this.textLayerRenderTask = null;
  2398. this._bindMouse();
  2399. }
  2400. TextLayerBuilder.prototype = {
  2401. _finishRendering: function TextLayerBuilder_finishRendering() {
  2402. this.renderingDone = true;
  2403. var endOfContent = document.createElement('div');
  2404. endOfContent.className = 'endOfContent';
  2405. this.textLayerDiv.appendChild(endOfContent);
  2406. this.eventBus.dispatch('textlayerrendered', {
  2407. source: this,
  2408. pageNumber: this.pageNumber
  2409. });
  2410. },
  2411. /**
  2412. * Renders the text layer.
  2413. * @param {number} timeout (optional) if specified, the rendering waits
  2414. * for specified amount of ms.
  2415. */
  2416. render: function TextLayerBuilder_render(timeout) {
  2417. if (!this.divContentDone || this.renderingDone) {
  2418. return;
  2419. }
  2420. if (this.textLayerRenderTask) {
  2421. this.textLayerRenderTask.cancel();
  2422. this.textLayerRenderTask = null;
  2423. }
  2424. this.textDivs = [];
  2425. var textLayerFrag = document.createDocumentFragment();
  2426. this.textLayerRenderTask = pdfjsLib.renderTextLayer({
  2427. textContent: this.textContent,
  2428. container: textLayerFrag,
  2429. viewport: this.viewport,
  2430. textDivs: this.textDivs,
  2431. timeout: timeout
  2432. });
  2433. this.textLayerRenderTask.promise.then(function () {
  2434. this.textLayerDiv.appendChild(textLayerFrag);
  2435. this._finishRendering();
  2436. this.updateMatches();
  2437. }.bind(this), function (reason) {
  2438. // canceled or failed to render text layer -- skipping errors
  2439. });
  2440. },
  2441. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  2442. if (this.textLayerRenderTask) {
  2443. this.textLayerRenderTask.cancel();
  2444. this.textLayerRenderTask = null;
  2445. }
  2446. this.textContent = textContent;
  2447. this.divContentDone = true;
  2448. },
  2449. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  2450. var i = 0;
  2451. var iIndex = 0;
  2452. var bidiTexts = this.textContent.items;
  2453. var end = bidiTexts.length - 1;
  2454. var queryLen = (this.findController === null ?
  2455. 0 : this.findController.state.query.length);
  2456. var ret = [];
  2457. for (var m = 0, len = matches.length; m < len; m++) {
  2458. // Calculate the start position.
  2459. var matchIdx = matches[m];
  2460. // Loop over the divIdxs.
  2461. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  2462. iIndex += bidiTexts[i].str.length;
  2463. i++;
  2464. }
  2465. if (i === bidiTexts.length) {
  2466. console.error('Could not find a matching mapping');
  2467. }
  2468. var match = {
  2469. begin: {
  2470. divIdx: i,
  2471. offset: matchIdx - iIndex
  2472. }
  2473. };
  2474. // Calculate the end position.
  2475. matchIdx += queryLen;
  2476. // Somewhat the same array as above, but use > instead of >= to get
  2477. // the end position right.
  2478. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  2479. iIndex += bidiTexts[i].str.length;
  2480. i++;
  2481. }
  2482. match.end = {
  2483. divIdx: i,
  2484. offset: matchIdx - iIndex
  2485. };
  2486. ret.push(match);
  2487. }
  2488. return ret;
  2489. },
  2490. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  2491. // Early exit if there is nothing to render.
  2492. if (matches.length === 0) {
  2493. return;
  2494. }
  2495. var bidiTexts = this.textContent.items;
  2496. var textDivs = this.textDivs;
  2497. var prevEnd = null;
  2498. var pageIdx = this.pageIdx;
  2499. var isSelectedPage = (this.findController === null ?
  2500. false : (pageIdx === this.findController.selected.pageIdx));
  2501. var selectedMatchIdx = (this.findController === null ?
  2502. -1 : this.findController.selected.matchIdx);
  2503. var highlightAll = (this.findController === null ?
  2504. false : this.findController.state.highlightAll);
  2505. var infinity = {
  2506. divIdx: -1,
  2507. offset: undefined
  2508. };
  2509. function beginText(begin, className) {
  2510. var divIdx = begin.divIdx;
  2511. textDivs[divIdx].textContent = '';
  2512. appendTextToDiv(divIdx, 0, begin.offset, className);
  2513. }
  2514. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  2515. var div = textDivs[divIdx];
  2516. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  2517. var node = document.createTextNode(content);
  2518. if (className) {
  2519. var span = document.createElement('span');
  2520. span.className = className;
  2521. span.appendChild(node);
  2522. div.appendChild(span);
  2523. return;
  2524. }
  2525. div.appendChild(node);
  2526. }
  2527. var i0 = selectedMatchIdx, i1 = i0 + 1;
  2528. if (highlightAll) {
  2529. i0 = 0;
  2530. i1 = matches.length;
  2531. } else if (!isSelectedPage) {
  2532. // Not highlighting all and this isn't the selected page, so do nothing.
  2533. return;
  2534. }
  2535. for (var i = i0; i < i1; i++) {
  2536. var match = matches[i];
  2537. var begin = match.begin;
  2538. var end = match.end;
  2539. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  2540. var highlightSuffix = (isSelected ? ' selected' : '');
  2541. if (this.findController) {
  2542. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  2543. begin.divIdx, end.divIdx);
  2544. }
  2545. // Match inside new div.
  2546. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  2547. // If there was a previous div, then add the text at the end.
  2548. if (prevEnd !== null) {
  2549. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2550. }
  2551. // Clear the divs and set the content until the starting point.
  2552. beginText(begin);
  2553. } else {
  2554. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  2555. }
  2556. if (begin.divIdx === end.divIdx) {
  2557. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  2558. 'highlight' + highlightSuffix);
  2559. } else {
  2560. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  2561. 'highlight begin' + highlightSuffix);
  2562. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  2563. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  2564. }
  2565. beginText(end, 'highlight end' + highlightSuffix);
  2566. }
  2567. prevEnd = end;
  2568. }
  2569. if (prevEnd) {
  2570. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  2571. }
  2572. },
  2573. updateMatches: function TextLayerBuilder_updateMatches() {
  2574. // Only show matches when all rendering is done.
  2575. if (!this.renderingDone) {
  2576. return;
  2577. }
  2578. // Clear all matches.
  2579. var matches = this.matches;
  2580. var textDivs = this.textDivs;
  2581. var bidiTexts = this.textContent.items;
  2582. var clearedUntilDivIdx = -1;
  2583. // Clear all current matches.
  2584. for (var i = 0, len = matches.length; i < len; i++) {
  2585. var match = matches[i];
  2586. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  2587. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  2588. var div = textDivs[n];
  2589. div.textContent = bidiTexts[n].str;
  2590. div.className = '';
  2591. }
  2592. clearedUntilDivIdx = match.end.divIdx + 1;
  2593. }
  2594. if (this.findController === null || !this.findController.active) {
  2595. return;
  2596. }
  2597. // Convert the matches on the page controller into the match format
  2598. // used for the textLayer.
  2599. this.matches = this.convertMatches(this.findController === null ?
  2600. [] : (this.findController.pageMatches[this.pageIdx] || []));
  2601. this.renderMatches(this.matches);
  2602. },
  2603. /**
  2604. * Fixes text selection: adds additional div where mouse was clicked.
  2605. * This reduces flickering of the content if mouse slowly dragged down/up.
  2606. * @private
  2607. */
  2608. _bindMouse: function TextLayerBuilder_bindMouse() {
  2609. var div = this.textLayerDiv;
  2610. div.addEventListener('mousedown', function (e) {
  2611. var end = div.querySelector('.endOfContent');
  2612. if (!end) {
  2613. return;
  2614. }
  2615. // On non-Firefox browsers, the selection will feel better if the height
  2616. // of the endOfContent div will be adjusted to start at mouse click
  2617. // location -- this will avoid flickering when selections moves up.
  2618. // However it does not work when selection started on empty space.
  2619. var adjustTop = e.target !== div;
  2620. adjustTop = adjustTop && window.getComputedStyle(end).
  2621. getPropertyValue('-moz-user-select') !== 'none';
  2622. if (adjustTop) {
  2623. var divBounds = div.getBoundingClientRect();
  2624. var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
  2625. end.style.top = (r * 100).toFixed(2) + '%';
  2626. }
  2627. end.classList.add('active');
  2628. });
  2629. div.addEventListener('mouseup', function (e) {
  2630. var end = div.querySelector('.endOfContent');
  2631. if (!end) {
  2632. return;
  2633. }
  2634. end.style.top = '';
  2635. end.classList.remove('active');
  2636. });
  2637. },
  2638. };
  2639. return TextLayerBuilder;
  2640. })();
  2641. /**
  2642. * @constructor
  2643. * @implements IPDFTextLayerFactory
  2644. */
  2645. function DefaultTextLayerFactory() {}
  2646. DefaultTextLayerFactory.prototype = {
  2647. /**
  2648. * @param {HTMLDivElement} textLayerDiv
  2649. * @param {number} pageIndex
  2650. * @param {PageViewport} viewport
  2651. * @returns {TextLayerBuilder}
  2652. */
  2653. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  2654. return new TextLayerBuilder({
  2655. textLayerDiv: textLayerDiv,
  2656. pageIndex: pageIndex,
  2657. viewport: viewport
  2658. });
  2659. }
  2660. };
  2661. exports.TextLayerBuilder = TextLayerBuilder;
  2662. exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2663. }));
  2664. (function (root, factory) {
  2665. {
  2666. factory((root.pdfjsWebAnnotationLayerBuilder = {}), root.pdfjsWebUIUtils,
  2667. root.pdfjsWebPDFLinkService, root.pdfjsWebPDFJS);
  2668. }
  2669. }(this, function (exports, uiUtils, pdfLinkService, pdfjsLib) {
  2670. var mozL10n = uiUtils.mozL10n;
  2671. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2672. /**
  2673. * @typedef {Object} AnnotationLayerBuilderOptions
  2674. * @property {HTMLDivElement} pageDiv
  2675. * @property {PDFPage} pdfPage
  2676. * @property {IPDFLinkService} linkService
  2677. * @property {DownloadManager} downloadManager
  2678. */
  2679. /**
  2680. * @class
  2681. */
  2682. var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
  2683. /**
  2684. * @param {AnnotationLayerBuilderOptions} options
  2685. * @constructs AnnotationLayerBuilder
  2686. */
  2687. function AnnotationLayerBuilder(options) {
  2688. this.pageDiv = options.pageDiv;
  2689. this.pdfPage = options.pdfPage;
  2690. this.linkService = options.linkService;
  2691. this.downloadManager = options.downloadManager;
  2692. this.div = null;
  2693. }
  2694. AnnotationLayerBuilder.prototype =
  2695. /** @lends AnnotationLayerBuilder.prototype */ {
  2696. /**
  2697. * @param {PageViewport} viewport
  2698. * @param {string} intent (default value is 'display')
  2699. */
  2700. render: function AnnotationLayerBuilder_render(viewport, intent) {
  2701. var self = this;
  2702. var parameters = {
  2703. intent: (intent === undefined ? 'display' : intent),
  2704. };
  2705. this.pdfPage.getAnnotations(parameters).then(function (annotations) {
  2706. viewport = viewport.clone({ dontFlip: true });
  2707. parameters = {
  2708. viewport: viewport,
  2709. div: self.div,
  2710. annotations: annotations,
  2711. page: self.pdfPage,
  2712. linkService: self.linkService,
  2713. downloadManager: self.downloadManager
  2714. };
  2715. if (self.div) {
  2716. // If an annotationLayer already exists, refresh its children's
  2717. // transformation matrices.
  2718. pdfjsLib.AnnotationLayer.update(parameters);
  2719. } else {
  2720. // Create an annotation layer div and render the annotations
  2721. // if there is at least one annotation.
  2722. if (annotations.length === 0) {
  2723. return;
  2724. }
  2725. self.div = document.createElement('div');
  2726. self.div.className = 'annotationLayer';
  2727. self.pageDiv.appendChild(self.div);
  2728. parameters.div = self.div;
  2729. pdfjsLib.AnnotationLayer.render(parameters);
  2730. if (typeof mozL10n !== 'undefined') {
  2731. mozL10n.translate(self.div);
  2732. }
  2733. }
  2734. });
  2735. },
  2736. hide: function AnnotationLayerBuilder_hide() {
  2737. if (!this.div) {
  2738. return;
  2739. }
  2740. this.div.setAttribute('hidden', 'true');
  2741. }
  2742. };
  2743. return AnnotationLayerBuilder;
  2744. })();
  2745. /**
  2746. * @constructor
  2747. * @implements IPDFAnnotationLayerFactory
  2748. */
  2749. function DefaultAnnotationLayerFactory() {}
  2750. DefaultAnnotationLayerFactory.prototype = {
  2751. /**
  2752. * @param {HTMLDivElement} pageDiv
  2753. * @param {PDFPage} pdfPage
  2754. * @returns {AnnotationLayerBuilder}
  2755. */
  2756. createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
  2757. return new AnnotationLayerBuilder({
  2758. pageDiv: pageDiv,
  2759. pdfPage: pdfPage,
  2760. linkService: new SimpleLinkService(),
  2761. });
  2762. }
  2763. };
  2764. exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
  2765. exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
  2766. }));
  2767. (function (root, factory) {
  2768. {
  2769. factory((root.pdfjsWebPDFViewer = {}), root.pdfjsWebUIUtils,
  2770. root.pdfjsWebPDFPageView, root.pdfjsWebPDFRenderingQueue,
  2771. root.pdfjsWebTextLayerBuilder, root.pdfjsWebAnnotationLayerBuilder,
  2772. root.pdfjsWebPDFLinkService, root.pdfjsWebDOMEvents, root.pdfjsWebPDFJS);
  2773. }
  2774. }(this, function (exports, uiUtils, pdfPageView, pdfRenderingQueue,
  2775. textLayerBuilder, annotationLayerBuilder, pdfLinkService,
  2776. domEvents, pdfjsLib) {
  2777. var UNKNOWN_SCALE = uiUtils.UNKNOWN_SCALE;
  2778. var SCROLLBAR_PADDING = uiUtils.SCROLLBAR_PADDING;
  2779. var VERTICAL_PADDING = uiUtils.VERTICAL_PADDING;
  2780. var MAX_AUTO_SCALE = uiUtils.MAX_AUTO_SCALE;
  2781. var CSS_UNITS = uiUtils.CSS_UNITS;
  2782. var DEFAULT_SCALE = uiUtils.DEFAULT_SCALE;
  2783. var DEFAULT_SCALE_VALUE = uiUtils.DEFAULT_SCALE_VALUE;
  2784. var scrollIntoView = uiUtils.scrollIntoView;
  2785. var watchScroll = uiUtils.watchScroll;
  2786. var getVisibleElements = uiUtils.getVisibleElements;
  2787. var PDFPageView = pdfPageView.PDFPageView;
  2788. var RenderingStates = pdfRenderingQueue.RenderingStates;
  2789. var PDFRenderingQueue = pdfRenderingQueue.PDFRenderingQueue;
  2790. var TextLayerBuilder = textLayerBuilder.TextLayerBuilder;
  2791. var AnnotationLayerBuilder = annotationLayerBuilder.AnnotationLayerBuilder;
  2792. var SimpleLinkService = pdfLinkService.SimpleLinkService;
  2793. var PresentationModeState = {
  2794. UNKNOWN: 0,
  2795. NORMAL: 1,
  2796. CHANGING: 2,
  2797. FULLSCREEN: 3,
  2798. };
  2799. var DEFAULT_CACHE_SIZE = 10;
  2800. /**
  2801. * @typedef {Object} PDFViewerOptions
  2802. * @property {HTMLDivElement} container - The container for the viewer element.
  2803. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  2804. * @property {EventBus} eventBus - The application event bus.
  2805. * @property {IPDFLinkService} linkService - The navigation/linking service.
  2806. * @property {DownloadManager} downloadManager - (optional) The download
  2807. * manager component.
  2808. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  2809. * queue object.
  2810. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  2811. * around the pages. The default is false.
  2812. */
  2813. /**
  2814. * Simple viewer control to display PDF content/pages.
  2815. * @class
  2816. * @implements {IRenderableView}
  2817. */
  2818. var PDFViewer = (function pdfViewer() {
  2819. function PDFPageViewBuffer(size) {
  2820. var data = [];
  2821. this.push = function cachePush(view) {
  2822. var i = data.indexOf(view);
  2823. if (i >= 0) {
  2824. data.splice(i, 1);
  2825. }
  2826. data.push(view);
  2827. if (data.length > size) {
  2828. data.shift().destroy();
  2829. }
  2830. };
  2831. this.resize = function (newSize) {
  2832. size = newSize;
  2833. while (data.length > size) {
  2834. data.shift().destroy();
  2835. }
  2836. };
  2837. }
  2838. function isSameScale(oldScale, newScale) {
  2839. if (newScale === oldScale) {
  2840. return true;
  2841. }
  2842. if (Math.abs(newScale - oldScale) < 1e-15) {
  2843. // Prevent unnecessary re-rendering of all pages when the scale
  2844. // changes only because of limited numerical precision.
  2845. return true;
  2846. }
  2847. return false;
  2848. }
  2849. /**
  2850. * @constructs PDFViewer
  2851. * @param {PDFViewerOptions} options
  2852. */
  2853. function PDFViewer(options) {
  2854. this.container = options.container;
  2855. this.viewer = options.viewer || options.container.firstElementChild;
  2856. this.eventBus = options.eventBus || domEvents.getGlobalEventBus();
  2857. this.linkService = options.linkService || new SimpleLinkService();
  2858. this.downloadManager = options.downloadManager || null;
  2859. this.removePageBorders = options.removePageBorders || false;
  2860. this.defaultRenderingQueue = !options.renderingQueue;
  2861. if (this.defaultRenderingQueue) {
  2862. // Custom rendering queue is not specified, using default one
  2863. this.renderingQueue = new PDFRenderingQueue();
  2864. this.renderingQueue.setViewer(this);
  2865. } else {
  2866. this.renderingQueue = options.renderingQueue;
  2867. }
  2868. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  2869. this.updateInProgress = false;
  2870. this.presentationModeState = PresentationModeState.UNKNOWN;
  2871. this._resetView();
  2872. if (this.removePageBorders) {
  2873. this.viewer.classList.add('removePageBorders');
  2874. }
  2875. }
  2876. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  2877. get pagesCount() {
  2878. return this._pages.length;
  2879. },
  2880. getPageView: function (index) {
  2881. return this._pages[index];
  2882. },
  2883. get currentPageNumber() {
  2884. return this._currentPageNumber;
  2885. },
  2886. set currentPageNumber(val) {
  2887. if (!this.pdfDocument) {
  2888. this._currentPageNumber = val;
  2889. return;
  2890. }
  2891. var arg;
  2892. if (!(0 < val && val <= this.pagesCount)) {
  2893. arg = {
  2894. source: this,
  2895. updateInProgress: this.updateInProgress,
  2896. pageNumber: this._currentPageNumber,
  2897. previousPageNumber: val
  2898. };
  2899. this.eventBus.dispatch('pagechanging', arg);
  2900. this.eventBus.dispatch('pagechange', arg);
  2901. return;
  2902. }
  2903. arg = {
  2904. source: this,
  2905. updateInProgress: this.updateInProgress,
  2906. pageNumber: val,
  2907. previousPageNumber: this._currentPageNumber
  2908. };
  2909. this.eventBus.dispatch('pagechanging', arg);
  2910. this._currentPageNumber = val;
  2911. this.eventBus.dispatch('pagechange', arg);
  2912. // Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
  2913. if (this.updateInProgress) {
  2914. return;
  2915. }
  2916. this.scrollPageIntoView(val);
  2917. },
  2918. /**
  2919. * @returns {number}
  2920. */
  2921. get currentScale() {
  2922. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  2923. DEFAULT_SCALE;
  2924. },
  2925. /**
  2926. * @param {number} val - Scale of the pages in percents.
  2927. */
  2928. set currentScale(val) {
  2929. if (isNaN(val)) {
  2930. throw new Error('Invalid numeric scale');
  2931. }
  2932. if (!this.pdfDocument) {
  2933. this._currentScale = val;
  2934. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  2935. return;
  2936. }
  2937. this._setScale(val, false);
  2938. },
  2939. /**
  2940. * @returns {string}
  2941. */
  2942. get currentScaleValue() {
  2943. return this._currentScaleValue;
  2944. },
  2945. /**
  2946. * @param val - The scale of the pages (in percent or predefined value).
  2947. */
  2948. set currentScaleValue(val) {
  2949. if (!this.pdfDocument) {
  2950. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  2951. this._currentScaleValue = val;
  2952. return;
  2953. }
  2954. this._setScale(val, false);
  2955. },
  2956. /**
  2957. * @returns {number}
  2958. */
  2959. get pagesRotation() {
  2960. return this._pagesRotation;
  2961. },
  2962. /**
  2963. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  2964. */
  2965. set pagesRotation(rotation) {
  2966. this._pagesRotation = rotation;
  2967. for (var i = 0, l = this._pages.length; i < l; i++) {
  2968. var pageView = this._pages[i];
  2969. pageView.update(pageView.scale, rotation);
  2970. }
  2971. this._setScale(this._currentScaleValue, true);
  2972. if (this.defaultRenderingQueue) {
  2973. this.update();
  2974. }
  2975. },
  2976. /**
  2977. * @param pdfDocument {PDFDocument}
  2978. */
  2979. setDocument: function (pdfDocument) {
  2980. if (this.pdfDocument) {
  2981. this._resetView();
  2982. }
  2983. this.pdfDocument = pdfDocument;
  2984. if (!pdfDocument) {
  2985. return;
  2986. }
  2987. var pagesCount = pdfDocument.numPages;
  2988. var self = this;
  2989. var resolvePagesPromise;
  2990. var pagesPromise = new Promise(function (resolve) {
  2991. resolvePagesPromise = resolve;
  2992. });
  2993. this.pagesPromise = pagesPromise;
  2994. pagesPromise.then(function () {
  2995. self.eventBus.dispatch('pagesloaded', {
  2996. source: self,
  2997. pagesCount: pagesCount
  2998. });
  2999. });
  3000. var isOnePageRenderedResolved = false;
  3001. var resolveOnePageRendered = null;
  3002. var onePageRendered = new Promise(function (resolve) {
  3003. resolveOnePageRendered = resolve;
  3004. });
  3005. this.onePageRendered = onePageRendered;
  3006. var bindOnAfterAndBeforeDraw = function (pageView) {
  3007. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  3008. // Add the page to the buffer at the start of drawing. That way it can
  3009. // be evicted from the buffer and destroyed even if we pause its
  3010. // rendering.
  3011. self._buffer.push(this);
  3012. };
  3013. // when page is painted, using the image as thumbnail base
  3014. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  3015. if (!isOnePageRenderedResolved) {
  3016. isOnePageRenderedResolved = true;
  3017. resolveOnePageRendered();
  3018. }
  3019. };
  3020. };
  3021. var firstPagePromise = pdfDocument.getPage(1);
  3022. this.firstPagePromise = firstPagePromise;
  3023. // Fetch a single page so we can get a viewport that will be the default
  3024. // viewport for all pages
  3025. return firstPagePromise.then(function(pdfPage) {
  3026. var scale = this.currentScale;
  3027. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  3028. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3029. var textLayerFactory = null;
  3030. if (!pdfjsLib.PDFJS.disableTextLayer) {
  3031. textLayerFactory = this;
  3032. }
  3033. var pageView = new PDFPageView({
  3034. container: this.viewer,
  3035. eventBus: this.eventBus,
  3036. id: pageNum,
  3037. scale: scale,
  3038. defaultViewport: viewport.clone(),
  3039. renderingQueue: this.renderingQueue,
  3040. textLayerFactory: textLayerFactory,
  3041. annotationLayerFactory: this
  3042. });
  3043. bindOnAfterAndBeforeDraw(pageView);
  3044. this._pages.push(pageView);
  3045. }
  3046. var linkService = this.linkService;
  3047. // Fetch all the pages since the viewport is needed before printing
  3048. // starts to create the correct size canvas. Wait until one page is
  3049. // rendered so we don't tie up too many resources early on.
  3050. onePageRendered.then(function () {
  3051. if (!pdfjsLib.PDFJS.disableAutoFetch) {
  3052. var getPagesLeft = pagesCount;
  3053. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  3054. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  3055. var pageView = self._pages[pageNum - 1];
  3056. if (!pageView.pdfPage) {
  3057. pageView.setPdfPage(pdfPage);
  3058. }
  3059. linkService.cachePageRef(pageNum, pdfPage.ref);
  3060. getPagesLeft--;
  3061. if (!getPagesLeft) {
  3062. resolvePagesPromise();
  3063. }
  3064. }.bind(null, pageNum));
  3065. }
  3066. } else {
  3067. // XXX: Printing is semi-broken with auto fetch disabled.
  3068. resolvePagesPromise();
  3069. }
  3070. });
  3071. self.eventBus.dispatch('pagesinit', {source: self});
  3072. if (this.defaultRenderingQueue) {
  3073. this.update();
  3074. }
  3075. if (this.findController) {
  3076. this.findController.resolveFirstPage();
  3077. }
  3078. }.bind(this));
  3079. },
  3080. _resetView: function () {
  3081. this._pages = [];
  3082. this._currentPageNumber = 1;
  3083. this._currentScale = UNKNOWN_SCALE;
  3084. this._currentScaleValue = null;
  3085. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  3086. this._location = null;
  3087. this._pagesRotation = 0;
  3088. this._pagesRequests = [];
  3089. var container = this.viewer;
  3090. while (container.hasChildNodes()) {
  3091. container.removeChild(container.lastChild);
  3092. }
  3093. },
  3094. _scrollUpdate: function PDFViewer_scrollUpdate() {
  3095. if (this.pagesCount === 0) {
  3096. return;
  3097. }
  3098. this.update();
  3099. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3100. this._pages[i].updatePosition();
  3101. }
  3102. },
  3103. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  3104. newScale, newValue, preset) {
  3105. var arg = {
  3106. source: this,
  3107. scale: newScale,
  3108. presetValue: preset ? newValue : undefined
  3109. };
  3110. this.eventBus.dispatch('scalechanging', arg);
  3111. this.eventBus.dispatch('scalechange', arg);
  3112. },
  3113. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  3114. newScale, newValue, noScroll, preset) {
  3115. this._currentScaleValue = newValue;
  3116. if (isSameScale(this._currentScale, newScale)) {
  3117. if (preset) {
  3118. this._setScaleDispatchEvent(newScale, newValue, true);
  3119. }
  3120. return;
  3121. }
  3122. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3123. this._pages[i].update(newScale);
  3124. }
  3125. this._currentScale = newScale;
  3126. if (!noScroll) {
  3127. var page = this._currentPageNumber, dest;
  3128. if (this._location && !pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom &&
  3129. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  3130. page = this._location.pageNumber;
  3131. dest = [null, { name: 'XYZ' }, this._location.left,
  3132. this._location.top, null];
  3133. }
  3134. this.scrollPageIntoView(page, dest);
  3135. }
  3136. this._setScaleDispatchEvent(newScale, newValue, preset);
  3137. if (this.defaultRenderingQueue) {
  3138. this.update();
  3139. }
  3140. },
  3141. _setScale: function pdfViewer_setScale(value, noScroll) {
  3142. var scale = parseFloat(value);
  3143. if (scale > 0) {
  3144. this._setScaleUpdatePages(scale, value, noScroll, false);
  3145. } else {
  3146. var currentPage = this._pages[this._currentPageNumber - 1];
  3147. if (!currentPage) {
  3148. return;
  3149. }
  3150. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  3151. 0 : SCROLLBAR_PADDING;
  3152. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  3153. 0 : VERTICAL_PADDING;
  3154. var pageWidthScale = (this.container.clientWidth - hPadding) /
  3155. currentPage.width * currentPage.scale;
  3156. var pageHeightScale = (this.container.clientHeight - vPadding) /
  3157. currentPage.height * currentPage.scale;
  3158. switch (value) {
  3159. case 'page-actual':
  3160. scale = 1;
  3161. break;
  3162. case 'page-width':
  3163. scale = pageWidthScale;
  3164. break;
  3165. case 'page-height':
  3166. scale = pageHeightScale;
  3167. break;
  3168. case 'page-fit':
  3169. scale = Math.min(pageWidthScale, pageHeightScale);
  3170. break;
  3171. case 'auto':
  3172. var isLandscape = (currentPage.width > currentPage.height);
  3173. // For pages in landscape mode, fit the page height to the viewer
  3174. // *unless* the page would thus become too wide to fit horizontally.
  3175. var horizontalScale = isLandscape ?
  3176. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  3177. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  3178. break;
  3179. default:
  3180. console.error('pdfViewSetScale: \'' + value +
  3181. '\' is an unknown zoom value.');
  3182. return;
  3183. }
  3184. this._setScaleUpdatePages(scale, value, noScroll, true);
  3185. }
  3186. },
  3187. /**
  3188. * Scrolls page into view.
  3189. * @param {number} pageNumber
  3190. * @param {Array} dest - (optional) original PDF destination array:
  3191. * <page-ref> </XYZ|FitXXX> <args..>
  3192. */
  3193. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  3194. dest) {
  3195. if (!this.pdfDocument) {
  3196. return;
  3197. }
  3198. var pageView = this._pages[pageNumber - 1];
  3199. if (this.isInPresentationMode) {
  3200. if (this._currentPageNumber !== pageView.id) {
  3201. // Avoid breaking getVisiblePages in presentation mode.
  3202. this.currentPageNumber = pageView.id;
  3203. return;
  3204. }
  3205. dest = null;
  3206. // Fixes the case when PDF has different page sizes.
  3207. this._setScale(this._currentScaleValue, true);
  3208. }
  3209. if (!dest) {
  3210. scrollIntoView(pageView.div);
  3211. return;
  3212. }
  3213. var x = 0, y = 0;
  3214. var width = 0, height = 0, widthScale, heightScale;
  3215. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  3216. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  3217. pageView.scale / CSS_UNITS;
  3218. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  3219. pageView.scale / CSS_UNITS;
  3220. var scale = 0;
  3221. switch (dest[1].name) {
  3222. case 'XYZ':
  3223. x = dest[2];
  3224. y = dest[3];
  3225. scale = dest[4];
  3226. // If x and/or y coordinates are not supplied, default to
  3227. // _top_ left of the page (not the obvious bottom left,
  3228. // since aligning the bottom of the intended page with the
  3229. // top of the window is rarely helpful).
  3230. x = x !== null ? x : 0;
  3231. y = y !== null ? y : pageHeight;
  3232. break;
  3233. case 'Fit':
  3234. case 'FitB':
  3235. scale = 'page-fit';
  3236. break;
  3237. case 'FitH':
  3238. case 'FitBH':
  3239. y = dest[2];
  3240. scale = 'page-width';
  3241. // According to the PDF spec, section 12.3.2.2, a `null` value in the
  3242. // parameter should maintain the position relative to the new page.
  3243. if (y === null && this._location) {
  3244. x = this._location.left;
  3245. y = this._location.top;
  3246. }
  3247. break;
  3248. case 'FitV':
  3249. case 'FitBV':
  3250. x = dest[2];
  3251. width = pageWidth;
  3252. height = pageHeight;
  3253. scale = 'page-height';
  3254. break;
  3255. case 'FitR':
  3256. x = dest[2];
  3257. y = dest[3];
  3258. width = dest[4] - x;
  3259. height = dest[5] - y;
  3260. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  3261. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  3262. widthScale = (this.container.clientWidth - hPadding) /
  3263. width / CSS_UNITS;
  3264. heightScale = (this.container.clientHeight - vPadding) /
  3265. height / CSS_UNITS;
  3266. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  3267. break;
  3268. default:
  3269. return;
  3270. }
  3271. if (scale && scale !== this._currentScale) {
  3272. this.currentScaleValue = scale;
  3273. } else if (this._currentScale === UNKNOWN_SCALE) {
  3274. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  3275. }
  3276. if (scale === 'page-fit' && !dest[4]) {
  3277. scrollIntoView(pageView.div);
  3278. return;
  3279. }
  3280. var boundingRect = [
  3281. pageView.viewport.convertToViewportPoint(x, y),
  3282. pageView.viewport.convertToViewportPoint(x + width, y + height)
  3283. ];
  3284. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  3285. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  3286. scrollIntoView(pageView.div, { left: left, top: top });
  3287. },
  3288. _updateLocation: function (firstPage) {
  3289. var currentScale = this._currentScale;
  3290. var currentScaleValue = this._currentScaleValue;
  3291. var normalizedScaleValue =
  3292. parseFloat(currentScaleValue) === currentScale ?
  3293. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  3294. var pageNumber = firstPage.id;
  3295. var pdfOpenParams = '#page=' + pageNumber;
  3296. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  3297. var currentPageView = this._pages[pageNumber - 1];
  3298. var container = this.container;
  3299. var topLeft = currentPageView.getPagePoint(
  3300. (container.scrollLeft - firstPage.x),
  3301. (container.scrollTop - firstPage.y));
  3302. var intLeft = Math.round(topLeft[0]);
  3303. var intTop = Math.round(topLeft[1]);
  3304. pdfOpenParams += ',' + intLeft + ',' + intTop;
  3305. this._location = {
  3306. pageNumber: pageNumber,
  3307. scale: normalizedScaleValue,
  3308. top: intTop,
  3309. left: intLeft,
  3310. pdfOpenParams: pdfOpenParams
  3311. };
  3312. },
  3313. update: function PDFViewer_update() {
  3314. var visible = this._getVisiblePages();
  3315. var visiblePages = visible.views;
  3316. if (visiblePages.length === 0) {
  3317. return;
  3318. }
  3319. this.updateInProgress = true;
  3320. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  3321. 2 * visiblePages.length + 1);
  3322. this._buffer.resize(suggestedCacheSize);
  3323. this.renderingQueue.renderHighestPriority(visible);
  3324. var currentId = this._currentPageNumber;
  3325. var firstPage = visible.first;
  3326. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  3327. i < ii; ++i) {
  3328. var page = visiblePages[i];
  3329. if (page.percent < 100) {
  3330. break;
  3331. }
  3332. if (page.id === currentId) {
  3333. stillFullyVisible = true;
  3334. break;
  3335. }
  3336. }
  3337. if (!stillFullyVisible) {
  3338. currentId = visiblePages[0].id;
  3339. }
  3340. if (!this.isInPresentationMode) {
  3341. this.currentPageNumber = currentId;
  3342. }
  3343. this._updateLocation(firstPage);
  3344. this.updateInProgress = false;
  3345. this.eventBus.dispatch('updateviewarea', {
  3346. source: this,
  3347. location: this._location
  3348. });
  3349. },
  3350. containsElement: function (element) {
  3351. return this.container.contains(element);
  3352. },
  3353. focus: function () {
  3354. this.container.focus();
  3355. },
  3356. get isInPresentationMode() {
  3357. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  3358. },
  3359. get isChangingPresentationMode() {
  3360. return this.presentationModeState === PresentationModeState.CHANGING;
  3361. },
  3362. get isHorizontalScrollbarEnabled() {
  3363. return (this.isInPresentationMode ?
  3364. false : (this.container.scrollWidth > this.container.clientWidth));
  3365. },
  3366. _getVisiblePages: function () {
  3367. if (!this.isInPresentationMode) {
  3368. return getVisibleElements(this.container, this._pages, true);
  3369. } else {
  3370. // The algorithm in getVisibleElements doesn't work in all browsers and
  3371. // configurations when presentation mode is active.
  3372. var visible = [];
  3373. var currentPage = this._pages[this._currentPageNumber - 1];
  3374. visible.push({ id: currentPage.id, view: currentPage });
  3375. return { first: currentPage, last: currentPage, views: visible };
  3376. }
  3377. },
  3378. cleanup: function () {
  3379. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  3380. if (this._pages[i] &&
  3381. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  3382. this._pages[i].reset();
  3383. }
  3384. }
  3385. },
  3386. /**
  3387. * @param {PDFPageView} pageView
  3388. * @returns {PDFPage}
  3389. * @private
  3390. */
  3391. _ensurePdfPageLoaded: function (pageView) {
  3392. if (pageView.pdfPage) {
  3393. return Promise.resolve(pageView.pdfPage);
  3394. }
  3395. var pageNumber = pageView.id;
  3396. if (this._pagesRequests[pageNumber]) {
  3397. return this._pagesRequests[pageNumber];
  3398. }
  3399. var promise = this.pdfDocument.getPage(pageNumber).then(
  3400. function (pdfPage) {
  3401. pageView.setPdfPage(pdfPage);
  3402. this._pagesRequests[pageNumber] = null;
  3403. return pdfPage;
  3404. }.bind(this));
  3405. this._pagesRequests[pageNumber] = promise;
  3406. return promise;
  3407. },
  3408. forceRendering: function (currentlyVisiblePages) {
  3409. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  3410. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  3411. this._pages,
  3412. this.scroll.down);
  3413. if (pageView) {
  3414. this._ensurePdfPageLoaded(pageView).then(function () {
  3415. this.renderingQueue.renderView(pageView);
  3416. }.bind(this));
  3417. return true;
  3418. }
  3419. return false;
  3420. },
  3421. getPageTextContent: function (pageIndex) {
  3422. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  3423. return page.getTextContent({ normalizeWhitespace: true });
  3424. });
  3425. },
  3426. /**
  3427. * @param {HTMLDivElement} textLayerDiv
  3428. * @param {number} pageIndex
  3429. * @param {PageViewport} viewport
  3430. * @returns {TextLayerBuilder}
  3431. */
  3432. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  3433. return new TextLayerBuilder({
  3434. textLayerDiv: textLayerDiv,
  3435. eventBus: this.eventBus,
  3436. pageIndex: pageIndex,
  3437. viewport: viewport,
  3438. findController: this.isInPresentationMode ? null : this.findController
  3439. });
  3440. },
  3441. /**
  3442. * @param {HTMLDivElement} pageDiv
  3443. * @param {PDFPage} pdfPage
  3444. * @returns {AnnotationLayerBuilder}
  3445. */
  3446. createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
  3447. return new AnnotationLayerBuilder({
  3448. pageDiv: pageDiv,
  3449. pdfPage: pdfPage,
  3450. linkService: this.linkService,
  3451. downloadManager: this.downloadManager
  3452. });
  3453. },
  3454. setFindController: function (findController) {
  3455. this.findController = findController;
  3456. },
  3457. };
  3458. return PDFViewer;
  3459. })();
  3460. exports.PresentationModeState = PresentationModeState;
  3461. exports.PDFViewer = PDFViewer;
  3462. }));
  3463. }).call(pdfViewerLibs);
  3464. var PDFJS = pdfjsLib.PDFJS;
  3465. PDFJS.PDFViewer = pdfViewerLibs.pdfjsWebPDFViewer.PDFViewer;
  3466. PDFJS.PDFPageView = pdfViewerLibs.pdfjsWebPDFPageView.PDFPageView;
  3467. PDFJS.PDFLinkService = pdfViewerLibs.pdfjsWebPDFLinkService.PDFLinkService;
  3468. PDFJS.TextLayerBuilder =
  3469. pdfViewerLibs.pdfjsWebTextLayerBuilder.TextLayerBuilder;
  3470. PDFJS.DefaultTextLayerFactory =
  3471. pdfViewerLibs.pdfjsWebTextLayerBuilder.DefaultTextLayerFactory;
  3472. PDFJS.AnnotationLayerBuilder =
  3473. pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.AnnotationLayerBuilder;
  3474. PDFJS.DefaultAnnotationLayerFactory =
  3475. pdfViewerLibs.pdfjsWebAnnotationLayerBuilder.DefaultAnnotationLayerFactory;
  3476. PDFJS.PDFHistory = pdfViewerLibs.pdfjsWebPDFHistory.PDFHistory;
  3477. PDFJS.PDFFindController =
  3478. pdfViewerLibs.pdfjsWebPDFFindController.PDFFindController;
  3479. PDFJS.EventBus = pdfViewerLibs.pdfjsWebUIUtils.EventBus;
  3480. PDFJS.DownloadManager = pdfViewerLibs.pdfjsWebDownloadManager.DownloadManager;
  3481. PDFJS.ProgressBar = pdfViewerLibs.pdfjsWebUIUtils.ProgressBar;
  3482. exports.PDFJS = PDFJS;
  3483. }));