pdf_viewer.js 130 KB

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