pdf_viewer.js 135 KB

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