pdf_viewer.js 124 KB

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