pdf_viewer.js 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124
  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2014 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*jshint globalstrict: false */
  18. /* globals PDFJS, PDFViewer, PDFPageView, TextLayerBuilder, PDFLinkService,
  19. DefaultTextLayerFactory, AnnotationsLayerBuilder, PDFHistory,
  20. DefaultAnnotationsLayerFactory, getFileName, ProgressBar */
  21. // Initializing PDFJS global object (if still undefined)
  22. if (typeof PDFJS === 'undefined') {
  23. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  24. }
  25. (function pdfViewerWrapper() {
  26. 'use strict';
  27. var CSS_UNITS = 96.0 / 72.0;
  28. var DEFAULT_SCALE_VALUE = 'auto';
  29. var DEFAULT_SCALE = 1.0;
  30. var UNKNOWN_SCALE = 0;
  31. var MAX_AUTO_SCALE = 1.25;
  32. var SCROLLBAR_PADDING = 40;
  33. var VERTICAL_PADDING = 5;
  34. // optimised CSS custom property getter/setter
  35. var CustomStyle = (function CustomStyleClosure() {
  36. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  37. // animate-css-transforms-firefox-webkit.html
  38. // in some versions of IE9 it is critical that ms appear in this list
  39. // before Moz
  40. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  41. var _cache = {};
  42. function CustomStyle() {}
  43. CustomStyle.getProp = function get(propName, element) {
  44. // check cache only when no element is given
  45. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  46. return _cache[propName];
  47. }
  48. element = element || document.documentElement;
  49. var style = element.style, prefixed, uPropName;
  50. // test standard property first
  51. if (typeof style[propName] === 'string') {
  52. return (_cache[propName] = propName);
  53. }
  54. // capitalize
  55. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  56. // test vendor specific properties
  57. for (var i = 0, l = prefixes.length; i < l; i++) {
  58. prefixed = prefixes[i] + uPropName;
  59. if (typeof style[prefixed] === 'string') {
  60. return (_cache[propName] = prefixed);
  61. }
  62. }
  63. //if all fails then set to undefined
  64. return (_cache[propName] = 'undefined');
  65. };
  66. CustomStyle.setProp = function set(propName, element, str) {
  67. var prop = this.getProp(propName);
  68. if (prop !== 'undefined') {
  69. element.style[prop] = str;
  70. }
  71. };
  72. return CustomStyle;
  73. })();
  74. function getFileName(url) {
  75. var anchor = url.indexOf('#');
  76. var query = url.indexOf('?');
  77. var end = Math.min(
  78. anchor > 0 ? anchor : url.length,
  79. query > 0 ? query : url.length);
  80. return url.substring(url.lastIndexOf('/', end) + 1, end);
  81. }
  82. /**
  83. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  84. * @return {Object} The object with horizontal (sx) and vertical (sy)
  85. scales. The scaled property is set to false if scaling is
  86. not required, true otherwise.
  87. */
  88. function getOutputScale(ctx) {
  89. var devicePixelRatio = window.devicePixelRatio || 1;
  90. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  91. ctx.mozBackingStorePixelRatio ||
  92. ctx.msBackingStorePixelRatio ||
  93. ctx.oBackingStorePixelRatio ||
  94. ctx.backingStorePixelRatio || 1;
  95. var pixelRatio = devicePixelRatio / backingStoreRatio;
  96. return {
  97. sx: pixelRatio,
  98. sy: pixelRatio,
  99. scaled: pixelRatio !== 1
  100. };
  101. }
  102. /**
  103. * Scrolls specified element into view of its parent.
  104. * element {Object} The element to be visible.
  105. * spot {Object} An object with optional top and left properties,
  106. * specifying the offset from the top left edge.
  107. */
  108. function scrollIntoView(element, spot) {
  109. // Assuming offsetParent is available (it's not available when viewer is in
  110. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  111. // producing the error. See also animationStartedClosure.
  112. var parent = element.offsetParent;
  113. var offsetY = element.offsetTop + element.clientTop;
  114. var offsetX = element.offsetLeft + element.clientLeft;
  115. if (!parent) {
  116. console.error('offsetParent is not set -- cannot scroll');
  117. return;
  118. }
  119. while (parent.clientHeight === parent.scrollHeight) {
  120. if (parent.dataset._scaleY) {
  121. offsetY /= parent.dataset._scaleY;
  122. offsetX /= parent.dataset._scaleX;
  123. }
  124. offsetY += parent.offsetTop;
  125. offsetX += parent.offsetLeft;
  126. parent = parent.offsetParent;
  127. if (!parent) {
  128. return; // no need to scroll
  129. }
  130. }
  131. if (spot) {
  132. if (spot.top !== undefined) {
  133. offsetY += spot.top;
  134. }
  135. if (spot.left !== undefined) {
  136. offsetX += spot.left;
  137. parent.scrollLeft = offsetX;
  138. }
  139. }
  140. parent.scrollTop = offsetY;
  141. }
  142. /**
  143. * Helper function to start monitoring the scroll event and converting them into
  144. * PDF.js friendly one: with scroll debounce and scroll direction.
  145. */
  146. function watchScroll(viewAreaElement, callback) {
  147. var debounceScroll = function debounceScroll(evt) {
  148. if (rAF) {
  149. return;
  150. }
  151. // schedule an invocation of scroll for next animation frame.
  152. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  153. rAF = null;
  154. var currentY = viewAreaElement.scrollTop;
  155. var lastY = state.lastY;
  156. if (currentY !== lastY) {
  157. state.down = currentY > lastY;
  158. }
  159. state.lastY = currentY;
  160. callback(state);
  161. });
  162. };
  163. var state = {
  164. down: true,
  165. lastY: viewAreaElement.scrollTop,
  166. _eventHandler: debounceScroll
  167. };
  168. var rAF = null;
  169. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  170. return state;
  171. }
  172. /**
  173. * Helper function to parse query string (e.g. ?param1=value&parm2=...).
  174. */
  175. function parseQueryString(query) {
  176. var parts = query.split('&');
  177. var params = {};
  178. for (var i = 0, ii = parts.length; i < ii; ++i) {
  179. var param = parts[i].split('=');
  180. var key = param[0].toLowerCase();
  181. var value = param.length > 1 ? param[1] : null;
  182. params[decodeURIComponent(key)] = decodeURIComponent(value);
  183. }
  184. return params;
  185. }
  186. /**
  187. * Use binary search to find the index of the first item in a given array which
  188. * passes a given condition. The items are expected to be sorted in the sense
  189. * that if the condition is true for one item in the array, then it is also true
  190. * for all following items.
  191. *
  192. * @returns {Number} Index of the first array element to pass the test,
  193. * or |items.length| if no such element exists.
  194. */
  195. function binarySearchFirstItem(items, condition) {
  196. var minIndex = 0;
  197. var maxIndex = items.length - 1;
  198. if (items.length === 0 || !condition(items[maxIndex])) {
  199. return items.length;
  200. }
  201. if (condition(items[minIndex])) {
  202. return minIndex;
  203. }
  204. while (minIndex < maxIndex) {
  205. var currentIndex = (minIndex + maxIndex) >> 1;
  206. var currentItem = items[currentIndex];
  207. if (condition(currentItem)) {
  208. maxIndex = currentIndex;
  209. } else {
  210. minIndex = currentIndex + 1;
  211. }
  212. }
  213. return minIndex; /* === maxIndex */
  214. }
  215. /**
  216. * Generic helper to find out what elements are visible within a scroll pane.
  217. */
  218. function getVisibleElements(scrollEl, views, sortByVisibility) {
  219. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  220. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  221. function isElementBottomBelowViewTop(view) {
  222. var element = view.div;
  223. var elementBottom =
  224. element.offsetTop + element.clientTop + element.clientHeight;
  225. return elementBottom > top;
  226. }
  227. var visible = [], view, element;
  228. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  229. var currentWidth, viewWidth;
  230. var firstVisibleElementInd = (views.length === 0) ? 0 :
  231. binarySearchFirstItem(views, isElementBottomBelowViewTop);
  232. for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
  233. view = views[i];
  234. element = view.div;
  235. currentHeight = element.offsetTop + element.clientTop;
  236. viewHeight = element.clientHeight;
  237. if (currentHeight > bottom) {
  238. break;
  239. }
  240. currentWidth = element.offsetLeft + element.clientLeft;
  241. viewWidth = element.clientWidth;
  242. if (currentWidth + viewWidth < left || currentWidth > right) {
  243. continue;
  244. }
  245. hiddenHeight = Math.max(0, top - currentHeight) +
  246. Math.max(0, currentHeight + viewHeight - bottom);
  247. percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
  248. visible.push({
  249. id: view.id,
  250. x: currentWidth,
  251. y: currentHeight,
  252. view: view,
  253. percent: percentHeight
  254. });
  255. }
  256. var first = visible[0];
  257. var last = visible[visible.length - 1];
  258. if (sortByVisibility) {
  259. visible.sort(function(a, b) {
  260. var pc = a.percent - b.percent;
  261. if (Math.abs(pc) > 0.001) {
  262. return -pc;
  263. }
  264. return a.id - b.id; // ensure stability
  265. });
  266. }
  267. return {first: first, last: last, views: visible};
  268. }
  269. /**
  270. * Event handler to suppress context menu.
  271. */
  272. function noContextMenuHandler(e) {
  273. e.preventDefault();
  274. }
  275. /**
  276. * Returns the filename or guessed filename from the url (see issue 3455).
  277. * url {String} The original PDF location.
  278. * @return {String} Guessed PDF file name.
  279. */
  280. function getPDFFileNameFromURL(url) {
  281. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  282. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  283. // Pattern to get last matching NAME.pdf
  284. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  285. var splitURI = reURI.exec(url);
  286. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  287. reFilename.exec(splitURI[2]) ||
  288. reFilename.exec(splitURI[3]);
  289. if (suggestedFilename) {
  290. suggestedFilename = suggestedFilename[0];
  291. if (suggestedFilename.indexOf('%') !== -1) {
  292. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  293. try {
  294. suggestedFilename =
  295. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  296. } catch(e) { // Possible (extremely rare) errors:
  297. // URIError "Malformed URI", e.g. for "%AA.pdf"
  298. // TypeError "null has no properties", e.g. for "%2F.pdf"
  299. }
  300. }
  301. }
  302. return suggestedFilename || 'document.pdf';
  303. }
  304. var ProgressBar = (function ProgressBarClosure() {
  305. function clamp(v, min, max) {
  306. return Math.min(Math.max(v, min), max);
  307. }
  308. function ProgressBar(id, opts) {
  309. this.visible = true;
  310. // Fetch the sub-elements for later.
  311. this.div = document.querySelector(id + ' .progress');
  312. // Get the loading bar element, so it can be resized to fit the viewer.
  313. this.bar = this.div.parentNode;
  314. // Get options, with sensible defaults.
  315. this.height = opts.height || 100;
  316. this.width = opts.width || 100;
  317. this.units = opts.units || '%';
  318. // Initialize heights.
  319. this.div.style.height = this.height + this.units;
  320. this.percent = 0;
  321. }
  322. ProgressBar.prototype = {
  323. updateBar: function ProgressBar_updateBar() {
  324. if (this._indeterminate) {
  325. this.div.classList.add('indeterminate');
  326. this.div.style.width = this.width + this.units;
  327. return;
  328. }
  329. this.div.classList.remove('indeterminate');
  330. var progressSize = this.width * this._percent / 100;
  331. this.div.style.width = progressSize + this.units;
  332. },
  333. get percent() {
  334. return this._percent;
  335. },
  336. set percent(val) {
  337. this._indeterminate = isNaN(val);
  338. this._percent = clamp(val, 0, 100);
  339. this.updateBar();
  340. },
  341. setWidth: function ProgressBar_setWidth(viewer) {
  342. if (viewer) {
  343. var container = viewer.parentNode;
  344. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  345. if (scrollbarWidth > 0) {
  346. this.bar.setAttribute('style', 'width: calc(100% - ' +
  347. scrollbarWidth + 'px);');
  348. }
  349. }
  350. },
  351. hide: function ProgressBar_hide() {
  352. if (!this.visible) {
  353. return;
  354. }
  355. this.visible = false;
  356. this.bar.classList.add('hidden');
  357. document.body.classList.remove('loadingInProgress');
  358. },
  359. show: function ProgressBar_show() {
  360. if (this.visible) {
  361. return;
  362. }
  363. this.visible = true;
  364. document.body.classList.add('loadingInProgress');
  365. this.bar.classList.remove('hidden');
  366. }
  367. };
  368. return ProgressBar;
  369. })();
  370. /**
  371. * Performs navigation functions inside PDF, such as opening specified page,
  372. * or destination.
  373. * @class
  374. * @implements {IPDFLinkService}
  375. */
  376. var PDFLinkService = (function () {
  377. /**
  378. * @constructs PDFLinkService
  379. */
  380. function PDFLinkService() {
  381. this.baseUrl = null;
  382. this.pdfDocument = null;
  383. this.pdfViewer = null;
  384. this.pdfHistory = null;
  385. this._pagesRefCache = null;
  386. }
  387. PDFLinkService.prototype = {
  388. setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
  389. this.baseUrl = baseUrl;
  390. this.pdfDocument = pdfDocument;
  391. this._pagesRefCache = Object.create(null);
  392. },
  393. setViewer: function PDFLinkService_setViewer(pdfViewer) {
  394. this.pdfViewer = pdfViewer;
  395. },
  396. setHistory: function PDFLinkService_setHistory(pdfHistory) {
  397. this.pdfHistory = pdfHistory;
  398. },
  399. /**
  400. * @returns {number}
  401. */
  402. get pagesCount() {
  403. return this.pdfDocument.numPages;
  404. },
  405. /**
  406. * @returns {number}
  407. */
  408. get page() {
  409. return this.pdfViewer.currentPageNumber;
  410. },
  411. /**
  412. * @param {number} value
  413. */
  414. set page(value) {
  415. this.pdfViewer.currentPageNumber = value;
  416. },
  417. /**
  418. * @param dest - The PDF destination object.
  419. */
  420. navigateTo: function PDFLinkService_navigateTo(dest) {
  421. var destString = '';
  422. var self = this;
  423. var goToDestination = function(destRef) {
  424. // dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
  425. var pageNumber = destRef instanceof Object ?
  426. self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  427. (destRef + 1);
  428. if (pageNumber) {
  429. if (pageNumber > self.pagesCount) {
  430. pageNumber = self.pagesCount;
  431. }
  432. self.pdfViewer.scrollPageIntoView(pageNumber, dest);
  433. if (self.pdfHistory) {
  434. // Update the browsing history.
  435. self.pdfHistory.push({
  436. dest: dest,
  437. hash: destString,
  438. page: pageNumber
  439. });
  440. }
  441. } else {
  442. self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
  443. var pageNum = pageIndex + 1;
  444. var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
  445. self._pagesRefCache[cacheKey] = pageNum;
  446. goToDestination(destRef);
  447. });
  448. }
  449. };
  450. var destinationPromise;
  451. if (typeof dest === 'string') {
  452. destString = dest;
  453. destinationPromise = this.pdfDocument.getDestination(dest);
  454. } else {
  455. destinationPromise = Promise.resolve(dest);
  456. }
  457. destinationPromise.then(function(destination) {
  458. dest = destination;
  459. if (!(destination instanceof Array)) {
  460. return; // invalid destination
  461. }
  462. goToDestination(destination[0]);
  463. });
  464. },
  465. /**
  466. * @param dest - The PDF destination object.
  467. * @returns {string} The hyperlink to the PDF object.
  468. */
  469. getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
  470. if (typeof dest === 'string') {
  471. return this.getAnchorUrl('#' + escape(dest));
  472. }
  473. if (dest instanceof Array) {
  474. var destRef = dest[0]; // see navigateTo method for dest format
  475. var pageNumber = destRef instanceof Object ?
  476. this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
  477. (destRef + 1);
  478. if (pageNumber) {
  479. var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
  480. var destKind = dest[1];
  481. if (typeof destKind === 'object' && 'name' in destKind &&
  482. destKind.name === 'XYZ') {
  483. var scale = (dest[4] || this.pdfViewer.currentScaleValue);
  484. var scaleNumber = parseFloat(scale);
  485. if (scaleNumber) {
  486. scale = scaleNumber * 100;
  487. }
  488. pdfOpenParams += '&zoom=' + scale;
  489. if (dest[2] || dest[3]) {
  490. pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
  491. }
  492. }
  493. return pdfOpenParams;
  494. }
  495. }
  496. return '';
  497. },
  498. /**
  499. * Prefix the full url on anchor links to make sure that links are resolved
  500. * relative to the current URL instead of the one defined in <base href>.
  501. * @param {String} anchor The anchor hash, including the #.
  502. * @returns {string} The hyperlink to the PDF object.
  503. */
  504. getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
  505. return (this.baseUrl || '') + anchor;
  506. },
  507. /**
  508. * @param {string} hash
  509. */
  510. setHash: function PDFLinkService_setHash(hash) {
  511. if (hash.indexOf('=') >= 0) {
  512. var params = parseQueryString(hash);
  513. // borrowing syntax from "Parameters for Opening PDF Files"
  514. if ('nameddest' in params) {
  515. if (this.pdfHistory) {
  516. this.pdfHistory.updateNextHashParam(params.nameddest);
  517. }
  518. this.navigateTo(params.nameddest);
  519. return;
  520. }
  521. var pageNumber, dest;
  522. if ('page' in params) {
  523. pageNumber = (params.page | 0) || 1;
  524. }
  525. if ('zoom' in params) {
  526. // Build the destination array.
  527. var zoomArgs = params.zoom.split(','); // scale,left,top
  528. var zoomArg = zoomArgs[0];
  529. var zoomArgNumber = parseFloat(zoomArg);
  530. if (zoomArg.indexOf('Fit') === -1) {
  531. // If the zoomArg is a number, it has to get divided by 100. If it's
  532. // a string, it should stay as it is.
  533. dest = [null, { name: 'XYZ' },
  534. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
  535. zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
  536. (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
  537. } else {
  538. if (zoomArg === 'Fit' || zoomArg === 'FitB') {
  539. dest = [null, { name: zoomArg }];
  540. } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
  541. (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
  542. dest = [null, { name: zoomArg },
  543. zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
  544. } else if (zoomArg === 'FitR') {
  545. if (zoomArgs.length !== 5) {
  546. console.error('PDFLinkService_setHash: ' +
  547. 'Not enough parameters for \'FitR\'.');
  548. } else {
  549. dest = [null, { name: zoomArg },
  550. (zoomArgs[1] | 0), (zoomArgs[2] | 0),
  551. (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
  552. }
  553. } else {
  554. console.error('PDFLinkService_setHash: \'' + zoomArg +
  555. '\' is not a valid zoom value.');
  556. }
  557. }
  558. }
  559. if (dest) {
  560. this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
  561. } else if (pageNumber) {
  562. this.page = pageNumber; // simple page
  563. }
  564. if ('pagemode' in params) {
  565. var event = document.createEvent('CustomEvent');
  566. event.initCustomEvent('pagemode', true, true, {
  567. mode: params.pagemode,
  568. });
  569. this.pdfViewer.container.dispatchEvent(event);
  570. }
  571. } else if (/^\d+$/.test(hash)) { // page number
  572. this.page = hash;
  573. } else { // named destination
  574. if (this.pdfHistory) {
  575. this.pdfHistory.updateNextHashParam(unescape(hash));
  576. }
  577. this.navigateTo(unescape(hash));
  578. }
  579. },
  580. /**
  581. * @param {string} action
  582. */
  583. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  584. // See PDF reference, table 8.45 - Named action
  585. switch (action) {
  586. case 'GoBack':
  587. if (this.pdfHistory) {
  588. this.pdfHistory.back();
  589. }
  590. break;
  591. case 'GoForward':
  592. if (this.pdfHistory) {
  593. this.pdfHistory.forward();
  594. }
  595. break;
  596. case 'NextPage':
  597. this.page++;
  598. break;
  599. case 'PrevPage':
  600. this.page--;
  601. break;
  602. case 'LastPage':
  603. this.page = this.pagesCount;
  604. break;
  605. case 'FirstPage':
  606. this.page = 1;
  607. break;
  608. default:
  609. break; // No action according to spec
  610. }
  611. var event = document.createEvent('CustomEvent');
  612. event.initCustomEvent('namedaction', true, true, {
  613. action: action
  614. });
  615. this.pdfViewer.container.dispatchEvent(event);
  616. },
  617. /**
  618. * @param {number} pageNum - page number.
  619. * @param {Object} pageRef - reference to the page.
  620. */
  621. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  622. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  623. this._pagesRefCache[refStr] = pageNum;
  624. }
  625. };
  626. return PDFLinkService;
  627. })();
  628. var PresentationModeState = {
  629. UNKNOWN: 0,
  630. NORMAL: 1,
  631. CHANGING: 2,
  632. FULLSCREEN: 3,
  633. };
  634. var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
  635. var DEFAULT_CACHE_SIZE = 10;
  636. var CLEANUP_TIMEOUT = 30000;
  637. var RenderingStates = {
  638. INITIAL: 0,
  639. RUNNING: 1,
  640. PAUSED: 2,
  641. FINISHED: 3
  642. };
  643. /**
  644. * Controls rendering of the views for pages and thumbnails.
  645. * @class
  646. */
  647. var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
  648. /**
  649. * @constructs
  650. */
  651. function PDFRenderingQueue() {
  652. this.pdfViewer = null;
  653. this.pdfThumbnailViewer = null;
  654. this.onIdle = null;
  655. this.highestPriorityPage = null;
  656. this.idleTimeout = null;
  657. this.printing = false;
  658. this.isThumbnailViewEnabled = false;
  659. }
  660. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
  661. /**
  662. * @param {PDFViewer} pdfViewer
  663. */
  664. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  665. this.pdfViewer = pdfViewer;
  666. },
  667. /**
  668. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  669. */
  670. setThumbnailViewer:
  671. function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  672. this.pdfThumbnailViewer = pdfThumbnailViewer;
  673. },
  674. /**
  675. * @param {IRenderableView} view
  676. * @returns {boolean}
  677. */
  678. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  679. return this.highestPriorityPage === view.renderingId;
  680. },
  681. renderHighestPriority: function
  682. PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  683. if (this.idleTimeout) {
  684. clearTimeout(this.idleTimeout);
  685. this.idleTimeout = null;
  686. }
  687. // Pages have a higher priority than thumbnails, so check them first.
  688. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  689. return;
  690. }
  691. // No pages needed rendering so check thumbnails.
  692. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  693. if (this.pdfThumbnailViewer.forceRendering()) {
  694. return;
  695. }
  696. }
  697. if (this.printing) {
  698. // If printing is currently ongoing do not reschedule cleanup.
  699. return;
  700. }
  701. if (this.onIdle) {
  702. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  703. }
  704. },
  705. getHighestPriority: function
  706. PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  707. // The state has changed figure out which page has the highest priority to
  708. // render next (if any).
  709. // Priority:
  710. // 1 visible pages
  711. // 2 if last scrolled down page after the visible pages
  712. // 2 if last scrolled up page before the visible pages
  713. var visibleViews = visible.views;
  714. var numVisible = visibleViews.length;
  715. if (numVisible === 0) {
  716. return false;
  717. }
  718. for (var i = 0; i < numVisible; ++i) {
  719. var view = visibleViews[i].view;
  720. if (!this.isViewFinished(view)) {
  721. return view;
  722. }
  723. }
  724. // All the visible views have rendered, try to render next/previous pages.
  725. if (scrolledDown) {
  726. var nextPageIndex = visible.last.id;
  727. // ID's start at 1 so no need to add 1.
  728. if (views[nextPageIndex] &&
  729. !this.isViewFinished(views[nextPageIndex])) {
  730. return views[nextPageIndex];
  731. }
  732. } else {
  733. var previousPageIndex = visible.first.id - 2;
  734. if (views[previousPageIndex] &&
  735. !this.isViewFinished(views[previousPageIndex])) {
  736. return views[previousPageIndex];
  737. }
  738. }
  739. // Everything that needs to be rendered has been.
  740. return null;
  741. },
  742. /**
  743. * @param {IRenderableView} view
  744. * @returns {boolean}
  745. */
  746. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  747. return view.renderingState === RenderingStates.FINISHED;
  748. },
  749. /**
  750. * Render a page or thumbnail view. This calls the appropriate function
  751. * based on the views state. If the view is already rendered it will return
  752. * false.
  753. * @param {IRenderableView} view
  754. */
  755. renderView: function PDFRenderingQueue_renderView(view) {
  756. var state = view.renderingState;
  757. switch (state) {
  758. case RenderingStates.FINISHED:
  759. return false;
  760. case RenderingStates.PAUSED:
  761. this.highestPriorityPage = view.renderingId;
  762. view.resume();
  763. break;
  764. case RenderingStates.RUNNING:
  765. this.highestPriorityPage = view.renderingId;
  766. break;
  767. case RenderingStates.INITIAL:
  768. this.highestPriorityPage = view.renderingId;
  769. var continueRendering = function () {
  770. this.renderHighestPriority();
  771. }.bind(this);
  772. view.draw().then(continueRendering, continueRendering);
  773. break;
  774. }
  775. return true;
  776. },
  777. };
  778. return PDFRenderingQueue;
  779. })();
  780. var TEXT_LAYER_RENDER_DELAY = 200; // ms
  781. /**
  782. * @typedef {Object} PDFPageViewOptions
  783. * @property {HTMLDivElement} container - The viewer element.
  784. * @property {number} id - The page unique ID (normally its number).
  785. * @property {number} scale - The page scale display.
  786. * @property {PageViewport} defaultViewport - The page viewport.
  787. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  788. * @property {IPDFTextLayerFactory} textLayerFactory
  789. * @property {IPDFAnnotationsLayerFactory} annotationsLayerFactory
  790. */
  791. /**
  792. * @class
  793. * @implements {IRenderableView}
  794. */
  795. var PDFPageView = (function PDFPageViewClosure() {
  796. /**
  797. * @constructs PDFPageView
  798. * @param {PDFPageViewOptions} options
  799. */
  800. function PDFPageView(options) {
  801. var container = options.container;
  802. var id = options.id;
  803. var scale = options.scale;
  804. var defaultViewport = options.defaultViewport;
  805. var renderingQueue = options.renderingQueue;
  806. var textLayerFactory = options.textLayerFactory;
  807. var annotationsLayerFactory = options.annotationsLayerFactory;
  808. this.id = id;
  809. this.renderingId = 'page' + id;
  810. this.rotation = 0;
  811. this.scale = scale || 1.0;
  812. this.viewport = defaultViewport;
  813. this.pdfPageRotate = defaultViewport.rotation;
  814. this.hasRestrictedScaling = false;
  815. this.renderingQueue = renderingQueue;
  816. this.textLayerFactory = textLayerFactory;
  817. this.annotationsLayerFactory = annotationsLayerFactory;
  818. this.renderingState = RenderingStates.INITIAL;
  819. this.resume = null;
  820. this.onBeforeDraw = null;
  821. this.onAfterDraw = null;
  822. this.textLayer = null;
  823. this.zoomLayer = null;
  824. this.annotationLayer = null;
  825. var div = document.createElement('div');
  826. div.id = 'pageContainer' + this.id;
  827. div.className = 'page';
  828. div.style.width = Math.floor(this.viewport.width) + 'px';
  829. div.style.height = Math.floor(this.viewport.height) + 'px';
  830. div.setAttribute('data-page-number', this.id);
  831. this.div = div;
  832. container.appendChild(div);
  833. }
  834. PDFPageView.prototype = {
  835. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  836. this.pdfPage = pdfPage;
  837. this.pdfPageRotate = pdfPage.rotate;
  838. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  839. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
  840. totalRotation);
  841. this.stats = pdfPage.stats;
  842. this.reset();
  843. },
  844. destroy: function PDFPageView_destroy() {
  845. this.zoomLayer = null;
  846. this.reset();
  847. if (this.pdfPage) {
  848. this.pdfPage.destroy();
  849. }
  850. },
  851. reset: function PDFPageView_reset(keepAnnotations) {
  852. if (this.renderTask) {
  853. this.renderTask.cancel();
  854. }
  855. this.resume = null;
  856. this.renderingState = RenderingStates.INITIAL;
  857. var div = this.div;
  858. div.style.width = Math.floor(this.viewport.width) + 'px';
  859. div.style.height = Math.floor(this.viewport.height) + 'px';
  860. var childNodes = div.childNodes;
  861. var currentZoomLayer = this.zoomLayer || null;
  862. var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
  863. this.annotationLayer.div) || null;
  864. for (var i = childNodes.length - 1; i >= 0; i--) {
  865. var node = childNodes[i];
  866. if (currentZoomLayer === node || currentAnnotationNode === node) {
  867. continue;
  868. }
  869. div.removeChild(node);
  870. }
  871. div.removeAttribute('data-loaded');
  872. if (keepAnnotations) {
  873. if (this.annotationLayer) {
  874. // Hide annotationLayer until all elements are resized
  875. // so they are not displayed on the already-resized page
  876. this.annotationLayer.hide();
  877. }
  878. } else {
  879. this.annotationLayer = null;
  880. }
  881. if (this.canvas) {
  882. // Zeroing the width and height causes Firefox to release graphics
  883. // resources immediately, which can greatly reduce memory consumption.
  884. this.canvas.width = 0;
  885. this.canvas.height = 0;
  886. delete this.canvas;
  887. }
  888. this.loadingIconDiv = document.createElement('div');
  889. this.loadingIconDiv.className = 'loadingIcon';
  890. div.appendChild(this.loadingIconDiv);
  891. },
  892. update: function PDFPageView_update(scale, rotation) {
  893. this.scale = scale || this.scale;
  894. if (typeof rotation !== 'undefined') {
  895. this.rotation = rotation;
  896. }
  897. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  898. this.viewport = this.viewport.clone({
  899. scale: this.scale * CSS_UNITS,
  900. rotation: totalRotation
  901. });
  902. var isScalingRestricted = false;
  903. if (this.canvas && PDFJS.maxCanvasPixels > 0) {
  904. var ctx = this.canvas.getContext('2d');
  905. var outputScale = getOutputScale(ctx);
  906. var pixelsInViewport = this.viewport.width * this.viewport.height;
  907. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  908. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  909. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  910. PDFJS.maxCanvasPixels) {
  911. isScalingRestricted = true;
  912. }
  913. }
  914. if (this.canvas &&
  915. (PDFJS.useOnlyCssZoom ||
  916. (this.hasRestrictedScaling && isScalingRestricted))) {
  917. this.cssTransform(this.canvas, true);
  918. return;
  919. } else if (this.canvas && !this.zoomLayer) {
  920. this.zoomLayer = this.canvas.parentNode;
  921. this.zoomLayer.style.position = 'absolute';
  922. }
  923. if (this.zoomLayer) {
  924. this.cssTransform(this.zoomLayer.firstChild);
  925. }
  926. this.reset(true);
  927. },
  928. /**
  929. * Called when moved in the parent's container.
  930. */
  931. updatePosition: function PDFPageView_updatePosition() {
  932. if (this.textLayer) {
  933. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  934. }
  935. },
  936. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  937. // Scale canvas, canvas wrapper, and page container.
  938. var width = this.viewport.width;
  939. var height = this.viewport.height;
  940. var div = this.div;
  941. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  942. Math.floor(width) + 'px';
  943. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  944. Math.floor(height) + 'px';
  945. // The canvas may have been originally rotated, rotate relative to that.
  946. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  947. var absRotation = Math.abs(relativeRotation);
  948. var scaleX = 1, scaleY = 1;
  949. if (absRotation === 90 || absRotation === 270) {
  950. // Scale x and y because of the rotation.
  951. scaleX = height / width;
  952. scaleY = width / height;
  953. }
  954. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  955. 'scale(' + scaleX + ',' + scaleY + ')';
  956. CustomStyle.setProp('transform', canvas, cssTransform);
  957. if (this.textLayer) {
  958. // Rotating the text layer is more complicated since the divs inside the
  959. // the text layer are rotated.
  960. // TODO: This could probably be simplified by drawing the text layer in
  961. // one orientation then rotating overall.
  962. var textLayerViewport = this.textLayer.viewport;
  963. var textRelativeRotation = this.viewport.rotation -
  964. textLayerViewport.rotation;
  965. var textAbsRotation = Math.abs(textRelativeRotation);
  966. var scale = width / textLayerViewport.width;
  967. if (textAbsRotation === 90 || textAbsRotation === 270) {
  968. scale = width / textLayerViewport.height;
  969. }
  970. var textLayerDiv = this.textLayer.textLayerDiv;
  971. var transX, transY;
  972. switch (textAbsRotation) {
  973. case 0:
  974. transX = transY = 0;
  975. break;
  976. case 90:
  977. transX = 0;
  978. transY = '-' + textLayerDiv.style.height;
  979. break;
  980. case 180:
  981. transX = '-' + textLayerDiv.style.width;
  982. transY = '-' + textLayerDiv.style.height;
  983. break;
  984. case 270:
  985. transX = '-' + textLayerDiv.style.width;
  986. transY = 0;
  987. break;
  988. default:
  989. console.error('Bad rotation value.');
  990. break;
  991. }
  992. CustomStyle.setProp('transform', textLayerDiv,
  993. 'rotate(' + textAbsRotation + 'deg) ' +
  994. 'scale(' + scale + ', ' + scale + ') ' +
  995. 'translate(' + transX + ', ' + transY + ')');
  996. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  997. }
  998. if (redrawAnnotations && this.annotationLayer) {
  999. this.annotationLayer.setupAnnotations(this.viewport);
  1000. }
  1001. },
  1002. get width() {
  1003. return this.viewport.width;
  1004. },
  1005. get height() {
  1006. return this.viewport.height;
  1007. },
  1008. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  1009. return this.viewport.convertToPdfPoint(x, y);
  1010. },
  1011. draw: function PDFPageView_draw() {
  1012. if (this.renderingState !== RenderingStates.INITIAL) {
  1013. console.error('Must be in new state before drawing');
  1014. }
  1015. this.renderingState = RenderingStates.RUNNING;
  1016. var pdfPage = this.pdfPage;
  1017. var viewport = this.viewport;
  1018. var div = this.div;
  1019. // Wrap the canvas so if it has a css transform for highdpi the overflow
  1020. // will be hidden in FF.
  1021. var canvasWrapper = document.createElement('div');
  1022. canvasWrapper.style.width = div.style.width;
  1023. canvasWrapper.style.height = div.style.height;
  1024. canvasWrapper.classList.add('canvasWrapper');
  1025. var canvas = document.createElement('canvas');
  1026. canvas.id = 'page' + this.id;
  1027. canvasWrapper.appendChild(canvas);
  1028. if (this.annotationLayer) {
  1029. // annotationLayer needs to stay on top
  1030. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  1031. } else {
  1032. div.appendChild(canvasWrapper);
  1033. }
  1034. this.canvas = canvas;
  1035. var ctx = canvas.getContext('2d');
  1036. var outputScale = getOutputScale(ctx);
  1037. if (PDFJS.useOnlyCssZoom) {
  1038. var actualSizeViewport = viewport.clone({ scale: CSS_UNITS });
  1039. // Use a scale that will make the canvas be the original intended size
  1040. // of the page.
  1041. outputScale.sx *= actualSizeViewport.width / viewport.width;
  1042. outputScale.sy *= actualSizeViewport.height / viewport.height;
  1043. outputScale.scaled = true;
  1044. }
  1045. if (PDFJS.maxCanvasPixels > 0) {
  1046. var pixelsInViewport = viewport.width * viewport.height;
  1047. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  1048. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  1049. outputScale.sx = maxScale;
  1050. outputScale.sy = maxScale;
  1051. outputScale.scaled = true;
  1052. this.hasRestrictedScaling = true;
  1053. } else {
  1054. this.hasRestrictedScaling = false;
  1055. }
  1056. }
  1057. canvas.width = (Math.floor(viewport.width) * outputScale.sx) | 0;
  1058. canvas.height = (Math.floor(viewport.height) * outputScale.sy) | 0;
  1059. canvas.style.width = Math.floor(viewport.width) + 'px';
  1060. canvas.style.height = Math.floor(viewport.height) + 'px';
  1061. // Add the viewport so it's known what it was originally drawn with.
  1062. canvas._viewport = viewport;
  1063. var textLayerDiv = null;
  1064. var textLayer = null;
  1065. if (this.textLayerFactory) {
  1066. textLayerDiv = document.createElement('div');
  1067. textLayerDiv.className = 'textLayer';
  1068. textLayerDiv.style.width = canvas.style.width;
  1069. textLayerDiv.style.height = canvas.style.height;
  1070. if (this.annotationLayer) {
  1071. // annotationLayer needs to stay on top
  1072. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  1073. } else {
  1074. div.appendChild(textLayerDiv);
  1075. }
  1076. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
  1077. this.id - 1,
  1078. this.viewport);
  1079. }
  1080. this.textLayer = textLayer;
  1081. if (outputScale.scaled) {
  1082. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  1083. ctx._transformMatrix = [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  1084. ctx.scale(outputScale.sx, outputScale.sy);
  1085. }
  1086. var resolveRenderPromise, rejectRenderPromise;
  1087. var promise = new Promise(function (resolve, reject) {
  1088. resolveRenderPromise = resolve;
  1089. rejectRenderPromise = reject;
  1090. });
  1091. // Rendering area
  1092. var self = this;
  1093. function pageViewDrawCallback(error) {
  1094. // The renderTask may have been replaced by a new one, so only remove
  1095. // the reference to the renderTask if it matches the one that is
  1096. // triggering this callback.
  1097. if (renderTask === self.renderTask) {
  1098. self.renderTask = null;
  1099. }
  1100. if (error === 'cancelled') {
  1101. rejectRenderPromise(error);
  1102. return;
  1103. }
  1104. self.renderingState = RenderingStates.FINISHED;
  1105. if (self.loadingIconDiv) {
  1106. div.removeChild(self.loadingIconDiv);
  1107. delete self.loadingIconDiv;
  1108. }
  1109. if (self.zoomLayer) {
  1110. div.removeChild(self.zoomLayer);
  1111. self.zoomLayer = null;
  1112. }
  1113. self.error = error;
  1114. self.stats = pdfPage.stats;
  1115. if (self.onAfterDraw) {
  1116. self.onAfterDraw();
  1117. }
  1118. var event = document.createEvent('CustomEvent');
  1119. event.initCustomEvent('pagerendered', true, true, {
  1120. pageNumber: self.id
  1121. });
  1122. div.dispatchEvent(event);
  1123. if (!error) {
  1124. resolveRenderPromise(undefined);
  1125. } else {
  1126. rejectRenderPromise(error);
  1127. }
  1128. }
  1129. var renderContinueCallback = null;
  1130. if (this.renderingQueue) {
  1131. renderContinueCallback = function renderContinueCallback(cont) {
  1132. if (!self.renderingQueue.isHighestPriority(self)) {
  1133. self.renderingState = RenderingStates.PAUSED;
  1134. self.resume = function resumeCallback() {
  1135. self.renderingState = RenderingStates.RUNNING;
  1136. cont();
  1137. };
  1138. return;
  1139. }
  1140. cont();
  1141. };
  1142. }
  1143. var renderContext = {
  1144. canvasContext: ctx,
  1145. viewport: this.viewport,
  1146. // intent: 'default', // === 'display'
  1147. continueCallback: renderContinueCallback
  1148. };
  1149. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  1150. this.renderTask.promise.then(
  1151. function pdfPageRenderCallback() {
  1152. pageViewDrawCallback(null);
  1153. if (textLayer) {
  1154. self.pdfPage.getTextContent().then(
  1155. function textContentResolved(textContent) {
  1156. textLayer.setTextContent(textContent);
  1157. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  1158. }
  1159. );
  1160. }
  1161. },
  1162. function pdfPageRenderError(error) {
  1163. pageViewDrawCallback(error);
  1164. }
  1165. );
  1166. if (this.annotationsLayerFactory) {
  1167. if (!this.annotationLayer) {
  1168. this.annotationLayer = this.annotationsLayerFactory.
  1169. createAnnotationsLayerBuilder(div, this.pdfPage);
  1170. }
  1171. this.annotationLayer.setupAnnotations(this.viewport);
  1172. }
  1173. div.setAttribute('data-loaded', true);
  1174. if (self.onBeforeDraw) {
  1175. self.onBeforeDraw();
  1176. }
  1177. return promise;
  1178. },
  1179. beforePrint: function PDFPageView_beforePrint() {
  1180. var pdfPage = this.pdfPage;
  1181. var viewport = pdfPage.getViewport(1);
  1182. // Use the same hack we use for high dpi displays for printing to get
  1183. // better output until bug 811002 is fixed in FF.
  1184. var PRINT_OUTPUT_SCALE = 2;
  1185. var canvas = document.createElement('canvas');
  1186. // The logical size of the canvas.
  1187. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  1188. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  1189. // The rendered size of the canvas, relative to the size of canvasWrapper.
  1190. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
  1191. canvas.style.height = (PRINT_OUTPUT_SCALE * 100) + '%';
  1192. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  1193. (1 / PRINT_OUTPUT_SCALE) + ')';
  1194. CustomStyle.setProp('transform' , canvas, cssScale);
  1195. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  1196. var printContainer = document.getElementById('printContainer');
  1197. var canvasWrapper = document.createElement('div');
  1198. canvasWrapper.style.width = viewport.width + 'pt';
  1199. canvasWrapper.style.height = viewport.height + 'pt';
  1200. canvasWrapper.appendChild(canvas);
  1201. printContainer.appendChild(canvasWrapper);
  1202. canvas.mozPrintCallback = function(obj) {
  1203. var ctx = obj.context;
  1204. ctx.save();
  1205. ctx.fillStyle = 'rgb(255, 255, 255)';
  1206. ctx.fillRect(0, 0, canvas.width, canvas.height);
  1207. ctx.restore();
  1208. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  1209. ctx._transformMatrix =
  1210. [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
  1211. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  1212. var renderContext = {
  1213. canvasContext: ctx,
  1214. viewport: viewport,
  1215. intent: 'print'
  1216. };
  1217. pdfPage.render(renderContext).promise.then(function() {
  1218. // Tell the printEngine that rendering this canvas/page has finished.
  1219. obj.done();
  1220. }, function(error) {
  1221. console.error(error);
  1222. // Tell the printEngine that rendering this canvas/page has failed.
  1223. // This will make the print proces stop.
  1224. if ('abort' in obj) {
  1225. obj.abort();
  1226. } else {
  1227. obj.done();
  1228. }
  1229. });
  1230. };
  1231. },
  1232. };
  1233. return PDFPageView;
  1234. })();
  1235. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  1236. var NonWhitespaceRegexp = /\S/;
  1237. function isAllWhitespace(str) {
  1238. return !NonWhitespaceRegexp.test(str);
  1239. }
  1240. /**
  1241. * @typedef {Object} TextLayerBuilderOptions
  1242. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  1243. * @property {number} pageIndex - The page index.
  1244. * @property {PageViewport} viewport - The viewport of the text layer.
  1245. * @property {PDFFindController} findController
  1246. */
  1247. /**
  1248. * TextLayerBuilder provides text-selection functionality for the PDF.
  1249. * It does this by creating overlay divs over the PDF text. These divs
  1250. * contain text that matches the PDF text they are overlaying. This object
  1251. * also provides a way to highlight text that is being searched for.
  1252. * @class
  1253. */
  1254. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  1255. function TextLayerBuilder(options) {
  1256. this.textLayerDiv = options.textLayerDiv;
  1257. this.renderingDone = false;
  1258. this.divContentDone = false;
  1259. this.pageIdx = options.pageIndex;
  1260. this.pageNumber = this.pageIdx + 1;
  1261. this.matches = [];
  1262. this.viewport = options.viewport;
  1263. this.textDivs = [];
  1264. this.findController = options.findController || null;
  1265. }
  1266. TextLayerBuilder.prototype = {
  1267. _finishRendering: function TextLayerBuilder_finishRendering() {
  1268. this.renderingDone = true;
  1269. var event = document.createEvent('CustomEvent');
  1270. event.initCustomEvent('textlayerrendered', true, true, {
  1271. pageNumber: this.pageNumber
  1272. });
  1273. this.textLayerDiv.dispatchEvent(event);
  1274. },
  1275. renderLayer: function TextLayerBuilder_renderLayer() {
  1276. var textLayerFrag = document.createDocumentFragment();
  1277. var textDivs = this.textDivs;
  1278. var textDivsLength = textDivs.length;
  1279. var canvas = document.createElement('canvas');
  1280. var ctx = canvas.getContext('2d');
  1281. // No point in rendering many divs as it would make the browser
  1282. // unusable even after the divs are rendered.
  1283. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  1284. this._finishRendering();
  1285. return;
  1286. }
  1287. var lastFontSize;
  1288. var lastFontFamily;
  1289. for (var i = 0; i < textDivsLength; i++) {
  1290. var textDiv = textDivs[i];
  1291. if (textDiv.dataset.isWhitespace !== undefined) {
  1292. continue;
  1293. }
  1294. var fontSize = textDiv.style.fontSize;
  1295. var fontFamily = textDiv.style.fontFamily;
  1296. // Only build font string and set to context if different from last.
  1297. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  1298. ctx.font = fontSize + ' ' + fontFamily;
  1299. lastFontSize = fontSize;
  1300. lastFontFamily = fontFamily;
  1301. }
  1302. var width = ctx.measureText(textDiv.textContent).width;
  1303. if (width > 0) {
  1304. textLayerFrag.appendChild(textDiv);
  1305. var transform;
  1306. if (textDiv.dataset.canvasWidth !== undefined) {
  1307. // Dataset values come of type string.
  1308. var textScale = textDiv.dataset.canvasWidth / width;
  1309. transform = 'scaleX(' + textScale + ')';
  1310. } else {
  1311. transform = '';
  1312. }
  1313. var rotation = textDiv.dataset.angle;
  1314. if (rotation) {
  1315. transform = 'rotate(' + rotation + 'deg) ' + transform;
  1316. }
  1317. if (transform) {
  1318. CustomStyle.setProp('transform' , textDiv, transform);
  1319. }
  1320. }
  1321. }
  1322. this.textLayerDiv.appendChild(textLayerFrag);
  1323. this._finishRendering();
  1324. this.updateMatches();
  1325. },
  1326. /**
  1327. * Renders the text layer.
  1328. * @param {number} timeout (optional) if specified, the rendering waits
  1329. * for specified amount of ms.
  1330. */
  1331. render: function TextLayerBuilder_render(timeout) {
  1332. if (!this.divContentDone || this.renderingDone) {
  1333. return;
  1334. }
  1335. if (this.renderTimer) {
  1336. clearTimeout(this.renderTimer);
  1337. this.renderTimer = null;
  1338. }
  1339. if (!timeout) { // Render right away
  1340. this.renderLayer();
  1341. } else { // Schedule
  1342. var self = this;
  1343. this.renderTimer = setTimeout(function() {
  1344. self.renderLayer();
  1345. self.renderTimer = null;
  1346. }, timeout);
  1347. }
  1348. },
  1349. appendText: function TextLayerBuilder_appendText(geom, styles) {
  1350. var style = styles[geom.fontName];
  1351. var textDiv = document.createElement('div');
  1352. this.textDivs.push(textDiv);
  1353. if (isAllWhitespace(geom.str)) {
  1354. textDiv.dataset.isWhitespace = true;
  1355. return;
  1356. }
  1357. var tx = PDFJS.Util.transform(this.viewport.transform, geom.transform);
  1358. var angle = Math.atan2(tx[1], tx[0]);
  1359. if (style.vertical) {
  1360. angle += Math.PI / 2;
  1361. }
  1362. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  1363. var fontAscent = fontHeight;
  1364. if (style.ascent) {
  1365. fontAscent = style.ascent * fontAscent;
  1366. } else if (style.descent) {
  1367. fontAscent = (1 + style.descent) * fontAscent;
  1368. }
  1369. var left;
  1370. var top;
  1371. if (angle === 0) {
  1372. left = tx[4];
  1373. top = tx[5] - fontAscent;
  1374. } else {
  1375. left = tx[4] + (fontAscent * Math.sin(angle));
  1376. top = tx[5] - (fontAscent * Math.cos(angle));
  1377. }
  1378. textDiv.style.left = left + 'px';
  1379. textDiv.style.top = top + 'px';
  1380. textDiv.style.fontSize = fontHeight + 'px';
  1381. textDiv.style.fontFamily = style.fontFamily;
  1382. textDiv.textContent = geom.str;
  1383. // |fontName| is only used by the Font Inspector. This test will succeed
  1384. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  1385. // not worth the effort to do a more accurate test.
  1386. if (PDFJS.pdfBug) {
  1387. textDiv.dataset.fontName = geom.fontName;
  1388. }
  1389. // Storing into dataset will convert number into string.
  1390. if (angle !== 0) {
  1391. textDiv.dataset.angle = angle * (180 / Math.PI);
  1392. }
  1393. // We don't bother scaling single-char text divs, because it has very
  1394. // little effect on text highlighting. This makes scrolling on docs with
  1395. // lots of such divs a lot faster.
  1396. if (geom.str.length > 1) {
  1397. if (style.vertical) {
  1398. textDiv.dataset.canvasWidth = geom.height * this.viewport.scale;
  1399. } else {
  1400. textDiv.dataset.canvasWidth = geom.width * this.viewport.scale;
  1401. }
  1402. }
  1403. },
  1404. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  1405. this.textContent = textContent;
  1406. var textItems = textContent.items;
  1407. for (var i = 0, len = textItems.length; i < len; i++) {
  1408. this.appendText(textItems[i], textContent.styles);
  1409. }
  1410. this.divContentDone = true;
  1411. },
  1412. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  1413. var i = 0;
  1414. var iIndex = 0;
  1415. var bidiTexts = this.textContent.items;
  1416. var end = bidiTexts.length - 1;
  1417. var queryLen = (this.findController === null ?
  1418. 0 : this.findController.state.query.length);
  1419. var ret = [];
  1420. for (var m = 0, len = matches.length; m < len; m++) {
  1421. // Calculate the start position.
  1422. var matchIdx = matches[m];
  1423. // Loop over the divIdxs.
  1424. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  1425. iIndex += bidiTexts[i].str.length;
  1426. i++;
  1427. }
  1428. if (i === bidiTexts.length) {
  1429. console.error('Could not find a matching mapping');
  1430. }
  1431. var match = {
  1432. begin: {
  1433. divIdx: i,
  1434. offset: matchIdx - iIndex
  1435. }
  1436. };
  1437. // Calculate the end position.
  1438. matchIdx += queryLen;
  1439. // Somewhat the same array as above, but use > instead of >= to get
  1440. // the end position right.
  1441. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  1442. iIndex += bidiTexts[i].str.length;
  1443. i++;
  1444. }
  1445. match.end = {
  1446. divIdx: i,
  1447. offset: matchIdx - iIndex
  1448. };
  1449. ret.push(match);
  1450. }
  1451. return ret;
  1452. },
  1453. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  1454. // Early exit if there is nothing to render.
  1455. if (matches.length === 0) {
  1456. return;
  1457. }
  1458. var bidiTexts = this.textContent.items;
  1459. var textDivs = this.textDivs;
  1460. var prevEnd = null;
  1461. var pageIdx = this.pageIdx;
  1462. var isSelectedPage = (this.findController === null ?
  1463. false : (pageIdx === this.findController.selected.pageIdx));
  1464. var selectedMatchIdx = (this.findController === null ?
  1465. -1 : this.findController.selected.matchIdx);
  1466. var highlightAll = (this.findController === null ?
  1467. false : this.findController.state.highlightAll);
  1468. var infinity = {
  1469. divIdx: -1,
  1470. offset: undefined
  1471. };
  1472. function beginText(begin, className) {
  1473. var divIdx = begin.divIdx;
  1474. textDivs[divIdx].textContent = '';
  1475. appendTextToDiv(divIdx, 0, begin.offset, className);
  1476. }
  1477. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  1478. var div = textDivs[divIdx];
  1479. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  1480. var node = document.createTextNode(content);
  1481. if (className) {
  1482. var span = document.createElement('span');
  1483. span.className = className;
  1484. span.appendChild(node);
  1485. div.appendChild(span);
  1486. return;
  1487. }
  1488. div.appendChild(node);
  1489. }
  1490. var i0 = selectedMatchIdx, i1 = i0 + 1;
  1491. if (highlightAll) {
  1492. i0 = 0;
  1493. i1 = matches.length;
  1494. } else if (!isSelectedPage) {
  1495. // Not highlighting all and this isn't the selected page, so do nothing.
  1496. return;
  1497. }
  1498. for (var i = i0; i < i1; i++) {
  1499. var match = matches[i];
  1500. var begin = match.begin;
  1501. var end = match.end;
  1502. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  1503. var highlightSuffix = (isSelected ? ' selected' : '');
  1504. if (this.findController) {
  1505. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  1506. begin.divIdx, end.divIdx);
  1507. }
  1508. // Match inside new div.
  1509. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  1510. // If there was a previous div, then add the text at the end.
  1511. if (prevEnd !== null) {
  1512. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1513. }
  1514. // Clear the divs and set the content until the starting point.
  1515. beginText(begin);
  1516. } else {
  1517. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  1518. }
  1519. if (begin.divIdx === end.divIdx) {
  1520. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  1521. 'highlight' + highlightSuffix);
  1522. } else {
  1523. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  1524. 'highlight begin' + highlightSuffix);
  1525. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  1526. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  1527. }
  1528. beginText(end, 'highlight end' + highlightSuffix);
  1529. }
  1530. prevEnd = end;
  1531. }
  1532. if (prevEnd) {
  1533. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1534. }
  1535. },
  1536. updateMatches: function TextLayerBuilder_updateMatches() {
  1537. // Only show matches when all rendering is done.
  1538. if (!this.renderingDone) {
  1539. return;
  1540. }
  1541. // Clear all matches.
  1542. var matches = this.matches;
  1543. var textDivs = this.textDivs;
  1544. var bidiTexts = this.textContent.items;
  1545. var clearedUntilDivIdx = -1;
  1546. // Clear all current matches.
  1547. for (var i = 0, len = matches.length; i < len; i++) {
  1548. var match = matches[i];
  1549. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  1550. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  1551. var div = textDivs[n];
  1552. div.textContent = bidiTexts[n].str;
  1553. div.className = '';
  1554. }
  1555. clearedUntilDivIdx = match.end.divIdx + 1;
  1556. }
  1557. if (this.findController === null || !this.findController.active) {
  1558. return;
  1559. }
  1560. // Convert the matches on the page controller into the match format
  1561. // used for the textLayer.
  1562. this.matches = this.convertMatches(this.findController === null ?
  1563. [] : (this.findController.pageMatches[this.pageIdx] || []));
  1564. this.renderMatches(this.matches);
  1565. }
  1566. };
  1567. return TextLayerBuilder;
  1568. })();
  1569. /**
  1570. * @constructor
  1571. * @implements IPDFTextLayerFactory
  1572. */
  1573. function DefaultTextLayerFactory() {}
  1574. DefaultTextLayerFactory.prototype = {
  1575. /**
  1576. * @param {HTMLDivElement} textLayerDiv
  1577. * @param {number} pageIndex
  1578. * @param {PageViewport} viewport
  1579. * @returns {TextLayerBuilder}
  1580. */
  1581. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  1582. return new TextLayerBuilder({
  1583. textLayerDiv: textLayerDiv,
  1584. pageIndex: pageIndex,
  1585. viewport: viewport
  1586. });
  1587. }
  1588. };
  1589. /**
  1590. * @typedef {Object} AnnotationsLayerBuilderOptions
  1591. * @property {HTMLDivElement} pageDiv
  1592. * @property {PDFPage} pdfPage
  1593. * @property {IPDFLinkService} linkService
  1594. */
  1595. /**
  1596. * @class
  1597. */
  1598. var AnnotationsLayerBuilder = (function AnnotationsLayerBuilderClosure() {
  1599. /**
  1600. * @param {AnnotationsLayerBuilderOptions} options
  1601. * @constructs AnnotationsLayerBuilder
  1602. */
  1603. function AnnotationsLayerBuilder(options) {
  1604. this.pageDiv = options.pageDiv;
  1605. this.pdfPage = options.pdfPage;
  1606. this.linkService = options.linkService;
  1607. this.div = null;
  1608. }
  1609. AnnotationsLayerBuilder.prototype =
  1610. /** @lends AnnotationsLayerBuilder.prototype */ {
  1611. /**
  1612. * @param {PageViewport} viewport
  1613. */
  1614. setupAnnotations:
  1615. function AnnotationsLayerBuilder_setupAnnotations(viewport) {
  1616. function bindLink(link, dest) {
  1617. link.href = linkService.getDestinationHash(dest);
  1618. link.onclick = function annotationsLayerBuilderLinksOnclick() {
  1619. if (dest) {
  1620. linkService.navigateTo(dest);
  1621. }
  1622. return false;
  1623. };
  1624. if (dest) {
  1625. link.className = 'internalLink';
  1626. }
  1627. }
  1628. function bindNamedAction(link, action) {
  1629. link.href = linkService.getAnchorUrl('');
  1630. link.onclick = function annotationsLayerBuilderNamedActionOnClick() {
  1631. linkService.executeNamedAction(action);
  1632. return false;
  1633. };
  1634. link.className = 'internalLink';
  1635. }
  1636. var linkService = this.linkService;
  1637. var pdfPage = this.pdfPage;
  1638. var self = this;
  1639. pdfPage.getAnnotations().then(function (annotationsData) {
  1640. viewport = viewport.clone({ dontFlip: true });
  1641. var transform = viewport.transform;
  1642. var transformStr = 'matrix(' + transform.join(',') + ')';
  1643. var data, element, i, ii;
  1644. if (self.div) {
  1645. // If an annotationLayer already exists, refresh its children's
  1646. // transformation matrices
  1647. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  1648. data = annotationsData[i];
  1649. element = self.div.querySelector(
  1650. '[data-annotation-id="' + data.id + '"]');
  1651. if (element) {
  1652. CustomStyle.setProp('transform', element, transformStr);
  1653. }
  1654. }
  1655. // See PDFPageView.reset()
  1656. self.div.removeAttribute('hidden');
  1657. } else {
  1658. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  1659. data = annotationsData[i];
  1660. if (!data || !data.hasHtml) {
  1661. continue;
  1662. }
  1663. element = PDFJS.AnnotationUtils.getHtmlElement(data,
  1664. pdfPage.commonObjs);
  1665. element.setAttribute('data-annotation-id', data.id);
  1666. if (typeof mozL10n !== 'undefined') {
  1667. mozL10n.translate(element);
  1668. }
  1669. var rect = data.rect;
  1670. var view = pdfPage.view;
  1671. rect = PDFJS.Util.normalizeRect([
  1672. rect[0],
  1673. view[3] - rect[1] + view[1],
  1674. rect[2],
  1675. view[3] - rect[3] + view[1]
  1676. ]);
  1677. element.style.left = rect[0] + 'px';
  1678. element.style.top = rect[1] + 'px';
  1679. element.style.position = 'absolute';
  1680. CustomStyle.setProp('transform', element, transformStr);
  1681. var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
  1682. CustomStyle.setProp('transformOrigin', element, transformOriginStr);
  1683. if (data.subtype === 'Link' && !data.url) {
  1684. var link = element.getElementsByTagName('a')[0];
  1685. if (link) {
  1686. if (data.action) {
  1687. bindNamedAction(link, data.action);
  1688. } else {
  1689. bindLink(link, ('dest' in data) ? data.dest : null);
  1690. }
  1691. }
  1692. }
  1693. if (!self.div) {
  1694. var annotationLayerDiv = document.createElement('div');
  1695. annotationLayerDiv.className = 'annotationLayer';
  1696. self.pageDiv.appendChild(annotationLayerDiv);
  1697. self.div = annotationLayerDiv;
  1698. }
  1699. self.div.appendChild(element);
  1700. }
  1701. }
  1702. });
  1703. },
  1704. hide: function () {
  1705. if (!this.div) {
  1706. return;
  1707. }
  1708. this.div.setAttribute('hidden', 'true');
  1709. }
  1710. };
  1711. return AnnotationsLayerBuilder;
  1712. })();
  1713. /**
  1714. * @constructor
  1715. * @implements IPDFAnnotationsLayerFactory
  1716. */
  1717. function DefaultAnnotationsLayerFactory() {}
  1718. DefaultAnnotationsLayerFactory.prototype = {
  1719. /**
  1720. * @param {HTMLDivElement} pageDiv
  1721. * @param {PDFPage} pdfPage
  1722. * @returns {AnnotationsLayerBuilder}
  1723. */
  1724. createAnnotationsLayerBuilder: function (pageDiv, pdfPage) {
  1725. return new AnnotationsLayerBuilder({
  1726. pageDiv: pageDiv,
  1727. pdfPage: pdfPage,
  1728. linkService: new SimpleLinkService(),
  1729. });
  1730. }
  1731. };
  1732. /**
  1733. * @typedef {Object} PDFViewerOptions
  1734. * @property {HTMLDivElement} container - The container for the viewer element.
  1735. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  1736. * @property {IPDFLinkService} linkService - The navigation/linking service.
  1737. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  1738. * queue object.
  1739. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  1740. * around the pages. The default is false.
  1741. */
  1742. /**
  1743. * Simple viewer control to display PDF content/pages.
  1744. * @class
  1745. * @implements {IRenderableView}
  1746. */
  1747. var PDFViewer = (function pdfViewer() {
  1748. function PDFPageViewBuffer(size) {
  1749. var data = [];
  1750. this.push = function cachePush(view) {
  1751. var i = data.indexOf(view);
  1752. if (i >= 0) {
  1753. data.splice(i, 1);
  1754. }
  1755. data.push(view);
  1756. if (data.length > size) {
  1757. data.shift().destroy();
  1758. }
  1759. };
  1760. this.resize = function (newSize) {
  1761. size = newSize;
  1762. while (data.length > size) {
  1763. data.shift().destroy();
  1764. }
  1765. };
  1766. }
  1767. function isSameScale(oldScale, newScale) {
  1768. if (newScale === oldScale) {
  1769. return true;
  1770. }
  1771. if (Math.abs(newScale - oldScale) < 1e-15) {
  1772. // Prevent unnecessary re-rendering of all pages when the scale
  1773. // changes only because of limited numerical precision.
  1774. return true;
  1775. }
  1776. return false;
  1777. }
  1778. /**
  1779. * @constructs PDFViewer
  1780. * @param {PDFViewerOptions} options
  1781. */
  1782. function PDFViewer(options) {
  1783. this.container = options.container;
  1784. this.viewer = options.viewer || options.container.firstElementChild;
  1785. this.linkService = options.linkService || new SimpleLinkService();
  1786. this.removePageBorders = options.removePageBorders || false;
  1787. this.defaultRenderingQueue = !options.renderingQueue;
  1788. if (this.defaultRenderingQueue) {
  1789. // Custom rendering queue is not specified, using default one
  1790. this.renderingQueue = new PDFRenderingQueue();
  1791. this.renderingQueue.setViewer(this);
  1792. } else {
  1793. this.renderingQueue = options.renderingQueue;
  1794. }
  1795. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  1796. this.updateInProgress = false;
  1797. this.presentationModeState = PresentationModeState.UNKNOWN;
  1798. this._resetView();
  1799. if (this.removePageBorders) {
  1800. this.viewer.classList.add('removePageBorders');
  1801. }
  1802. }
  1803. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  1804. get pagesCount() {
  1805. return this._pages.length;
  1806. },
  1807. getPageView: function (index) {
  1808. return this._pages[index];
  1809. },
  1810. get currentPageNumber() {
  1811. return this._currentPageNumber;
  1812. },
  1813. set currentPageNumber(val) {
  1814. if (!this.pdfDocument) {
  1815. this._currentPageNumber = val;
  1816. return;
  1817. }
  1818. var event = document.createEvent('UIEvents');
  1819. event.initUIEvent('pagechange', true, true, window, 0);
  1820. event.updateInProgress = this.updateInProgress;
  1821. if (!(0 < val && val <= this.pagesCount)) {
  1822. event.pageNumber = this._currentPageNumber;
  1823. event.previousPageNumber = val;
  1824. this.container.dispatchEvent(event);
  1825. return;
  1826. }
  1827. event.previousPageNumber = this._currentPageNumber;
  1828. this._currentPageNumber = val;
  1829. event.pageNumber = val;
  1830. this.container.dispatchEvent(event);
  1831. // Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
  1832. if (this.updateInProgress) {
  1833. return;
  1834. }
  1835. this.scrollPageIntoView(val);
  1836. },
  1837. /**
  1838. * @returns {number}
  1839. */
  1840. get currentScale() {
  1841. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  1842. DEFAULT_SCALE;
  1843. },
  1844. /**
  1845. * @param {number} val - Scale of the pages in percents.
  1846. */
  1847. set currentScale(val) {
  1848. if (isNaN(val)) {
  1849. throw new Error('Invalid numeric scale');
  1850. }
  1851. if (!this.pdfDocument) {
  1852. this._currentScale = val;
  1853. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  1854. return;
  1855. }
  1856. this._setScale(val, false);
  1857. },
  1858. /**
  1859. * @returns {string}
  1860. */
  1861. get currentScaleValue() {
  1862. return this._currentScaleValue;
  1863. },
  1864. /**
  1865. * @param val - The scale of the pages (in percent or predefined value).
  1866. */
  1867. set currentScaleValue(val) {
  1868. if (!this.pdfDocument) {
  1869. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  1870. this._currentScaleValue = val;
  1871. return;
  1872. }
  1873. this._setScale(val, false);
  1874. },
  1875. /**
  1876. * @returns {number}
  1877. */
  1878. get pagesRotation() {
  1879. return this._pagesRotation;
  1880. },
  1881. /**
  1882. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  1883. */
  1884. set pagesRotation(rotation) {
  1885. this._pagesRotation = rotation;
  1886. for (var i = 0, l = this._pages.length; i < l; i++) {
  1887. var pageView = this._pages[i];
  1888. pageView.update(pageView.scale, rotation);
  1889. }
  1890. this._setScale(this._currentScaleValue, true);
  1891. if (this.defaultRenderingQueue) {
  1892. this.update();
  1893. }
  1894. },
  1895. /**
  1896. * @param pdfDocument {PDFDocument}
  1897. */
  1898. setDocument: function (pdfDocument) {
  1899. if (this.pdfDocument) {
  1900. this._resetView();
  1901. }
  1902. this.pdfDocument = pdfDocument;
  1903. if (!pdfDocument) {
  1904. return;
  1905. }
  1906. var pagesCount = pdfDocument.numPages;
  1907. var self = this;
  1908. var resolvePagesPromise;
  1909. var pagesPromise = new Promise(function (resolve) {
  1910. resolvePagesPromise = resolve;
  1911. });
  1912. this.pagesPromise = pagesPromise;
  1913. pagesPromise.then(function () {
  1914. var event = document.createEvent('CustomEvent');
  1915. event.initCustomEvent('pagesloaded', true, true, {
  1916. pagesCount: pagesCount
  1917. });
  1918. self.container.dispatchEvent(event);
  1919. });
  1920. var isOnePageRenderedResolved = false;
  1921. var resolveOnePageRendered = null;
  1922. var onePageRendered = new Promise(function (resolve) {
  1923. resolveOnePageRendered = resolve;
  1924. });
  1925. this.onePageRendered = onePageRendered;
  1926. var bindOnAfterAndBeforeDraw = function (pageView) {
  1927. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  1928. // Add the page to the buffer at the start of drawing. That way it can
  1929. // be evicted from the buffer and destroyed even if we pause its
  1930. // rendering.
  1931. self._buffer.push(this);
  1932. };
  1933. // when page is painted, using the image as thumbnail base
  1934. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  1935. if (!isOnePageRenderedResolved) {
  1936. isOnePageRenderedResolved = true;
  1937. resolveOnePageRendered();
  1938. }
  1939. };
  1940. };
  1941. var firstPagePromise = pdfDocument.getPage(1);
  1942. this.firstPagePromise = firstPagePromise;
  1943. // Fetch a single page so we can get a viewport that will be the default
  1944. // viewport for all pages
  1945. return firstPagePromise.then(function(pdfPage) {
  1946. var scale = this.currentScale;
  1947. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  1948. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1949. var textLayerFactory = null;
  1950. if (!PDFJS.disableTextLayer) {
  1951. textLayerFactory = this;
  1952. }
  1953. var pageView = new PDFPageView({
  1954. container: this.viewer,
  1955. id: pageNum,
  1956. scale: scale,
  1957. defaultViewport: viewport.clone(),
  1958. renderingQueue: this.renderingQueue,
  1959. textLayerFactory: textLayerFactory,
  1960. annotationsLayerFactory: this
  1961. });
  1962. bindOnAfterAndBeforeDraw(pageView);
  1963. this._pages.push(pageView);
  1964. }
  1965. var linkService = this.linkService;
  1966. // Fetch all the pages since the viewport is needed before printing
  1967. // starts to create the correct size canvas. Wait until one page is
  1968. // rendered so we don't tie up too many resources early on.
  1969. onePageRendered.then(function () {
  1970. if (!PDFJS.disableAutoFetch) {
  1971. var getPagesLeft = pagesCount;
  1972. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1973. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  1974. var pageView = self._pages[pageNum - 1];
  1975. if (!pageView.pdfPage) {
  1976. pageView.setPdfPage(pdfPage);
  1977. }
  1978. linkService.cachePageRef(pageNum, pdfPage.ref);
  1979. getPagesLeft--;
  1980. if (!getPagesLeft) {
  1981. resolvePagesPromise();
  1982. }
  1983. }.bind(null, pageNum));
  1984. }
  1985. } else {
  1986. // XXX: Printing is semi-broken with auto fetch disabled.
  1987. resolvePagesPromise();
  1988. }
  1989. });
  1990. var event = document.createEvent('CustomEvent');
  1991. event.initCustomEvent('pagesinit', true, true, null);
  1992. self.container.dispatchEvent(event);
  1993. if (this.defaultRenderingQueue) {
  1994. this.update();
  1995. }
  1996. if (this.findController) {
  1997. this.findController.resolveFirstPage();
  1998. }
  1999. }.bind(this));
  2000. },
  2001. _resetView: function () {
  2002. this._pages = [];
  2003. this._currentPageNumber = 1;
  2004. this._currentScale = UNKNOWN_SCALE;
  2005. this._currentScaleValue = null;
  2006. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  2007. this._location = null;
  2008. this._pagesRotation = 0;
  2009. this._pagesRequests = [];
  2010. var container = this.viewer;
  2011. while (container.hasChildNodes()) {
  2012. container.removeChild(container.lastChild);
  2013. }
  2014. },
  2015. _scrollUpdate: function PDFViewer_scrollUpdate() {
  2016. if (this.pagesCount === 0) {
  2017. return;
  2018. }
  2019. this.update();
  2020. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2021. this._pages[i].updatePosition();
  2022. }
  2023. },
  2024. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  2025. newScale, newValue, preset) {
  2026. var event = document.createEvent('UIEvents');
  2027. event.initUIEvent('scalechange', true, true, window, 0);
  2028. event.scale = newScale;
  2029. if (preset) {
  2030. event.presetValue = newValue;
  2031. }
  2032. this.container.dispatchEvent(event);
  2033. },
  2034. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  2035. newScale, newValue, noScroll, preset) {
  2036. this._currentScaleValue = newValue;
  2037. if (isSameScale(this._currentScale, newScale)) {
  2038. if (preset) {
  2039. this._setScaleDispatchEvent(newScale, newValue, true);
  2040. }
  2041. return;
  2042. }
  2043. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2044. this._pages[i].update(newScale);
  2045. }
  2046. this._currentScale = newScale;
  2047. if (!noScroll) {
  2048. var page = this._currentPageNumber, dest;
  2049. if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
  2050. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  2051. page = this._location.pageNumber;
  2052. dest = [null, { name: 'XYZ' }, this._location.left,
  2053. this._location.top, null];
  2054. }
  2055. this.scrollPageIntoView(page, dest);
  2056. }
  2057. this._setScaleDispatchEvent(newScale, newValue, preset);
  2058. if (this.defaultRenderingQueue) {
  2059. this.update();
  2060. }
  2061. },
  2062. _setScale: function pdfViewer_setScale(value, noScroll) {
  2063. var scale = parseFloat(value);
  2064. if (scale > 0) {
  2065. this._setScaleUpdatePages(scale, value, noScroll, false);
  2066. } else {
  2067. var currentPage = this._pages[this._currentPageNumber - 1];
  2068. if (!currentPage) {
  2069. return;
  2070. }
  2071. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  2072. 0 : SCROLLBAR_PADDING;
  2073. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  2074. 0 : VERTICAL_PADDING;
  2075. var pageWidthScale = (this.container.clientWidth - hPadding) /
  2076. currentPage.width * currentPage.scale;
  2077. var pageHeightScale = (this.container.clientHeight - vPadding) /
  2078. currentPage.height * currentPage.scale;
  2079. switch (value) {
  2080. case 'page-actual':
  2081. scale = 1;
  2082. break;
  2083. case 'page-width':
  2084. scale = pageWidthScale;
  2085. break;
  2086. case 'page-height':
  2087. scale = pageHeightScale;
  2088. break;
  2089. case 'page-fit':
  2090. scale = Math.min(pageWidthScale, pageHeightScale);
  2091. break;
  2092. case 'auto':
  2093. var isLandscape = (currentPage.width > currentPage.height);
  2094. // For pages in landscape mode, fit the page height to the viewer
  2095. // *unless* the page would thus become too wide to fit horizontally.
  2096. var horizontalScale = isLandscape ?
  2097. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  2098. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  2099. break;
  2100. default:
  2101. console.error('pdfViewSetScale: \'' + value +
  2102. '\' is an unknown zoom value.');
  2103. return;
  2104. }
  2105. this._setScaleUpdatePages(scale, value, noScroll, true);
  2106. }
  2107. },
  2108. /**
  2109. * Scrolls page into view.
  2110. * @param {number} pageNumber
  2111. * @param {Array} dest - (optional) original PDF destination array:
  2112. * <page-ref> </XYZ|FitXXX> <args..>
  2113. */
  2114. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  2115. dest) {
  2116. var pageView = this._pages[pageNumber - 1];
  2117. if (this.isInPresentationMode) {
  2118. if (this._currentPageNumber !== pageView.id) {
  2119. // Avoid breaking getVisiblePages in presentation mode.
  2120. this.currentPageNumber = pageView.id;
  2121. return;
  2122. }
  2123. dest = null;
  2124. // Fixes the case when PDF has different page sizes.
  2125. this._setScale(this._currentScaleValue, true);
  2126. }
  2127. if (!dest) {
  2128. scrollIntoView(pageView.div);
  2129. return;
  2130. }
  2131. var x = 0, y = 0;
  2132. var width = 0, height = 0, widthScale, heightScale;
  2133. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  2134. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  2135. pageView.scale / CSS_UNITS;
  2136. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  2137. pageView.scale / CSS_UNITS;
  2138. var scale = 0;
  2139. switch (dest[1].name) {
  2140. case 'XYZ':
  2141. x = dest[2];
  2142. y = dest[3];
  2143. scale = dest[4];
  2144. // If x and/or y coordinates are not supplied, default to
  2145. // _top_ left of the page (not the obvious bottom left,
  2146. // since aligning the bottom of the intended page with the
  2147. // top of the window is rarely helpful).
  2148. x = x !== null ? x : 0;
  2149. y = y !== null ? y : pageHeight;
  2150. break;
  2151. case 'Fit':
  2152. case 'FitB':
  2153. scale = 'page-fit';
  2154. break;
  2155. case 'FitH':
  2156. case 'FitBH':
  2157. y = dest[2];
  2158. scale = 'page-width';
  2159. break;
  2160. case 'FitV':
  2161. case 'FitBV':
  2162. x = dest[2];
  2163. width = pageWidth;
  2164. height = pageHeight;
  2165. scale = 'page-height';
  2166. break;
  2167. case 'FitR':
  2168. x = dest[2];
  2169. y = dest[3];
  2170. width = dest[4] - x;
  2171. height = dest[5] - y;
  2172. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  2173. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  2174. widthScale = (this.container.clientWidth - hPadding) /
  2175. width / CSS_UNITS;
  2176. heightScale = (this.container.clientHeight - vPadding) /
  2177. height / CSS_UNITS;
  2178. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  2179. break;
  2180. default:
  2181. return;
  2182. }
  2183. if (scale && scale !== this._currentScale) {
  2184. this.currentScaleValue = scale;
  2185. } else if (this._currentScale === UNKNOWN_SCALE) {
  2186. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  2187. }
  2188. if (scale === 'page-fit' && !dest[4]) {
  2189. scrollIntoView(pageView.div);
  2190. return;
  2191. }
  2192. var boundingRect = [
  2193. pageView.viewport.convertToViewportPoint(x, y),
  2194. pageView.viewport.convertToViewportPoint(x + width, y + height)
  2195. ];
  2196. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  2197. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  2198. scrollIntoView(pageView.div, { left: left, top: top });
  2199. },
  2200. _updateLocation: function (firstPage) {
  2201. var currentScale = this._currentScale;
  2202. var currentScaleValue = this._currentScaleValue;
  2203. var normalizedScaleValue =
  2204. parseFloat(currentScaleValue) === currentScale ?
  2205. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  2206. var pageNumber = firstPage.id;
  2207. var pdfOpenParams = '#page=' + pageNumber;
  2208. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  2209. var currentPageView = this._pages[pageNumber - 1];
  2210. var container = this.container;
  2211. var topLeft = currentPageView.getPagePoint(
  2212. (container.scrollLeft - firstPage.x),
  2213. (container.scrollTop - firstPage.y));
  2214. var intLeft = Math.round(topLeft[0]);
  2215. var intTop = Math.round(topLeft[1]);
  2216. pdfOpenParams += ',' + intLeft + ',' + intTop;
  2217. this._location = {
  2218. pageNumber: pageNumber,
  2219. scale: normalizedScaleValue,
  2220. top: intTop,
  2221. left: intLeft,
  2222. pdfOpenParams: pdfOpenParams
  2223. };
  2224. },
  2225. update: function PDFViewer_update() {
  2226. var visible = this._getVisiblePages();
  2227. var visiblePages = visible.views;
  2228. if (visiblePages.length === 0) {
  2229. return;
  2230. }
  2231. this.updateInProgress = true;
  2232. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  2233. 2 * visiblePages.length + 1);
  2234. this._buffer.resize(suggestedCacheSize);
  2235. this.renderingQueue.renderHighestPriority(visible);
  2236. var currentId = this._currentPageNumber;
  2237. var firstPage = visible.first;
  2238. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  2239. i < ii; ++i) {
  2240. var page = visiblePages[i];
  2241. if (page.percent < 100) {
  2242. break;
  2243. }
  2244. if (page.id === currentId) {
  2245. stillFullyVisible = true;
  2246. break;
  2247. }
  2248. }
  2249. if (!stillFullyVisible) {
  2250. currentId = visiblePages[0].id;
  2251. }
  2252. if (!this.isInPresentationMode) {
  2253. this.currentPageNumber = currentId;
  2254. }
  2255. this._updateLocation(firstPage);
  2256. this.updateInProgress = false;
  2257. var event = document.createEvent('UIEvents');
  2258. event.initUIEvent('updateviewarea', true, true, window, 0);
  2259. event.location = this._location;
  2260. this.container.dispatchEvent(event);
  2261. },
  2262. containsElement: function (element) {
  2263. return this.container.contains(element);
  2264. },
  2265. focus: function () {
  2266. this.container.focus();
  2267. },
  2268. get isInPresentationMode() {
  2269. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  2270. },
  2271. get isChangingPresentationMode() {
  2272. return this.PresentationModeState === PresentationModeState.CHANGING;
  2273. },
  2274. get isHorizontalScrollbarEnabled() {
  2275. return (this.isInPresentationMode ?
  2276. false : (this.container.scrollWidth > this.container.clientWidth));
  2277. },
  2278. _getVisiblePages: function () {
  2279. if (!this.isInPresentationMode) {
  2280. return getVisibleElements(this.container, this._pages, true);
  2281. } else {
  2282. // The algorithm in getVisibleElements doesn't work in all browsers and
  2283. // configurations when presentation mode is active.
  2284. var visible = [];
  2285. var currentPage = this._pages[this._currentPageNumber - 1];
  2286. visible.push({ id: currentPage.id, view: currentPage });
  2287. return { first: currentPage, last: currentPage, views: visible };
  2288. }
  2289. },
  2290. cleanup: function () {
  2291. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2292. if (this._pages[i] &&
  2293. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  2294. this._pages[i].reset();
  2295. }
  2296. }
  2297. },
  2298. /**
  2299. * @param {PDFPageView} pageView
  2300. * @returns {PDFPage}
  2301. * @private
  2302. */
  2303. _ensurePdfPageLoaded: function (pageView) {
  2304. if (pageView.pdfPage) {
  2305. return Promise.resolve(pageView.pdfPage);
  2306. }
  2307. var pageNumber = pageView.id;
  2308. if (this._pagesRequests[pageNumber]) {
  2309. return this._pagesRequests[pageNumber];
  2310. }
  2311. var promise = this.pdfDocument.getPage(pageNumber).then(
  2312. function (pdfPage) {
  2313. pageView.setPdfPage(pdfPage);
  2314. this._pagesRequests[pageNumber] = null;
  2315. return pdfPage;
  2316. }.bind(this));
  2317. this._pagesRequests[pageNumber] = promise;
  2318. return promise;
  2319. },
  2320. forceRendering: function (currentlyVisiblePages) {
  2321. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  2322. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  2323. this._pages,
  2324. this.scroll.down);
  2325. if (pageView) {
  2326. this._ensurePdfPageLoaded(pageView).then(function () {
  2327. this.renderingQueue.renderView(pageView);
  2328. }.bind(this));
  2329. return true;
  2330. }
  2331. return false;
  2332. },
  2333. getPageTextContent: function (pageIndex) {
  2334. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  2335. return page.getTextContent();
  2336. });
  2337. },
  2338. /**
  2339. * @param {HTMLDivElement} textLayerDiv
  2340. * @param {number} pageIndex
  2341. * @param {PageViewport} viewport
  2342. * @returns {TextLayerBuilder}
  2343. */
  2344. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  2345. return new TextLayerBuilder({
  2346. textLayerDiv: textLayerDiv,
  2347. pageIndex: pageIndex,
  2348. viewport: viewport,
  2349. findController: this.isInPresentationMode ? null : this.findController
  2350. });
  2351. },
  2352. /**
  2353. * @param {HTMLDivElement} pageDiv
  2354. * @param {PDFPage} pdfPage
  2355. * @returns {AnnotationsLayerBuilder}
  2356. */
  2357. createAnnotationsLayerBuilder: function (pageDiv, pdfPage) {
  2358. return new AnnotationsLayerBuilder({
  2359. pageDiv: pageDiv,
  2360. pdfPage: pdfPage,
  2361. linkService: this.linkService
  2362. });
  2363. },
  2364. setFindController: function (findController) {
  2365. this.findController = findController;
  2366. },
  2367. };
  2368. return PDFViewer;
  2369. })();
  2370. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  2371. function SimpleLinkService() {}
  2372. SimpleLinkService.prototype = {
  2373. /**
  2374. * @returns {number}
  2375. */
  2376. get page() {
  2377. return 0;
  2378. },
  2379. /**
  2380. * @param {number} value
  2381. */
  2382. set page(value) {},
  2383. /**
  2384. * @param dest - The PDF destination object.
  2385. */
  2386. navigateTo: function (dest) {},
  2387. /**
  2388. * @param dest - The PDF destination object.
  2389. * @returns {string} The hyperlink to the PDF object.
  2390. */
  2391. getDestinationHash: function (dest) {
  2392. return '#';
  2393. },
  2394. /**
  2395. * @param hash - The PDF parameters/hash.
  2396. * @returns {string} The hyperlink to the PDF object.
  2397. */
  2398. getAnchorUrl: function (hash) {
  2399. return '#';
  2400. },
  2401. /**
  2402. * @param {string} hash
  2403. */
  2404. setHash: function (hash) {},
  2405. /**
  2406. * @param {string} action
  2407. */
  2408. executeNamedAction: function (action) {},
  2409. /**
  2410. * @param {number} pageNum - page number.
  2411. * @param {Object} pageRef - reference to the page.
  2412. */
  2413. cachePageRef: function (pageNum, pageRef) {}
  2414. };
  2415. return SimpleLinkService;
  2416. })();
  2417. var PDFHistory = (function () {
  2418. function PDFHistory(options) {
  2419. this.linkService = options.linkService;
  2420. this.initialized = false;
  2421. this.initialDestination = null;
  2422. this.initialBookmark = null;
  2423. }
  2424. PDFHistory.prototype = {
  2425. /**
  2426. * @param {string} fingerprint
  2427. * @param {IPDFLinkService} linkService
  2428. */
  2429. initialize: function pdfHistoryInitialize(fingerprint) {
  2430. this.initialized = true;
  2431. this.reInitialized = false;
  2432. this.allowHashChange = true;
  2433. this.historyUnlocked = true;
  2434. this.isViewerInPresentationMode = false;
  2435. this.previousHash = window.location.hash.substring(1);
  2436. this.currentBookmark = '';
  2437. this.currentPage = 0;
  2438. this.updatePreviousBookmark = false;
  2439. this.previousBookmark = '';
  2440. this.previousPage = 0;
  2441. this.nextHashParam = '';
  2442. this.fingerprint = fingerprint;
  2443. this.currentUid = this.uid = 0;
  2444. this.current = {};
  2445. var state = window.history.state;
  2446. if (this._isStateObjectDefined(state)) {
  2447. // This corresponds to navigating back to the document
  2448. // from another page in the browser history.
  2449. if (state.target.dest) {
  2450. this.initialDestination = state.target.dest;
  2451. } else {
  2452. this.initialBookmark = state.target.hash;
  2453. }
  2454. this.currentUid = state.uid;
  2455. this.uid = state.uid + 1;
  2456. this.current = state.target;
  2457. } else {
  2458. // This corresponds to the loading of a new document.
  2459. if (state && state.fingerprint &&
  2460. this.fingerprint !== state.fingerprint) {
  2461. // Reinitialize the browsing history when a new document
  2462. // is opened in the web viewer.
  2463. this.reInitialized = true;
  2464. }
  2465. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  2466. }
  2467. var self = this;
  2468. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  2469. evt.preventDefault();
  2470. evt.stopPropagation();
  2471. if (!self.historyUnlocked) {
  2472. return;
  2473. }
  2474. if (evt.state) {
  2475. // Move back/forward in the history.
  2476. self._goTo(evt.state);
  2477. } else {
  2478. // Handle the user modifying the hash of a loaded document.
  2479. self.previousHash = window.location.hash.substring(1);
  2480. // If the history is empty when the hash changes,
  2481. // update the previous entry in the browser history.
  2482. if (self.uid === 0) {
  2483. var previousParams = (self.previousHash && self.currentBookmark &&
  2484. self.previousHash !== self.currentBookmark) ?
  2485. {hash: self.currentBookmark, page: self.currentPage} :
  2486. {page: 1};
  2487. self.historyUnlocked = false;
  2488. self.allowHashChange = false;
  2489. window.history.back();
  2490. self._pushToHistory(previousParams, false, true);
  2491. window.history.forward();
  2492. self.historyUnlocked = true;
  2493. }
  2494. self._pushToHistory({hash: self.previousHash}, false, true);
  2495. self._updatePreviousBookmark();
  2496. }
  2497. }, false);
  2498. function pdfHistoryBeforeUnload() {
  2499. var previousParams = self._getPreviousParams(null, true);
  2500. if (previousParams) {
  2501. var replacePrevious = (!self.current.dest &&
  2502. self.current.hash !== self.previousHash);
  2503. self._pushToHistory(previousParams, false, replacePrevious);
  2504. self._updatePreviousBookmark();
  2505. }
  2506. // Remove the event listener when navigating away from the document,
  2507. // since 'beforeunload' prevents Firefox from caching the document.
  2508. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  2509. false);
  2510. }
  2511. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2512. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  2513. // If the entire viewer (including the PDF file) is cached in
  2514. // the browser, we need to reattach the 'beforeunload' event listener
  2515. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  2516. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2517. }, false);
  2518. window.addEventListener('presentationmodechanged', function(e) {
  2519. self.isViewerInPresentationMode = !!e.detail.active;
  2520. });
  2521. },
  2522. clearHistoryState: function pdfHistory_clearHistoryState() {
  2523. this._pushOrReplaceState(null, true);
  2524. },
  2525. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  2526. return (state && state.uid >= 0 &&
  2527. state.fingerprint && this.fingerprint === state.fingerprint &&
  2528. state.target && state.target.hash) ? true : false;
  2529. },
  2530. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  2531. replace) {
  2532. if (replace) {
  2533. window.history.replaceState(stateObj, '');
  2534. } else {
  2535. window.history.pushState(stateObj, '');
  2536. }
  2537. },
  2538. get isHashChangeUnlocked() {
  2539. if (!this.initialized) {
  2540. return true;
  2541. }
  2542. // If the current hash changes when moving back/forward in the history,
  2543. // this will trigger a 'popstate' event *as well* as a 'hashchange' event.
  2544. // Since the hash generally won't correspond to the exact the position
  2545. // stored in the history's state object, triggering the 'hashchange' event
  2546. // can thus corrupt the browser history.
  2547. //
  2548. // When the hash changes during a 'popstate' event, we *only* prevent the
  2549. // first 'hashchange' event and immediately reset allowHashChange.
  2550. // If it is not reset, the user would not be able to change the hash.
  2551. var temp = this.allowHashChange;
  2552. this.allowHashChange = true;
  2553. return temp;
  2554. },
  2555. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  2556. if (this.updatePreviousBookmark &&
  2557. this.currentBookmark && this.currentPage) {
  2558. this.previousBookmark = this.currentBookmark;
  2559. this.previousPage = this.currentPage;
  2560. this.updatePreviousBookmark = false;
  2561. }
  2562. },
  2563. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  2564. pageNum) {
  2565. if (this.initialized) {
  2566. this.currentBookmark = bookmark.substring(1);
  2567. this.currentPage = pageNum | 0;
  2568. this._updatePreviousBookmark();
  2569. }
  2570. },
  2571. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  2572. if (this.initialized) {
  2573. this.nextHashParam = param;
  2574. }
  2575. },
  2576. push: function pdfHistoryPush(params, isInitialBookmark) {
  2577. if (!(this.initialized && this.historyUnlocked)) {
  2578. return;
  2579. }
  2580. if (params.dest && !params.hash) {
  2581. params.hash = (this.current.hash && this.current.dest &&
  2582. this.current.dest === params.dest) ?
  2583. this.current.hash :
  2584. this.linkService.getDestinationHash(params.dest).split('#')[1];
  2585. }
  2586. if (params.page) {
  2587. params.page |= 0;
  2588. }
  2589. if (isInitialBookmark) {
  2590. var target = window.history.state.target;
  2591. if (!target) {
  2592. // Invoked when the user specifies an initial bookmark,
  2593. // thus setting initialBookmark, when the document is loaded.
  2594. this._pushToHistory(params, false);
  2595. this.previousHash = window.location.hash.substring(1);
  2596. }
  2597. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  2598. if (target) {
  2599. // If the current document is reloaded,
  2600. // avoid creating duplicate entries in the history.
  2601. this._updatePreviousBookmark();
  2602. }
  2603. return;
  2604. }
  2605. if (this.nextHashParam) {
  2606. if (this.nextHashParam === params.hash) {
  2607. this.nextHashParam = null;
  2608. this.updatePreviousBookmark = true;
  2609. return;
  2610. } else {
  2611. this.nextHashParam = null;
  2612. }
  2613. }
  2614. if (params.hash) {
  2615. if (this.current.hash) {
  2616. if (this.current.hash !== params.hash) {
  2617. this._pushToHistory(params, true);
  2618. } else {
  2619. if (!this.current.page && params.page) {
  2620. this._pushToHistory(params, false, true);
  2621. }
  2622. this.updatePreviousBookmark = true;
  2623. }
  2624. } else {
  2625. this._pushToHistory(params, true);
  2626. }
  2627. } else if (this.current.page && params.page &&
  2628. this.current.page !== params.page) {
  2629. this._pushToHistory(params, true);
  2630. }
  2631. },
  2632. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  2633. beforeUnload) {
  2634. if (!(this.currentBookmark && this.currentPage)) {
  2635. return null;
  2636. } else if (this.updatePreviousBookmark) {
  2637. this.updatePreviousBookmark = false;
  2638. }
  2639. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  2640. // Prevent the history from getting stuck in the current state,
  2641. // effectively preventing the user from going back/forward in
  2642. // the history.
  2643. //
  2644. // This happens if the current position in the document didn't change
  2645. // when the history was previously updated. The reasons for this are
  2646. // either:
  2647. // 1. The current zoom value is such that the document does not need to,
  2648. // or cannot, be scrolled to display the destination.
  2649. // 2. The previous destination is broken, and doesn't actally point to a
  2650. // position within the document.
  2651. // (This is either due to a bad PDF generator, or the user making a
  2652. // mistake when entering a destination in the hash parameters.)
  2653. return null;
  2654. }
  2655. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  2656. if (this.previousBookmark === this.currentBookmark) {
  2657. return null;
  2658. }
  2659. } else if (this.current.page || onlyCheckPage) {
  2660. if (this.previousPage === this.currentPage) {
  2661. return null;
  2662. }
  2663. } else {
  2664. return null;
  2665. }
  2666. var params = {hash: this.currentBookmark, page: this.currentPage};
  2667. if (this.isViewerInPresentationMode) {
  2668. params.hash = null;
  2669. }
  2670. return params;
  2671. },
  2672. _stateObj: function pdfHistory_stateObj(params) {
  2673. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  2674. },
  2675. _pushToHistory: function pdfHistory_pushToHistory(params,
  2676. addPrevious, overwrite) {
  2677. if (!this.initialized) {
  2678. return;
  2679. }
  2680. if (!params.hash && params.page) {
  2681. params.hash = ('page=' + params.page);
  2682. }
  2683. if (addPrevious && !overwrite) {
  2684. var previousParams = this._getPreviousParams();
  2685. if (previousParams) {
  2686. var replacePrevious = (!this.current.dest &&
  2687. this.current.hash !== this.previousHash);
  2688. this._pushToHistory(previousParams, false, replacePrevious);
  2689. }
  2690. }
  2691. this._pushOrReplaceState(this._stateObj(params),
  2692. (overwrite || this.uid === 0));
  2693. this.currentUid = this.uid++;
  2694. this.current = params;
  2695. this.updatePreviousBookmark = true;
  2696. },
  2697. _goTo: function pdfHistory_goTo(state) {
  2698. if (!(this.initialized && this.historyUnlocked &&
  2699. this._isStateObjectDefined(state))) {
  2700. return;
  2701. }
  2702. if (!this.reInitialized && state.uid < this.currentUid) {
  2703. var previousParams = this._getPreviousParams(true);
  2704. if (previousParams) {
  2705. this._pushToHistory(this.current, false);
  2706. this._pushToHistory(previousParams, false);
  2707. this.currentUid = state.uid;
  2708. window.history.back();
  2709. return;
  2710. }
  2711. }
  2712. this.historyUnlocked = false;
  2713. if (state.target.dest) {
  2714. this.linkService.navigateTo(state.target.dest);
  2715. } else {
  2716. this.linkService.setHash(state.target.hash);
  2717. }
  2718. this.currentUid = state.uid;
  2719. if (state.uid > this.uid) {
  2720. this.uid = state.uid;
  2721. }
  2722. this.current = state.target;
  2723. this.updatePreviousBookmark = true;
  2724. var currentHash = window.location.hash.substring(1);
  2725. if (this.previousHash !== currentHash) {
  2726. this.allowHashChange = false;
  2727. }
  2728. this.previousHash = currentHash;
  2729. this.historyUnlocked = true;
  2730. },
  2731. back: function pdfHistoryBack() {
  2732. this.go(-1);
  2733. },
  2734. forward: function pdfHistoryForward() {
  2735. this.go(1);
  2736. },
  2737. go: function pdfHistoryGo(direction) {
  2738. if (this.initialized && this.historyUnlocked) {
  2739. var state = window.history.state;
  2740. if (direction === -1 && state && state.uid > 0) {
  2741. window.history.back();
  2742. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  2743. window.history.forward();
  2744. }
  2745. }
  2746. }
  2747. };
  2748. return PDFHistory;
  2749. })();
  2750. PDFJS.PDFViewer = PDFViewer;
  2751. PDFJS.PDFPageView = PDFPageView;
  2752. PDFJS.PDFLinkService = PDFLinkService;
  2753. PDFJS.TextLayerBuilder = TextLayerBuilder;
  2754. PDFJS.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2755. PDFJS.AnnotationsLayerBuilder = AnnotationsLayerBuilder;
  2756. PDFJS.DefaultAnnotationsLayerFactory = DefaultAnnotationsLayerFactory;
  2757. PDFJS.PDFHistory = PDFHistory;
  2758. PDFJS.getFileName = getFileName;
  2759. PDFJS.ProgressBar = ProgressBar;
  2760. }).call((typeof window === 'undefined') ? this : window);