2
0

pdf_viewer.js 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121
  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. if (params.pagemode === 'thumbs' || params.pagemode === 'bookmarks' ||
  566. params.pagemode === 'attachments') {
  567. this.switchSidebarView((params.pagemode === 'bookmarks' ?
  568. 'outline' : params.pagemode), true);
  569. } else if (params.pagemode === 'none' && this.sidebarOpen) {
  570. document.getElementById('sidebarToggle').click();
  571. }
  572. }
  573. } else if (/^\d+$/.test(hash)) { // page number
  574. this.page = hash;
  575. } else { // named destination
  576. if (this.pdfHistory) {
  577. this.pdfHistory.updateNextHashParam(unescape(hash));
  578. }
  579. this.navigateTo(unescape(hash));
  580. }
  581. },
  582. /**
  583. * @param {string} action
  584. */
  585. executeNamedAction: function PDFLinkService_executeNamedAction(action) {
  586. // See PDF reference, table 8.45 - Named action
  587. switch (action) {
  588. case 'GoBack':
  589. if (this.pdfHistory) {
  590. this.pdfHistory.back();
  591. }
  592. break;
  593. case 'GoForward':
  594. if (this.pdfHistory) {
  595. this.pdfHistory.forward();
  596. }
  597. break;
  598. case 'NextPage':
  599. this.page++;
  600. break;
  601. case 'PrevPage':
  602. this.page--;
  603. break;
  604. case 'LastPage':
  605. this.page = this.pagesCount;
  606. break;
  607. case 'FirstPage':
  608. this.page = 1;
  609. break;
  610. default:
  611. break; // No action according to spec
  612. }
  613. var event = document.createEvent('CustomEvent');
  614. event.initCustomEvent('namedaction', true, true, {
  615. action: action
  616. });
  617. this.pdfViewer.container.dispatchEvent(event);
  618. },
  619. /**
  620. * @param {number} pageNum - page number.
  621. * @param {Object} pageRef - reference to the page.
  622. */
  623. cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
  624. var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
  625. this._pagesRefCache[refStr] = pageNum;
  626. }
  627. };
  628. return PDFLinkService;
  629. })();
  630. var PresentationModeState = {
  631. UNKNOWN: 0,
  632. NORMAL: 1,
  633. CHANGING: 2,
  634. FULLSCREEN: 3,
  635. };
  636. var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
  637. var DEFAULT_CACHE_SIZE = 10;
  638. var CLEANUP_TIMEOUT = 30000;
  639. var RenderingStates = {
  640. INITIAL: 0,
  641. RUNNING: 1,
  642. PAUSED: 2,
  643. FINISHED: 3
  644. };
  645. /**
  646. * Controls rendering of the views for pages and thumbnails.
  647. * @class
  648. */
  649. var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
  650. /**
  651. * @constructs
  652. */
  653. function PDFRenderingQueue() {
  654. this.pdfViewer = null;
  655. this.pdfThumbnailViewer = null;
  656. this.onIdle = null;
  657. this.highestPriorityPage = null;
  658. this.idleTimeout = null;
  659. this.printing = false;
  660. this.isThumbnailViewEnabled = false;
  661. }
  662. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
  663. /**
  664. * @param {PDFViewer} pdfViewer
  665. */
  666. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  667. this.pdfViewer = pdfViewer;
  668. },
  669. /**
  670. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  671. */
  672. setThumbnailViewer:
  673. function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  674. this.pdfThumbnailViewer = pdfThumbnailViewer;
  675. },
  676. /**
  677. * @param {IRenderableView} view
  678. * @returns {boolean}
  679. */
  680. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  681. return this.highestPriorityPage === view.renderingId;
  682. },
  683. renderHighestPriority: function
  684. PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  685. if (this.idleTimeout) {
  686. clearTimeout(this.idleTimeout);
  687. this.idleTimeout = null;
  688. }
  689. // Pages have a higher priority than thumbnails, so check them first.
  690. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  691. return;
  692. }
  693. // No pages needed rendering so check thumbnails.
  694. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  695. if (this.pdfThumbnailViewer.forceRendering()) {
  696. return;
  697. }
  698. }
  699. if (this.printing) {
  700. // If printing is currently ongoing do not reschedule cleanup.
  701. return;
  702. }
  703. if (this.onIdle) {
  704. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  705. }
  706. },
  707. getHighestPriority: function
  708. PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  709. // The state has changed figure out which page has the highest priority to
  710. // render next (if any).
  711. // Priority:
  712. // 1 visible pages
  713. // 2 if last scrolled down page after the visible pages
  714. // 2 if last scrolled up page before the visible pages
  715. var visibleViews = visible.views;
  716. var numVisible = visibleViews.length;
  717. if (numVisible === 0) {
  718. return false;
  719. }
  720. for (var i = 0; i < numVisible; ++i) {
  721. var view = visibleViews[i].view;
  722. if (!this.isViewFinished(view)) {
  723. return view;
  724. }
  725. }
  726. // All the visible views have rendered, try to render next/previous pages.
  727. if (scrolledDown) {
  728. var nextPageIndex = visible.last.id;
  729. // ID's start at 1 so no need to add 1.
  730. if (views[nextPageIndex] &&
  731. !this.isViewFinished(views[nextPageIndex])) {
  732. return views[nextPageIndex];
  733. }
  734. } else {
  735. var previousPageIndex = visible.first.id - 2;
  736. if (views[previousPageIndex] &&
  737. !this.isViewFinished(views[previousPageIndex])) {
  738. return views[previousPageIndex];
  739. }
  740. }
  741. // Everything that needs to be rendered has been.
  742. return null;
  743. },
  744. /**
  745. * @param {IRenderableView} view
  746. * @returns {boolean}
  747. */
  748. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  749. return view.renderingState === RenderingStates.FINISHED;
  750. },
  751. /**
  752. * Render a page or thumbnail view. This calls the appropriate function
  753. * based on the views state. If the view is already rendered it will return
  754. * false.
  755. * @param {IRenderableView} view
  756. */
  757. renderView: function PDFRenderingQueue_renderView(view) {
  758. var state = view.renderingState;
  759. switch (state) {
  760. case RenderingStates.FINISHED:
  761. return false;
  762. case RenderingStates.PAUSED:
  763. this.highestPriorityPage = view.renderingId;
  764. view.resume();
  765. break;
  766. case RenderingStates.RUNNING:
  767. this.highestPriorityPage = view.renderingId;
  768. break;
  769. case RenderingStates.INITIAL:
  770. this.highestPriorityPage = view.renderingId;
  771. var continueRendering = function () {
  772. this.renderHighestPriority();
  773. }.bind(this);
  774. view.draw().then(continueRendering, continueRendering);
  775. break;
  776. }
  777. return true;
  778. },
  779. };
  780. return PDFRenderingQueue;
  781. })();
  782. var TEXT_LAYER_RENDER_DELAY = 200; // ms
  783. /**
  784. * @typedef {Object} PDFPageViewOptions
  785. * @property {HTMLDivElement} container - The viewer element.
  786. * @property {number} id - The page unique ID (normally its number).
  787. * @property {number} scale - The page scale display.
  788. * @property {PageViewport} defaultViewport - The page viewport.
  789. * @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
  790. * @property {IPDFTextLayerFactory} textLayerFactory
  791. * @property {IPDFAnnotationsLayerFactory} annotationsLayerFactory
  792. */
  793. /**
  794. * @class
  795. * @implements {IRenderableView}
  796. */
  797. var PDFPageView = (function PDFPageViewClosure() {
  798. /**
  799. * @constructs PDFPageView
  800. * @param {PDFPageViewOptions} options
  801. */
  802. function PDFPageView(options) {
  803. var container = options.container;
  804. var id = options.id;
  805. var scale = options.scale;
  806. var defaultViewport = options.defaultViewport;
  807. var renderingQueue = options.renderingQueue;
  808. var textLayerFactory = options.textLayerFactory;
  809. var annotationsLayerFactory = options.annotationsLayerFactory;
  810. this.id = id;
  811. this.renderingId = 'page' + id;
  812. this.rotation = 0;
  813. this.scale = scale || 1.0;
  814. this.viewport = defaultViewport;
  815. this.pdfPageRotate = defaultViewport.rotation;
  816. this.hasRestrictedScaling = false;
  817. this.renderingQueue = renderingQueue;
  818. this.textLayerFactory = textLayerFactory;
  819. this.annotationsLayerFactory = annotationsLayerFactory;
  820. this.renderingState = RenderingStates.INITIAL;
  821. this.resume = null;
  822. this.onBeforeDraw = null;
  823. this.onAfterDraw = null;
  824. this.textLayer = null;
  825. this.zoomLayer = null;
  826. this.annotationLayer = null;
  827. var div = document.createElement('div');
  828. div.id = 'pageContainer' + this.id;
  829. div.className = 'page';
  830. div.style.width = Math.floor(this.viewport.width) + 'px';
  831. div.style.height = Math.floor(this.viewport.height) + 'px';
  832. div.setAttribute('data-page-number', this.id);
  833. this.div = div;
  834. container.appendChild(div);
  835. }
  836. PDFPageView.prototype = {
  837. setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
  838. this.pdfPage = pdfPage;
  839. this.pdfPageRotate = pdfPage.rotate;
  840. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  841. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
  842. totalRotation);
  843. this.stats = pdfPage.stats;
  844. this.reset();
  845. },
  846. destroy: function PDFPageView_destroy() {
  847. this.zoomLayer = null;
  848. this.reset();
  849. if (this.pdfPage) {
  850. this.pdfPage.destroy();
  851. }
  852. },
  853. reset: function PDFPageView_reset(keepAnnotations) {
  854. if (this.renderTask) {
  855. this.renderTask.cancel();
  856. }
  857. this.resume = null;
  858. this.renderingState = RenderingStates.INITIAL;
  859. var div = this.div;
  860. div.style.width = Math.floor(this.viewport.width) + 'px';
  861. div.style.height = Math.floor(this.viewport.height) + 'px';
  862. var childNodes = div.childNodes;
  863. var currentZoomLayer = this.zoomLayer || null;
  864. var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
  865. this.annotationLayer.div) || null;
  866. for (var i = childNodes.length - 1; i >= 0; i--) {
  867. var node = childNodes[i];
  868. if (currentZoomLayer === node || currentAnnotationNode === node) {
  869. continue;
  870. }
  871. div.removeChild(node);
  872. }
  873. div.removeAttribute('data-loaded');
  874. if (keepAnnotations) {
  875. if (this.annotationLayer) {
  876. // Hide annotationLayer until all elements are resized
  877. // so they are not displayed on the already-resized page
  878. this.annotationLayer.hide();
  879. }
  880. } else {
  881. this.annotationLayer = null;
  882. }
  883. if (this.canvas) {
  884. // Zeroing the width and height causes Firefox to release graphics
  885. // resources immediately, which can greatly reduce memory consumption.
  886. this.canvas.width = 0;
  887. this.canvas.height = 0;
  888. delete this.canvas;
  889. }
  890. this.loadingIconDiv = document.createElement('div');
  891. this.loadingIconDiv.className = 'loadingIcon';
  892. div.appendChild(this.loadingIconDiv);
  893. },
  894. update: function PDFPageView_update(scale, rotation) {
  895. this.scale = scale || this.scale;
  896. if (typeof rotation !== 'undefined') {
  897. this.rotation = rotation;
  898. }
  899. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  900. this.viewport = this.viewport.clone({
  901. scale: this.scale * CSS_UNITS,
  902. rotation: totalRotation
  903. });
  904. var isScalingRestricted = false;
  905. if (this.canvas && PDFJS.maxCanvasPixels > 0) {
  906. var ctx = this.canvas.getContext('2d');
  907. var outputScale = getOutputScale(ctx);
  908. var pixelsInViewport = this.viewport.width * this.viewport.height;
  909. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  910. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  911. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  912. PDFJS.maxCanvasPixels) {
  913. isScalingRestricted = true;
  914. }
  915. }
  916. if (this.canvas &&
  917. (PDFJS.useOnlyCssZoom ||
  918. (this.hasRestrictedScaling && isScalingRestricted))) {
  919. this.cssTransform(this.canvas, true);
  920. return;
  921. } else if (this.canvas && !this.zoomLayer) {
  922. this.zoomLayer = this.canvas.parentNode;
  923. this.zoomLayer.style.position = 'absolute';
  924. }
  925. if (this.zoomLayer) {
  926. this.cssTransform(this.zoomLayer.firstChild);
  927. }
  928. this.reset(true);
  929. },
  930. /**
  931. * Called when moved in the parent's container.
  932. */
  933. updatePosition: function PDFPageView_updatePosition() {
  934. if (this.textLayer) {
  935. this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
  936. }
  937. },
  938. cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
  939. // Scale canvas, canvas wrapper, and page container.
  940. var width = this.viewport.width;
  941. var height = this.viewport.height;
  942. var div = this.div;
  943. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  944. Math.floor(width) + 'px';
  945. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  946. Math.floor(height) + 'px';
  947. // The canvas may have been originally rotated, rotate relative to that.
  948. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  949. var absRotation = Math.abs(relativeRotation);
  950. var scaleX = 1, scaleY = 1;
  951. if (absRotation === 90 || absRotation === 270) {
  952. // Scale x and y because of the rotation.
  953. scaleX = height / width;
  954. scaleY = width / height;
  955. }
  956. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  957. 'scale(' + scaleX + ',' + scaleY + ')';
  958. CustomStyle.setProp('transform', canvas, cssTransform);
  959. if (this.textLayer) {
  960. // Rotating the text layer is more complicated since the divs inside the
  961. // the text layer are rotated.
  962. // TODO: This could probably be simplified by drawing the text layer in
  963. // one orientation then rotating overall.
  964. var textLayerViewport = this.textLayer.viewport;
  965. var textRelativeRotation = this.viewport.rotation -
  966. textLayerViewport.rotation;
  967. var textAbsRotation = Math.abs(textRelativeRotation);
  968. var scale = width / textLayerViewport.width;
  969. if (textAbsRotation === 90 || textAbsRotation === 270) {
  970. scale = width / textLayerViewport.height;
  971. }
  972. var textLayerDiv = this.textLayer.textLayerDiv;
  973. var transX, transY;
  974. switch (textAbsRotation) {
  975. case 0:
  976. transX = transY = 0;
  977. break;
  978. case 90:
  979. transX = 0;
  980. transY = '-' + textLayerDiv.style.height;
  981. break;
  982. case 180:
  983. transX = '-' + textLayerDiv.style.width;
  984. transY = '-' + textLayerDiv.style.height;
  985. break;
  986. case 270:
  987. transX = '-' + textLayerDiv.style.width;
  988. transY = 0;
  989. break;
  990. default:
  991. console.error('Bad rotation value.');
  992. break;
  993. }
  994. CustomStyle.setProp('transform', textLayerDiv,
  995. 'rotate(' + textAbsRotation + 'deg) ' +
  996. 'scale(' + scale + ', ' + scale + ') ' +
  997. 'translate(' + transX + ', ' + transY + ')');
  998. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  999. }
  1000. if (redrawAnnotations && this.annotationLayer) {
  1001. this.annotationLayer.setupAnnotations(this.viewport);
  1002. }
  1003. },
  1004. get width() {
  1005. return this.viewport.width;
  1006. },
  1007. get height() {
  1008. return this.viewport.height;
  1009. },
  1010. getPagePoint: function PDFPageView_getPagePoint(x, y) {
  1011. return this.viewport.convertToPdfPoint(x, y);
  1012. },
  1013. draw: function PDFPageView_draw() {
  1014. if (this.renderingState !== RenderingStates.INITIAL) {
  1015. console.error('Must be in new state before drawing');
  1016. }
  1017. this.renderingState = RenderingStates.RUNNING;
  1018. var pdfPage = this.pdfPage;
  1019. var viewport = this.viewport;
  1020. var div = this.div;
  1021. // Wrap the canvas so if it has a css transform for highdpi the overflow
  1022. // will be hidden in FF.
  1023. var canvasWrapper = document.createElement('div');
  1024. canvasWrapper.style.width = div.style.width;
  1025. canvasWrapper.style.height = div.style.height;
  1026. canvasWrapper.classList.add('canvasWrapper');
  1027. var canvas = document.createElement('canvas');
  1028. canvas.id = 'page' + this.id;
  1029. canvasWrapper.appendChild(canvas);
  1030. if (this.annotationLayer) {
  1031. // annotationLayer needs to stay on top
  1032. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  1033. } else {
  1034. div.appendChild(canvasWrapper);
  1035. }
  1036. this.canvas = canvas;
  1037. var ctx = canvas.getContext('2d');
  1038. var outputScale = getOutputScale(ctx);
  1039. if (PDFJS.useOnlyCssZoom) {
  1040. var actualSizeViewport = viewport.clone({ scale: CSS_UNITS });
  1041. // Use a scale that will make the canvas be the original intended size
  1042. // of the page.
  1043. outputScale.sx *= actualSizeViewport.width / viewport.width;
  1044. outputScale.sy *= actualSizeViewport.height / viewport.height;
  1045. outputScale.scaled = true;
  1046. }
  1047. if (PDFJS.maxCanvasPixels > 0) {
  1048. var pixelsInViewport = viewport.width * viewport.height;
  1049. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  1050. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  1051. outputScale.sx = maxScale;
  1052. outputScale.sy = maxScale;
  1053. outputScale.scaled = true;
  1054. this.hasRestrictedScaling = true;
  1055. } else {
  1056. this.hasRestrictedScaling = false;
  1057. }
  1058. }
  1059. canvas.width = (Math.floor(viewport.width) * outputScale.sx) | 0;
  1060. canvas.height = (Math.floor(viewport.height) * outputScale.sy) | 0;
  1061. canvas.style.width = Math.floor(viewport.width) + 'px';
  1062. canvas.style.height = Math.floor(viewport.height) + 'px';
  1063. // Add the viewport so it's known what it was originally drawn with.
  1064. canvas._viewport = viewport;
  1065. var textLayerDiv = null;
  1066. var textLayer = null;
  1067. if (this.textLayerFactory) {
  1068. textLayerDiv = document.createElement('div');
  1069. textLayerDiv.className = 'textLayer';
  1070. textLayerDiv.style.width = canvas.style.width;
  1071. textLayerDiv.style.height = canvas.style.height;
  1072. if (this.annotationLayer) {
  1073. // annotationLayer needs to stay on top
  1074. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  1075. } else {
  1076. div.appendChild(textLayerDiv);
  1077. }
  1078. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
  1079. this.id - 1,
  1080. this.viewport);
  1081. }
  1082. this.textLayer = textLayer;
  1083. if (outputScale.scaled) {
  1084. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  1085. ctx._transformMatrix = [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  1086. ctx.scale(outputScale.sx, outputScale.sy);
  1087. }
  1088. var resolveRenderPromise, rejectRenderPromise;
  1089. var promise = new Promise(function (resolve, reject) {
  1090. resolveRenderPromise = resolve;
  1091. rejectRenderPromise = reject;
  1092. });
  1093. // Rendering area
  1094. var self = this;
  1095. function pageViewDrawCallback(error) {
  1096. // The renderTask may have been replaced by a new one, so only remove
  1097. // the reference to the renderTask if it matches the one that is
  1098. // triggering this callback.
  1099. if (renderTask === self.renderTask) {
  1100. self.renderTask = null;
  1101. }
  1102. if (error === 'cancelled') {
  1103. rejectRenderPromise(error);
  1104. return;
  1105. }
  1106. self.renderingState = RenderingStates.FINISHED;
  1107. if (self.loadingIconDiv) {
  1108. div.removeChild(self.loadingIconDiv);
  1109. delete self.loadingIconDiv;
  1110. }
  1111. if (self.zoomLayer) {
  1112. div.removeChild(self.zoomLayer);
  1113. self.zoomLayer = null;
  1114. }
  1115. self.error = error;
  1116. self.stats = pdfPage.stats;
  1117. if (self.onAfterDraw) {
  1118. self.onAfterDraw();
  1119. }
  1120. var event = document.createEvent('CustomEvent');
  1121. event.initCustomEvent('pagerendered', true, true, {
  1122. pageNumber: self.id
  1123. });
  1124. div.dispatchEvent(event);
  1125. if (!error) {
  1126. resolveRenderPromise(undefined);
  1127. } else {
  1128. rejectRenderPromise(error);
  1129. }
  1130. }
  1131. var renderContinueCallback = null;
  1132. if (this.renderingQueue) {
  1133. renderContinueCallback = function renderContinueCallback(cont) {
  1134. if (!self.renderingQueue.isHighestPriority(self)) {
  1135. self.renderingState = RenderingStates.PAUSED;
  1136. self.resume = function resumeCallback() {
  1137. self.renderingState = RenderingStates.RUNNING;
  1138. cont();
  1139. };
  1140. return;
  1141. }
  1142. cont();
  1143. };
  1144. }
  1145. var renderContext = {
  1146. canvasContext: ctx,
  1147. viewport: this.viewport,
  1148. // intent: 'default', // === 'display'
  1149. continueCallback: renderContinueCallback
  1150. };
  1151. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  1152. this.renderTask.promise.then(
  1153. function pdfPageRenderCallback() {
  1154. pageViewDrawCallback(null);
  1155. if (textLayer) {
  1156. self.pdfPage.getTextContent().then(
  1157. function textContentResolved(textContent) {
  1158. textLayer.setTextContent(textContent);
  1159. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  1160. }
  1161. );
  1162. }
  1163. },
  1164. function pdfPageRenderError(error) {
  1165. pageViewDrawCallback(error);
  1166. }
  1167. );
  1168. if (this.annotationsLayerFactory) {
  1169. if (!this.annotationLayer) {
  1170. this.annotationLayer = this.annotationsLayerFactory.
  1171. createAnnotationsLayerBuilder(div, this.pdfPage);
  1172. }
  1173. this.annotationLayer.setupAnnotations(this.viewport);
  1174. }
  1175. div.setAttribute('data-loaded', true);
  1176. if (self.onBeforeDraw) {
  1177. self.onBeforeDraw();
  1178. }
  1179. return promise;
  1180. },
  1181. beforePrint: function PDFPageView_beforePrint() {
  1182. var pdfPage = this.pdfPage;
  1183. var viewport = pdfPage.getViewport(1);
  1184. // Use the same hack we use for high dpi displays for printing to get
  1185. // better output until bug 811002 is fixed in FF.
  1186. var PRINT_OUTPUT_SCALE = 2;
  1187. var canvas = document.createElement('canvas');
  1188. // The logical size of the canvas.
  1189. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  1190. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  1191. // The rendered size of the canvas, relative to the size of canvasWrapper.
  1192. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
  1193. canvas.style.height = (PRINT_OUTPUT_SCALE * 100) + '%';
  1194. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  1195. (1 / PRINT_OUTPUT_SCALE) + ')';
  1196. CustomStyle.setProp('transform' , canvas, cssScale);
  1197. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  1198. var printContainer = document.getElementById('printContainer');
  1199. var canvasWrapper = document.createElement('div');
  1200. canvasWrapper.style.width = viewport.width + 'pt';
  1201. canvasWrapper.style.height = viewport.height + 'pt';
  1202. canvasWrapper.appendChild(canvas);
  1203. printContainer.appendChild(canvasWrapper);
  1204. canvas.mozPrintCallback = function(obj) {
  1205. var ctx = obj.context;
  1206. ctx.save();
  1207. ctx.fillStyle = 'rgb(255, 255, 255)';
  1208. ctx.fillRect(0, 0, canvas.width, canvas.height);
  1209. ctx.restore();
  1210. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  1211. ctx._transformMatrix =
  1212. [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
  1213. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  1214. var renderContext = {
  1215. canvasContext: ctx,
  1216. viewport: viewport,
  1217. intent: 'print'
  1218. };
  1219. pdfPage.render(renderContext).promise.then(function() {
  1220. // Tell the printEngine that rendering this canvas/page has finished.
  1221. obj.done();
  1222. }, function(error) {
  1223. console.error(error);
  1224. // Tell the printEngine that rendering this canvas/page has failed.
  1225. // This will make the print proces stop.
  1226. if ('abort' in obj) {
  1227. obj.abort();
  1228. } else {
  1229. obj.done();
  1230. }
  1231. });
  1232. };
  1233. },
  1234. };
  1235. return PDFPageView;
  1236. })();
  1237. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  1238. var NonWhitespaceRegexp = /\S/;
  1239. function isAllWhitespace(str) {
  1240. return !NonWhitespaceRegexp.test(str);
  1241. }
  1242. /**
  1243. * @typedef {Object} TextLayerBuilderOptions
  1244. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  1245. * @property {number} pageIndex - The page index.
  1246. * @property {PageViewport} viewport - The viewport of the text layer.
  1247. * @property {PDFFindController} findController
  1248. */
  1249. /**
  1250. * TextLayerBuilder provides text-selection functionality for the PDF.
  1251. * It does this by creating overlay divs over the PDF text. These divs
  1252. * contain text that matches the PDF text they are overlaying. This object
  1253. * also provides a way to highlight text that is being searched for.
  1254. * @class
  1255. */
  1256. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  1257. function TextLayerBuilder(options) {
  1258. this.textLayerDiv = options.textLayerDiv;
  1259. this.renderingDone = false;
  1260. this.divContentDone = false;
  1261. this.pageIdx = options.pageIndex;
  1262. this.pageNumber = this.pageIdx + 1;
  1263. this.matches = [];
  1264. this.viewport = options.viewport;
  1265. this.textDivs = [];
  1266. this.findController = options.findController || null;
  1267. }
  1268. TextLayerBuilder.prototype = {
  1269. _finishRendering: function TextLayerBuilder_finishRendering() {
  1270. this.renderingDone = true;
  1271. var event = document.createEvent('CustomEvent');
  1272. event.initCustomEvent('textlayerrendered', true, true, {
  1273. pageNumber: this.pageNumber
  1274. });
  1275. this.textLayerDiv.dispatchEvent(event);
  1276. },
  1277. renderLayer: function TextLayerBuilder_renderLayer() {
  1278. var textLayerFrag = document.createDocumentFragment();
  1279. var textDivs = this.textDivs;
  1280. var textDivsLength = textDivs.length;
  1281. var canvas = document.createElement('canvas');
  1282. var ctx = canvas.getContext('2d');
  1283. // No point in rendering many divs as it would make the browser
  1284. // unusable even after the divs are rendered.
  1285. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  1286. this._finishRendering();
  1287. return;
  1288. }
  1289. var lastFontSize;
  1290. var lastFontFamily;
  1291. for (var i = 0; i < textDivsLength; i++) {
  1292. var textDiv = textDivs[i];
  1293. if (textDiv.dataset.isWhitespace !== undefined) {
  1294. continue;
  1295. }
  1296. var fontSize = textDiv.style.fontSize;
  1297. var fontFamily = textDiv.style.fontFamily;
  1298. // Only build font string and set to context if different from last.
  1299. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  1300. ctx.font = fontSize + ' ' + fontFamily;
  1301. lastFontSize = fontSize;
  1302. lastFontFamily = fontFamily;
  1303. }
  1304. var width = ctx.measureText(textDiv.textContent).width;
  1305. if (width > 0) {
  1306. textLayerFrag.appendChild(textDiv);
  1307. var transform;
  1308. if (textDiv.dataset.canvasWidth !== undefined) {
  1309. // Dataset values come of type string.
  1310. var textScale = textDiv.dataset.canvasWidth / width;
  1311. transform = 'scaleX(' + textScale + ')';
  1312. } else {
  1313. transform = '';
  1314. }
  1315. var rotation = textDiv.dataset.angle;
  1316. if (rotation) {
  1317. transform = 'rotate(' + rotation + 'deg) ' + transform;
  1318. }
  1319. if (transform) {
  1320. CustomStyle.setProp('transform' , textDiv, transform);
  1321. }
  1322. }
  1323. }
  1324. this.textLayerDiv.appendChild(textLayerFrag);
  1325. this._finishRendering();
  1326. this.updateMatches();
  1327. },
  1328. /**
  1329. * Renders the text layer.
  1330. * @param {number} timeout (optional) if specified, the rendering waits
  1331. * for specified amount of ms.
  1332. */
  1333. render: function TextLayerBuilder_render(timeout) {
  1334. if (!this.divContentDone || this.renderingDone) {
  1335. return;
  1336. }
  1337. if (this.renderTimer) {
  1338. clearTimeout(this.renderTimer);
  1339. this.renderTimer = null;
  1340. }
  1341. if (!timeout) { // Render right away
  1342. this.renderLayer();
  1343. } else { // Schedule
  1344. var self = this;
  1345. this.renderTimer = setTimeout(function() {
  1346. self.renderLayer();
  1347. self.renderTimer = null;
  1348. }, timeout);
  1349. }
  1350. },
  1351. appendText: function TextLayerBuilder_appendText(geom, styles) {
  1352. var style = styles[geom.fontName];
  1353. var textDiv = document.createElement('div');
  1354. this.textDivs.push(textDiv);
  1355. if (isAllWhitespace(geom.str)) {
  1356. textDiv.dataset.isWhitespace = true;
  1357. return;
  1358. }
  1359. var tx = PDFJS.Util.transform(this.viewport.transform, geom.transform);
  1360. var angle = Math.atan2(tx[1], tx[0]);
  1361. if (style.vertical) {
  1362. angle += Math.PI / 2;
  1363. }
  1364. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  1365. var fontAscent = fontHeight;
  1366. if (style.ascent) {
  1367. fontAscent = style.ascent * fontAscent;
  1368. } else if (style.descent) {
  1369. fontAscent = (1 + style.descent) * fontAscent;
  1370. }
  1371. var left;
  1372. var top;
  1373. if (angle === 0) {
  1374. left = tx[4];
  1375. top = tx[5] - fontAscent;
  1376. } else {
  1377. left = tx[4] + (fontAscent * Math.sin(angle));
  1378. top = tx[5] - (fontAscent * Math.cos(angle));
  1379. }
  1380. textDiv.style.left = left + 'px';
  1381. textDiv.style.top = top + 'px';
  1382. textDiv.style.fontSize = fontHeight + 'px';
  1383. textDiv.style.fontFamily = style.fontFamily;
  1384. textDiv.textContent = geom.str;
  1385. // |fontName| is only used by the Font Inspector. This test will succeed
  1386. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  1387. // not worth the effort to do a more accurate test.
  1388. if (PDFJS.pdfBug) {
  1389. textDiv.dataset.fontName = geom.fontName;
  1390. }
  1391. // Storing into dataset will convert number into string.
  1392. if (angle !== 0) {
  1393. textDiv.dataset.angle = angle * (180 / Math.PI);
  1394. }
  1395. // We don't bother scaling single-char text divs, because it has very
  1396. // little effect on text highlighting. This makes scrolling on docs with
  1397. // lots of such divs a lot faster.
  1398. if (textDiv.textContent.length > 1) {
  1399. if (style.vertical) {
  1400. textDiv.dataset.canvasWidth = geom.height * this.viewport.scale;
  1401. } else {
  1402. textDiv.dataset.canvasWidth = geom.width * this.viewport.scale;
  1403. }
  1404. }
  1405. },
  1406. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  1407. this.textContent = textContent;
  1408. var textItems = textContent.items;
  1409. for (var i = 0, len = textItems.length; i < len; i++) {
  1410. this.appendText(textItems[i], textContent.styles);
  1411. }
  1412. this.divContentDone = true;
  1413. },
  1414. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  1415. var i = 0;
  1416. var iIndex = 0;
  1417. var bidiTexts = this.textContent.items;
  1418. var end = bidiTexts.length - 1;
  1419. var queryLen = (this.findController === null ?
  1420. 0 : this.findController.state.query.length);
  1421. var ret = [];
  1422. for (var m = 0, len = matches.length; m < len; m++) {
  1423. // Calculate the start position.
  1424. var matchIdx = matches[m];
  1425. // Loop over the divIdxs.
  1426. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  1427. iIndex += bidiTexts[i].str.length;
  1428. i++;
  1429. }
  1430. if (i === bidiTexts.length) {
  1431. console.error('Could not find a matching mapping');
  1432. }
  1433. var match = {
  1434. begin: {
  1435. divIdx: i,
  1436. offset: matchIdx - iIndex
  1437. }
  1438. };
  1439. // Calculate the end position.
  1440. matchIdx += queryLen;
  1441. // Somewhat the same array as above, but use > instead of >= to get
  1442. // the end position right.
  1443. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  1444. iIndex += bidiTexts[i].str.length;
  1445. i++;
  1446. }
  1447. match.end = {
  1448. divIdx: i,
  1449. offset: matchIdx - iIndex
  1450. };
  1451. ret.push(match);
  1452. }
  1453. return ret;
  1454. },
  1455. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  1456. // Early exit if there is nothing to render.
  1457. if (matches.length === 0) {
  1458. return;
  1459. }
  1460. var bidiTexts = this.textContent.items;
  1461. var textDivs = this.textDivs;
  1462. var prevEnd = null;
  1463. var pageIdx = this.pageIdx;
  1464. var isSelectedPage = (this.findController === null ?
  1465. false : (pageIdx === this.findController.selected.pageIdx));
  1466. var selectedMatchIdx = (this.findController === null ?
  1467. -1 : this.findController.selected.matchIdx);
  1468. var highlightAll = (this.findController === null ?
  1469. false : this.findController.state.highlightAll);
  1470. var infinity = {
  1471. divIdx: -1,
  1472. offset: undefined
  1473. };
  1474. function beginText(begin, className) {
  1475. var divIdx = begin.divIdx;
  1476. textDivs[divIdx].textContent = '';
  1477. appendTextToDiv(divIdx, 0, begin.offset, className);
  1478. }
  1479. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  1480. var div = textDivs[divIdx];
  1481. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  1482. var node = document.createTextNode(content);
  1483. if (className) {
  1484. var span = document.createElement('span');
  1485. span.className = className;
  1486. span.appendChild(node);
  1487. div.appendChild(span);
  1488. return;
  1489. }
  1490. div.appendChild(node);
  1491. }
  1492. var i0 = selectedMatchIdx, i1 = i0 + 1;
  1493. if (highlightAll) {
  1494. i0 = 0;
  1495. i1 = matches.length;
  1496. } else if (!isSelectedPage) {
  1497. // Not highlighting all and this isn't the selected page, so do nothing.
  1498. return;
  1499. }
  1500. for (var i = i0; i < i1; i++) {
  1501. var match = matches[i];
  1502. var begin = match.begin;
  1503. var end = match.end;
  1504. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  1505. var highlightSuffix = (isSelected ? ' selected' : '');
  1506. if (this.findController) {
  1507. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  1508. begin.divIdx, end.divIdx);
  1509. }
  1510. // Match inside new div.
  1511. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  1512. // If there was a previous div, then add the text at the end.
  1513. if (prevEnd !== null) {
  1514. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1515. }
  1516. // Clear the divs and set the content until the starting point.
  1517. beginText(begin);
  1518. } else {
  1519. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  1520. }
  1521. if (begin.divIdx === end.divIdx) {
  1522. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  1523. 'highlight' + highlightSuffix);
  1524. } else {
  1525. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  1526. 'highlight begin' + highlightSuffix);
  1527. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  1528. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  1529. }
  1530. beginText(end, 'highlight end' + highlightSuffix);
  1531. }
  1532. prevEnd = end;
  1533. }
  1534. if (prevEnd) {
  1535. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1536. }
  1537. },
  1538. updateMatches: function TextLayerBuilder_updateMatches() {
  1539. // Only show matches when all rendering is done.
  1540. if (!this.renderingDone) {
  1541. return;
  1542. }
  1543. // Clear all matches.
  1544. var matches = this.matches;
  1545. var textDivs = this.textDivs;
  1546. var bidiTexts = this.textContent.items;
  1547. var clearedUntilDivIdx = -1;
  1548. // Clear all current matches.
  1549. for (var i = 0, len = matches.length; i < len; i++) {
  1550. var match = matches[i];
  1551. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  1552. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  1553. var div = textDivs[n];
  1554. div.textContent = bidiTexts[n].str;
  1555. div.className = '';
  1556. }
  1557. clearedUntilDivIdx = match.end.divIdx + 1;
  1558. }
  1559. if (this.findController === null || !this.findController.active) {
  1560. return;
  1561. }
  1562. // Convert the matches on the page controller into the match format
  1563. // used for the textLayer.
  1564. this.matches = this.convertMatches(this.findController === null ?
  1565. [] : (this.findController.pageMatches[this.pageIdx] || []));
  1566. this.renderMatches(this.matches);
  1567. }
  1568. };
  1569. return TextLayerBuilder;
  1570. })();
  1571. /**
  1572. * @constructor
  1573. * @implements IPDFTextLayerFactory
  1574. */
  1575. function DefaultTextLayerFactory() {}
  1576. DefaultTextLayerFactory.prototype = {
  1577. /**
  1578. * @param {HTMLDivElement} textLayerDiv
  1579. * @param {number} pageIndex
  1580. * @param {PageViewport} viewport
  1581. * @returns {TextLayerBuilder}
  1582. */
  1583. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  1584. return new TextLayerBuilder({
  1585. textLayerDiv: textLayerDiv,
  1586. pageIndex: pageIndex,
  1587. viewport: viewport
  1588. });
  1589. }
  1590. };
  1591. /**
  1592. * @typedef {Object} AnnotationsLayerBuilderOptions
  1593. * @property {HTMLDivElement} pageDiv
  1594. * @property {PDFPage} pdfPage
  1595. * @property {IPDFLinkService} linkService
  1596. */
  1597. /**
  1598. * @class
  1599. */
  1600. var AnnotationsLayerBuilder = (function AnnotationsLayerBuilderClosure() {
  1601. /**
  1602. * @param {AnnotationsLayerBuilderOptions} options
  1603. * @constructs AnnotationsLayerBuilder
  1604. */
  1605. function AnnotationsLayerBuilder(options) {
  1606. this.pageDiv = options.pageDiv;
  1607. this.pdfPage = options.pdfPage;
  1608. this.linkService = options.linkService;
  1609. this.div = null;
  1610. }
  1611. AnnotationsLayerBuilder.prototype =
  1612. /** @lends AnnotationsLayerBuilder.prototype */ {
  1613. /**
  1614. * @param {PageViewport} viewport
  1615. */
  1616. setupAnnotations:
  1617. function AnnotationsLayerBuilder_setupAnnotations(viewport) {
  1618. function bindLink(link, dest) {
  1619. link.href = linkService.getDestinationHash(dest);
  1620. link.onclick = function annotationsLayerBuilderLinksOnclick() {
  1621. if (dest) {
  1622. linkService.navigateTo(dest);
  1623. }
  1624. return false;
  1625. };
  1626. if (dest) {
  1627. link.className = 'internalLink';
  1628. }
  1629. }
  1630. function bindNamedAction(link, action) {
  1631. link.href = linkService.getAnchorUrl('');
  1632. link.onclick = function annotationsLayerBuilderNamedActionOnClick() {
  1633. linkService.executeNamedAction(action);
  1634. return false;
  1635. };
  1636. link.className = 'internalLink';
  1637. }
  1638. var linkService = this.linkService;
  1639. var pdfPage = this.pdfPage;
  1640. var self = this;
  1641. pdfPage.getAnnotations().then(function (annotationsData) {
  1642. viewport = viewport.clone({ dontFlip: true });
  1643. var transform = viewport.transform;
  1644. var transformStr = 'matrix(' + transform.join(',') + ')';
  1645. var data, element, i, ii;
  1646. if (self.div) {
  1647. // If an annotationLayer already exists, refresh its children's
  1648. // transformation matrices
  1649. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  1650. data = annotationsData[i];
  1651. element = self.div.querySelector(
  1652. '[data-annotation-id="' + data.id + '"]');
  1653. if (element) {
  1654. CustomStyle.setProp('transform', element, transformStr);
  1655. }
  1656. }
  1657. // See PDFPageView.reset()
  1658. self.div.removeAttribute('hidden');
  1659. } else {
  1660. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  1661. data = annotationsData[i];
  1662. if (!data || !data.hasHtml) {
  1663. continue;
  1664. }
  1665. element = PDFJS.AnnotationUtils.getHtmlElement(data,
  1666. pdfPage.commonObjs);
  1667. element.setAttribute('data-annotation-id', data.id);
  1668. if (typeof mozL10n !== 'undefined') {
  1669. mozL10n.translate(element);
  1670. }
  1671. var rect = data.rect;
  1672. var view = pdfPage.view;
  1673. rect = PDFJS.Util.normalizeRect([
  1674. rect[0],
  1675. view[3] - rect[1] + view[1],
  1676. rect[2],
  1677. view[3] - rect[3] + view[1]
  1678. ]);
  1679. element.style.left = rect[0] + 'px';
  1680. element.style.top = rect[1] + 'px';
  1681. element.style.position = 'absolute';
  1682. CustomStyle.setProp('transform', element, transformStr);
  1683. var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
  1684. CustomStyle.setProp('transformOrigin', element, transformOriginStr);
  1685. if (data.subtype === 'Link' && !data.url) {
  1686. var link = element.getElementsByTagName('a')[0];
  1687. if (link) {
  1688. if (data.action) {
  1689. bindNamedAction(link, data.action);
  1690. } else {
  1691. bindLink(link, ('dest' in data) ? data.dest : null);
  1692. }
  1693. }
  1694. }
  1695. if (!self.div) {
  1696. var annotationLayerDiv = document.createElement('div');
  1697. annotationLayerDiv.className = 'annotationLayer';
  1698. self.pageDiv.appendChild(annotationLayerDiv);
  1699. self.div = annotationLayerDiv;
  1700. }
  1701. self.div.appendChild(element);
  1702. }
  1703. }
  1704. });
  1705. },
  1706. hide: function () {
  1707. if (!this.div) {
  1708. return;
  1709. }
  1710. this.div.setAttribute('hidden', 'true');
  1711. }
  1712. };
  1713. return AnnotationsLayerBuilder;
  1714. })();
  1715. /**
  1716. * @constructor
  1717. * @implements IPDFAnnotationsLayerFactory
  1718. */
  1719. function DefaultAnnotationsLayerFactory() {}
  1720. DefaultAnnotationsLayerFactory.prototype = {
  1721. /**
  1722. * @param {HTMLDivElement} pageDiv
  1723. * @param {PDFPage} pdfPage
  1724. * @returns {AnnotationsLayerBuilder}
  1725. */
  1726. createAnnotationsLayerBuilder: function (pageDiv, pdfPage) {
  1727. return new AnnotationsLayerBuilder({
  1728. pageDiv: pageDiv,
  1729. pdfPage: pdfPage,
  1730. linkService: new SimpleLinkService(),
  1731. });
  1732. }
  1733. };
  1734. /**
  1735. * @typedef {Object} PDFViewerOptions
  1736. * @property {HTMLDivElement} container - The container for the viewer element.
  1737. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  1738. * @property {IPDFLinkService} linkService - The navigation/linking service.
  1739. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  1740. * queue object.
  1741. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  1742. * around the pages. The default is false.
  1743. */
  1744. /**
  1745. * Simple viewer control to display PDF content/pages.
  1746. * @class
  1747. * @implements {IRenderableView}
  1748. */
  1749. var PDFViewer = (function pdfViewer() {
  1750. function PDFPageViewBuffer(size) {
  1751. var data = [];
  1752. this.push = function cachePush(view) {
  1753. var i = data.indexOf(view);
  1754. if (i >= 0) {
  1755. data.splice(i, 1);
  1756. }
  1757. data.push(view);
  1758. if (data.length > size) {
  1759. data.shift().destroy();
  1760. }
  1761. };
  1762. this.resize = function (newSize) {
  1763. size = newSize;
  1764. while (data.length > size) {
  1765. data.shift().destroy();
  1766. }
  1767. };
  1768. }
  1769. function isSameScale(oldScale, newScale) {
  1770. if (newScale === oldScale) {
  1771. return true;
  1772. }
  1773. if (Math.abs(newScale - oldScale) < 1e-15) {
  1774. // Prevent unnecessary re-rendering of all pages when the scale
  1775. // changes only because of limited numerical precision.
  1776. return true;
  1777. }
  1778. return false;
  1779. }
  1780. /**
  1781. * @constructs PDFViewer
  1782. * @param {PDFViewerOptions} options
  1783. */
  1784. function PDFViewer(options) {
  1785. this.container = options.container;
  1786. this.viewer = options.viewer || options.container.firstElementChild;
  1787. this.linkService = options.linkService || new SimpleLinkService();
  1788. this.removePageBorders = options.removePageBorders || false;
  1789. this.defaultRenderingQueue = !options.renderingQueue;
  1790. if (this.defaultRenderingQueue) {
  1791. // Custom rendering queue is not specified, using default one
  1792. this.renderingQueue = new PDFRenderingQueue();
  1793. this.renderingQueue.setViewer(this);
  1794. } else {
  1795. this.renderingQueue = options.renderingQueue;
  1796. }
  1797. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  1798. this.updateInProgress = false;
  1799. this.presentationModeState = PresentationModeState.UNKNOWN;
  1800. this._resetView();
  1801. if (this.removePageBorders) {
  1802. this.viewer.classList.add('removePageBorders');
  1803. }
  1804. }
  1805. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  1806. get pagesCount() {
  1807. return this._pages.length;
  1808. },
  1809. getPageView: function (index) {
  1810. return this._pages[index];
  1811. },
  1812. get currentPageNumber() {
  1813. return this._currentPageNumber;
  1814. },
  1815. set currentPageNumber(val) {
  1816. if (!this.pdfDocument) {
  1817. this._currentPageNumber = val;
  1818. return;
  1819. }
  1820. var event = document.createEvent('UIEvents');
  1821. event.initUIEvent('pagechange', true, true, window, 0);
  1822. event.updateInProgress = this.updateInProgress;
  1823. if (!(0 < val && val <= this.pagesCount)) {
  1824. event.pageNumber = this._currentPageNumber;
  1825. event.previousPageNumber = val;
  1826. this.container.dispatchEvent(event);
  1827. return;
  1828. }
  1829. event.previousPageNumber = this._currentPageNumber;
  1830. this._currentPageNumber = val;
  1831. event.pageNumber = val;
  1832. this.container.dispatchEvent(event);
  1833. // Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
  1834. if (this.updateInProgress) {
  1835. return;
  1836. }
  1837. this.scrollPageIntoView(val);
  1838. },
  1839. /**
  1840. * @returns {number}
  1841. */
  1842. get currentScale() {
  1843. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  1844. DEFAULT_SCALE;
  1845. },
  1846. /**
  1847. * @param {number} val - Scale of the pages in percents.
  1848. */
  1849. set currentScale(val) {
  1850. if (isNaN(val)) {
  1851. throw new Error('Invalid numeric scale');
  1852. }
  1853. if (!this.pdfDocument) {
  1854. this._currentScale = val;
  1855. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  1856. return;
  1857. }
  1858. this._setScale(val, false);
  1859. },
  1860. /**
  1861. * @returns {string}
  1862. */
  1863. get currentScaleValue() {
  1864. return this._currentScaleValue;
  1865. },
  1866. /**
  1867. * @param val - The scale of the pages (in percent or predefined value).
  1868. */
  1869. set currentScaleValue(val) {
  1870. if (!this.pdfDocument) {
  1871. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  1872. this._currentScaleValue = val;
  1873. return;
  1874. }
  1875. this._setScale(val, false);
  1876. },
  1877. /**
  1878. * @returns {number}
  1879. */
  1880. get pagesRotation() {
  1881. return this._pagesRotation;
  1882. },
  1883. /**
  1884. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  1885. */
  1886. set pagesRotation(rotation) {
  1887. this._pagesRotation = rotation;
  1888. for (var i = 0, l = this._pages.length; i < l; i++) {
  1889. var pageView = this._pages[i];
  1890. pageView.update(pageView.scale, rotation);
  1891. }
  1892. this._setScale(this._currentScaleValue, true);
  1893. },
  1894. /**
  1895. * @param pdfDocument {PDFDocument}
  1896. */
  1897. setDocument: function (pdfDocument) {
  1898. if (this.pdfDocument) {
  1899. this._resetView();
  1900. }
  1901. this.pdfDocument = pdfDocument;
  1902. if (!pdfDocument) {
  1903. return;
  1904. }
  1905. var pagesCount = pdfDocument.numPages;
  1906. var self = this;
  1907. var resolvePagesPromise;
  1908. var pagesPromise = new Promise(function (resolve) {
  1909. resolvePagesPromise = resolve;
  1910. });
  1911. this.pagesPromise = pagesPromise;
  1912. pagesPromise.then(function () {
  1913. var event = document.createEvent('CustomEvent');
  1914. event.initCustomEvent('pagesloaded', true, true, {
  1915. pagesCount: pagesCount
  1916. });
  1917. self.container.dispatchEvent(event);
  1918. });
  1919. var isOnePageRenderedResolved = false;
  1920. var resolveOnePageRendered = null;
  1921. var onePageRendered = new Promise(function (resolve) {
  1922. resolveOnePageRendered = resolve;
  1923. });
  1924. this.onePageRendered = onePageRendered;
  1925. var bindOnAfterAndBeforeDraw = function (pageView) {
  1926. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  1927. // Add the page to the buffer at the start of drawing. That way it can
  1928. // be evicted from the buffer and destroyed even if we pause its
  1929. // rendering.
  1930. self._buffer.push(this);
  1931. };
  1932. // when page is painted, using the image as thumbnail base
  1933. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  1934. if (!isOnePageRenderedResolved) {
  1935. isOnePageRenderedResolved = true;
  1936. resolveOnePageRendered();
  1937. }
  1938. };
  1939. };
  1940. var firstPagePromise = pdfDocument.getPage(1);
  1941. this.firstPagePromise = firstPagePromise;
  1942. // Fetch a single page so we can get a viewport that will be the default
  1943. // viewport for all pages
  1944. return firstPagePromise.then(function(pdfPage) {
  1945. var scale = this.currentScale;
  1946. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  1947. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1948. var textLayerFactory = null;
  1949. if (!PDFJS.disableTextLayer) {
  1950. textLayerFactory = this;
  1951. }
  1952. var pageView = new PDFPageView({
  1953. container: this.viewer,
  1954. id: pageNum,
  1955. scale: scale,
  1956. defaultViewport: viewport.clone(),
  1957. renderingQueue: this.renderingQueue,
  1958. textLayerFactory: textLayerFactory,
  1959. annotationsLayerFactory: this
  1960. });
  1961. bindOnAfterAndBeforeDraw(pageView);
  1962. this._pages.push(pageView);
  1963. }
  1964. var linkService = this.linkService;
  1965. // Fetch all the pages since the viewport is needed before printing
  1966. // starts to create the correct size canvas. Wait until one page is
  1967. // rendered so we don't tie up too many resources early on.
  1968. onePageRendered.then(function () {
  1969. if (!PDFJS.disableAutoFetch) {
  1970. var getPagesLeft = pagesCount;
  1971. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1972. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  1973. var pageView = self._pages[pageNum - 1];
  1974. if (!pageView.pdfPage) {
  1975. pageView.setPdfPage(pdfPage);
  1976. }
  1977. linkService.cachePageRef(pageNum, pdfPage.ref);
  1978. getPagesLeft--;
  1979. if (!getPagesLeft) {
  1980. resolvePagesPromise();
  1981. }
  1982. }.bind(null, pageNum));
  1983. }
  1984. } else {
  1985. // XXX: Printing is semi-broken with auto fetch disabled.
  1986. resolvePagesPromise();
  1987. }
  1988. });
  1989. var event = document.createEvent('CustomEvent');
  1990. event.initCustomEvent('pagesinit', true, true, null);
  1991. self.container.dispatchEvent(event);
  1992. if (this.defaultRenderingQueue) {
  1993. this.update();
  1994. }
  1995. if (this.findController) {
  1996. this.findController.resolveFirstPage();
  1997. }
  1998. }.bind(this));
  1999. },
  2000. _resetView: function () {
  2001. this._pages = [];
  2002. this._currentPageNumber = 1;
  2003. this._currentScale = UNKNOWN_SCALE;
  2004. this._currentScaleValue = null;
  2005. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  2006. this._location = null;
  2007. this._pagesRotation = 0;
  2008. this._pagesRequests = [];
  2009. var container = this.viewer;
  2010. while (container.hasChildNodes()) {
  2011. container.removeChild(container.lastChild);
  2012. }
  2013. },
  2014. _scrollUpdate: function () {
  2015. if (this.pagesCount === 0) {
  2016. return;
  2017. }
  2018. this.update();
  2019. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2020. this._pages[i].updatePosition();
  2021. }
  2022. },
  2023. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  2024. newScale, newValue, preset) {
  2025. var event = document.createEvent('UIEvents');
  2026. event.initUIEvent('scalechange', true, true, window, 0);
  2027. event.scale = newScale;
  2028. if (preset) {
  2029. event.presetValue = newValue;
  2030. }
  2031. this.container.dispatchEvent(event);
  2032. },
  2033. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  2034. newScale, newValue, noScroll, preset) {
  2035. this._currentScaleValue = newValue;
  2036. if (isSameScale(this._currentScale, newScale)) {
  2037. if (preset) {
  2038. this._setScaleDispatchEvent(newScale, newValue, true);
  2039. }
  2040. return;
  2041. }
  2042. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2043. this._pages[i].update(newScale);
  2044. }
  2045. this._currentScale = newScale;
  2046. if (!noScroll) {
  2047. var page = this._currentPageNumber, dest;
  2048. if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
  2049. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  2050. page = this._location.pageNumber;
  2051. dest = [null, { name: 'XYZ' }, this._location.left,
  2052. this._location.top, null];
  2053. }
  2054. this.scrollPageIntoView(page, dest);
  2055. }
  2056. this._setScaleDispatchEvent(newScale, newValue, preset);
  2057. },
  2058. _setScale: function pdfViewer_setScale(value, noScroll) {
  2059. if (value === 'custom') {
  2060. return;
  2061. }
  2062. var scale = parseFloat(value);
  2063. if (scale > 0) {
  2064. this._setScaleUpdatePages(scale, value, noScroll, false);
  2065. } else {
  2066. var currentPage = this._pages[this._currentPageNumber - 1];
  2067. if (!currentPage) {
  2068. return;
  2069. }
  2070. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  2071. 0 : SCROLLBAR_PADDING;
  2072. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  2073. 0 : VERTICAL_PADDING;
  2074. var pageWidthScale = (this.container.clientWidth - hPadding) /
  2075. currentPage.width * currentPage.scale;
  2076. var pageHeightScale = (this.container.clientHeight - vPadding) /
  2077. currentPage.height * currentPage.scale;
  2078. switch (value) {
  2079. case 'page-actual':
  2080. scale = 1;
  2081. break;
  2082. case 'page-width':
  2083. scale = pageWidthScale;
  2084. break;
  2085. case 'page-height':
  2086. scale = pageHeightScale;
  2087. break;
  2088. case 'page-fit':
  2089. scale = Math.min(pageWidthScale, pageHeightScale);
  2090. break;
  2091. case 'auto':
  2092. var isLandscape = (currentPage.width > currentPage.height);
  2093. // For pages in landscape mode, fit the page height to the viewer
  2094. // *unless* the page would thus become too wide to fit horizontally.
  2095. var horizontalScale = isLandscape ?
  2096. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  2097. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  2098. break;
  2099. default:
  2100. console.error('pdfViewSetScale: \'' + value +
  2101. '\' is an unknown zoom value.');
  2102. return;
  2103. }
  2104. this._setScaleUpdatePages(scale, value, noScroll, true);
  2105. }
  2106. },
  2107. /**
  2108. * Scrolls page into view.
  2109. * @param {number} pageNumber
  2110. * @param {Array} dest - (optional) original PDF destination array:
  2111. * <page-ref> </XYZ|FitXXX> <args..>
  2112. */
  2113. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  2114. dest) {
  2115. var pageView = this._pages[pageNumber - 1];
  2116. if (this.isInPresentationMode) {
  2117. if (this._currentPageNumber !== pageView.id) {
  2118. // Avoid breaking getVisiblePages in presentation mode.
  2119. this.currentPageNumber = pageView.id;
  2120. return;
  2121. }
  2122. dest = null;
  2123. // Fixes the case when PDF has different page sizes.
  2124. this._setScale(this._currentScaleValue, true);
  2125. }
  2126. if (!dest) {
  2127. scrollIntoView(pageView.div);
  2128. return;
  2129. }
  2130. var x = 0, y = 0;
  2131. var width = 0, height = 0, widthScale, heightScale;
  2132. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  2133. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  2134. pageView.scale / CSS_UNITS;
  2135. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  2136. pageView.scale / CSS_UNITS;
  2137. var scale = 0;
  2138. switch (dest[1].name) {
  2139. case 'XYZ':
  2140. x = dest[2];
  2141. y = dest[3];
  2142. scale = dest[4];
  2143. // If x and/or y coordinates are not supplied, default to
  2144. // _top_ left of the page (not the obvious bottom left,
  2145. // since aligning the bottom of the intended page with the
  2146. // top of the window is rarely helpful).
  2147. x = x !== null ? x : 0;
  2148. y = y !== null ? y : pageHeight;
  2149. break;
  2150. case 'Fit':
  2151. case 'FitB':
  2152. scale = 'page-fit';
  2153. break;
  2154. case 'FitH':
  2155. case 'FitBH':
  2156. y = dest[2];
  2157. scale = 'page-width';
  2158. break;
  2159. case 'FitV':
  2160. case 'FitBV':
  2161. x = dest[2];
  2162. width = pageWidth;
  2163. height = pageHeight;
  2164. scale = 'page-height';
  2165. break;
  2166. case 'FitR':
  2167. x = dest[2];
  2168. y = dest[3];
  2169. width = dest[4] - x;
  2170. height = dest[5] - y;
  2171. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  2172. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  2173. widthScale = (this.container.clientWidth - hPadding) /
  2174. width / CSS_UNITS;
  2175. heightScale = (this.container.clientHeight - vPadding) /
  2176. height / CSS_UNITS;
  2177. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  2178. break;
  2179. default:
  2180. return;
  2181. }
  2182. if (scale && scale !== this._currentScale) {
  2183. this.currentScaleValue = scale;
  2184. } else if (this._currentScale === UNKNOWN_SCALE) {
  2185. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  2186. }
  2187. if (scale === 'page-fit' && !dest[4]) {
  2188. scrollIntoView(pageView.div);
  2189. return;
  2190. }
  2191. var boundingRect = [
  2192. pageView.viewport.convertToViewportPoint(x, y),
  2193. pageView.viewport.convertToViewportPoint(x + width, y + height)
  2194. ];
  2195. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  2196. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  2197. scrollIntoView(pageView.div, { left: left, top: top });
  2198. },
  2199. _updateLocation: function (firstPage) {
  2200. var currentScale = this._currentScale;
  2201. var currentScaleValue = this._currentScaleValue;
  2202. var normalizedScaleValue =
  2203. parseFloat(currentScaleValue) === currentScale ?
  2204. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  2205. var pageNumber = firstPage.id;
  2206. var pdfOpenParams = '#page=' + pageNumber;
  2207. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  2208. var currentPageView = this._pages[pageNumber - 1];
  2209. var container = this.container;
  2210. var topLeft = currentPageView.getPagePoint(
  2211. (container.scrollLeft - firstPage.x),
  2212. (container.scrollTop - firstPage.y));
  2213. var intLeft = Math.round(topLeft[0]);
  2214. var intTop = Math.round(topLeft[1]);
  2215. pdfOpenParams += ',' + intLeft + ',' + intTop;
  2216. this._location = {
  2217. pageNumber: pageNumber,
  2218. scale: normalizedScaleValue,
  2219. top: intTop,
  2220. left: intLeft,
  2221. pdfOpenParams: pdfOpenParams
  2222. };
  2223. },
  2224. update: function PDFViewer_update() {
  2225. var visible = this._getVisiblePages();
  2226. var visiblePages = visible.views;
  2227. if (visiblePages.length === 0) {
  2228. return;
  2229. }
  2230. this.updateInProgress = true;
  2231. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  2232. 2 * visiblePages.length + 1);
  2233. this._buffer.resize(suggestedCacheSize);
  2234. this.renderingQueue.renderHighestPriority(visible);
  2235. var currentId = this._currentPageNumber;
  2236. var firstPage = visible.first;
  2237. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  2238. i < ii; ++i) {
  2239. var page = visiblePages[i];
  2240. if (page.percent < 100) {
  2241. break;
  2242. }
  2243. if (page.id === currentId) {
  2244. stillFullyVisible = true;
  2245. break;
  2246. }
  2247. }
  2248. if (!stillFullyVisible) {
  2249. currentId = visiblePages[0].id;
  2250. }
  2251. if (!this.isInPresentationMode) {
  2252. this.currentPageNumber = currentId;
  2253. }
  2254. this._updateLocation(firstPage);
  2255. this.updateInProgress = false;
  2256. var event = document.createEvent('UIEvents');
  2257. event.initUIEvent('updateviewarea', true, true, window, 0);
  2258. event.location = this._location;
  2259. this.container.dispatchEvent(event);
  2260. },
  2261. containsElement: function (element) {
  2262. return this.container.contains(element);
  2263. },
  2264. focus: function () {
  2265. this.container.focus();
  2266. },
  2267. get isInPresentationMode() {
  2268. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  2269. },
  2270. get isChangingPresentationMode() {
  2271. return this.PresentationModeState === PresentationModeState.CHANGING;
  2272. },
  2273. get isHorizontalScrollbarEnabled() {
  2274. return (this.isInPresentationMode ?
  2275. false : (this.container.scrollWidth > this.container.clientWidth));
  2276. },
  2277. _getVisiblePages: function () {
  2278. if (!this.isInPresentationMode) {
  2279. return getVisibleElements(this.container, this._pages, true);
  2280. } else {
  2281. // The algorithm in getVisibleElements doesn't work in all browsers and
  2282. // configurations when presentation mode is active.
  2283. var visible = [];
  2284. var currentPage = this._pages[this._currentPageNumber - 1];
  2285. visible.push({ id: currentPage.id, view: currentPage });
  2286. return { first: currentPage, last: currentPage, views: visible };
  2287. }
  2288. },
  2289. cleanup: function () {
  2290. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2291. if (this._pages[i] &&
  2292. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  2293. this._pages[i].reset();
  2294. }
  2295. }
  2296. },
  2297. /**
  2298. * @param {PDFPageView} pageView
  2299. * @returns {PDFPage}
  2300. * @private
  2301. */
  2302. _ensurePdfPageLoaded: function (pageView) {
  2303. if (pageView.pdfPage) {
  2304. return Promise.resolve(pageView.pdfPage);
  2305. }
  2306. var pageNumber = pageView.id;
  2307. if (this._pagesRequests[pageNumber]) {
  2308. return this._pagesRequests[pageNumber];
  2309. }
  2310. var promise = this.pdfDocument.getPage(pageNumber).then(
  2311. function (pdfPage) {
  2312. pageView.setPdfPage(pdfPage);
  2313. this._pagesRequests[pageNumber] = null;
  2314. return pdfPage;
  2315. }.bind(this));
  2316. this._pagesRequests[pageNumber] = promise;
  2317. return promise;
  2318. },
  2319. forceRendering: function (currentlyVisiblePages) {
  2320. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  2321. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  2322. this._pages,
  2323. this.scroll.down);
  2324. if (pageView) {
  2325. this._ensurePdfPageLoaded(pageView).then(function () {
  2326. this.renderingQueue.renderView(pageView);
  2327. }.bind(this));
  2328. return true;
  2329. }
  2330. return false;
  2331. },
  2332. getPageTextContent: function (pageIndex) {
  2333. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  2334. return page.getTextContent();
  2335. });
  2336. },
  2337. /**
  2338. * @param {HTMLDivElement} textLayerDiv
  2339. * @param {number} pageIndex
  2340. * @param {PageViewport} viewport
  2341. * @returns {TextLayerBuilder}
  2342. */
  2343. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  2344. return new TextLayerBuilder({
  2345. textLayerDiv: textLayerDiv,
  2346. pageIndex: pageIndex,
  2347. viewport: viewport,
  2348. findController: this.isInPresentationMode ? null : this.findController
  2349. });
  2350. },
  2351. /**
  2352. * @param {HTMLDivElement} pageDiv
  2353. * @param {PDFPage} pdfPage
  2354. * @returns {AnnotationsLayerBuilder}
  2355. */
  2356. createAnnotationsLayerBuilder: function (pageDiv, pdfPage) {
  2357. return new AnnotationsLayerBuilder({
  2358. pageDiv: pageDiv,
  2359. pdfPage: pdfPage,
  2360. linkService: this.linkService
  2361. });
  2362. },
  2363. setFindController: function (findController) {
  2364. this.findController = findController;
  2365. },
  2366. };
  2367. return PDFViewer;
  2368. })();
  2369. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  2370. function SimpleLinkService() {}
  2371. SimpleLinkService.prototype = {
  2372. /**
  2373. * @returns {number}
  2374. */
  2375. get page() {
  2376. return 0;
  2377. },
  2378. /**
  2379. * @param {number} value
  2380. */
  2381. set page(value) {},
  2382. /**
  2383. * @param dest - The PDF destination object.
  2384. */
  2385. navigateTo: function (dest) {},
  2386. /**
  2387. * @param dest - The PDF destination object.
  2388. * @returns {string} The hyperlink to the PDF object.
  2389. */
  2390. getDestinationHash: function (dest) {
  2391. return '#';
  2392. },
  2393. /**
  2394. * @param hash - The PDF parameters/hash.
  2395. * @returns {string} The hyperlink to the PDF object.
  2396. */
  2397. getAnchorUrl: function (hash) {
  2398. return '#';
  2399. },
  2400. /**
  2401. * @param {string} hash
  2402. */
  2403. setHash: function (hash) {},
  2404. /**
  2405. * @param {string} action
  2406. */
  2407. executeNamedAction: function (action) {},
  2408. /**
  2409. * @param {number} pageNum - page number.
  2410. * @param {Object} pageRef - reference to the page.
  2411. */
  2412. cachePageRef: function (pageNum, pageRef) {}
  2413. };
  2414. return SimpleLinkService;
  2415. })();
  2416. var PDFHistory = (function () {
  2417. function PDFHistory(options) {
  2418. this.linkService = options.linkService;
  2419. this.initialized = false;
  2420. this.initialDestination = null;
  2421. this.initialBookmark = null;
  2422. }
  2423. PDFHistory.prototype = {
  2424. /**
  2425. * @param {string} fingerprint
  2426. * @param {IPDFLinkService} linkService
  2427. */
  2428. initialize: function pdfHistoryInitialize(fingerprint) {
  2429. this.initialized = true;
  2430. this.reInitialized = false;
  2431. this.allowHashChange = true;
  2432. this.historyUnlocked = true;
  2433. this.isViewerInPresentationMode = false;
  2434. this.previousHash = window.location.hash.substring(1);
  2435. this.currentBookmark = '';
  2436. this.currentPage = 0;
  2437. this.updatePreviousBookmark = false;
  2438. this.previousBookmark = '';
  2439. this.previousPage = 0;
  2440. this.nextHashParam = '';
  2441. this.fingerprint = fingerprint;
  2442. this.currentUid = this.uid = 0;
  2443. this.current = {};
  2444. var state = window.history.state;
  2445. if (this._isStateObjectDefined(state)) {
  2446. // This corresponds to navigating back to the document
  2447. // from another page in the browser history.
  2448. if (state.target.dest) {
  2449. this.initialDestination = state.target.dest;
  2450. } else {
  2451. this.initialBookmark = state.target.hash;
  2452. }
  2453. this.currentUid = state.uid;
  2454. this.uid = state.uid + 1;
  2455. this.current = state.target;
  2456. } else {
  2457. // This corresponds to the loading of a new document.
  2458. if (state && state.fingerprint &&
  2459. this.fingerprint !== state.fingerprint) {
  2460. // Reinitialize the browsing history when a new document
  2461. // is opened in the web viewer.
  2462. this.reInitialized = true;
  2463. }
  2464. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  2465. }
  2466. var self = this;
  2467. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  2468. evt.preventDefault();
  2469. evt.stopPropagation();
  2470. if (!self.historyUnlocked) {
  2471. return;
  2472. }
  2473. if (evt.state) {
  2474. // Move back/forward in the history.
  2475. self._goTo(evt.state);
  2476. } else {
  2477. // Handle the user modifying the hash of a loaded document.
  2478. self.previousHash = window.location.hash.substring(1);
  2479. // If the history is empty when the hash changes,
  2480. // update the previous entry in the browser history.
  2481. if (self.uid === 0) {
  2482. var previousParams = (self.previousHash && self.currentBookmark &&
  2483. self.previousHash !== self.currentBookmark) ?
  2484. {hash: self.currentBookmark, page: self.currentPage} :
  2485. {page: 1};
  2486. self.historyUnlocked = false;
  2487. self.allowHashChange = false;
  2488. window.history.back();
  2489. self._pushToHistory(previousParams, false, true);
  2490. window.history.forward();
  2491. self.historyUnlocked = true;
  2492. }
  2493. self._pushToHistory({hash: self.previousHash}, false, true);
  2494. self._updatePreviousBookmark();
  2495. }
  2496. }, false);
  2497. function pdfHistoryBeforeUnload() {
  2498. var previousParams = self._getPreviousParams(null, true);
  2499. if (previousParams) {
  2500. var replacePrevious = (!self.current.dest &&
  2501. self.current.hash !== self.previousHash);
  2502. self._pushToHistory(previousParams, false, replacePrevious);
  2503. self._updatePreviousBookmark();
  2504. }
  2505. // Remove the event listener when navigating away from the document,
  2506. // since 'beforeunload' prevents Firefox from caching the document.
  2507. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  2508. false);
  2509. }
  2510. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2511. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  2512. // If the entire viewer (including the PDF file) is cached in
  2513. // the browser, we need to reattach the 'beforeunload' event listener
  2514. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  2515. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2516. }, false);
  2517. window.addEventListener('presentationmodechanged', function(e) {
  2518. self.isViewerInPresentationMode = !!e.detail.active;
  2519. });
  2520. },
  2521. clearHistoryState: function pdfHistory_clearHistoryState() {
  2522. this._pushOrReplaceState(null, true);
  2523. },
  2524. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  2525. return (state && state.uid >= 0 &&
  2526. state.fingerprint && this.fingerprint === state.fingerprint &&
  2527. state.target && state.target.hash) ? true : false;
  2528. },
  2529. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  2530. replace) {
  2531. if (replace) {
  2532. window.history.replaceState(stateObj, '');
  2533. } else {
  2534. window.history.pushState(stateObj, '');
  2535. }
  2536. },
  2537. get isHashChangeUnlocked() {
  2538. if (!this.initialized) {
  2539. return true;
  2540. }
  2541. // If the current hash changes when moving back/forward in the history,
  2542. // this will trigger a 'popstate' event *as well* as a 'hashchange' event.
  2543. // Since the hash generally won't correspond to the exact the position
  2544. // stored in the history's state object, triggering the 'hashchange' event
  2545. // can thus corrupt the browser history.
  2546. //
  2547. // When the hash changes during a 'popstate' event, we *only* prevent the
  2548. // first 'hashchange' event and immediately reset allowHashChange.
  2549. // If it is not reset, the user would not be able to change the hash.
  2550. var temp = this.allowHashChange;
  2551. this.allowHashChange = true;
  2552. return temp;
  2553. },
  2554. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  2555. if (this.updatePreviousBookmark &&
  2556. this.currentBookmark && this.currentPage) {
  2557. this.previousBookmark = this.currentBookmark;
  2558. this.previousPage = this.currentPage;
  2559. this.updatePreviousBookmark = false;
  2560. }
  2561. },
  2562. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  2563. pageNum) {
  2564. if (this.initialized) {
  2565. this.currentBookmark = bookmark.substring(1);
  2566. this.currentPage = pageNum | 0;
  2567. this._updatePreviousBookmark();
  2568. }
  2569. },
  2570. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  2571. if (this.initialized) {
  2572. this.nextHashParam = param;
  2573. }
  2574. },
  2575. push: function pdfHistoryPush(params, isInitialBookmark) {
  2576. if (!(this.initialized && this.historyUnlocked)) {
  2577. return;
  2578. }
  2579. if (params.dest && !params.hash) {
  2580. params.hash = (this.current.hash && this.current.dest &&
  2581. this.current.dest === params.dest) ?
  2582. this.current.hash :
  2583. this.linkService.getDestinationHash(params.dest).split('#')[1];
  2584. }
  2585. if (params.page) {
  2586. params.page |= 0;
  2587. }
  2588. if (isInitialBookmark) {
  2589. var target = window.history.state.target;
  2590. if (!target) {
  2591. // Invoked when the user specifies an initial bookmark,
  2592. // thus setting initialBookmark, when the document is loaded.
  2593. this._pushToHistory(params, false);
  2594. this.previousHash = window.location.hash.substring(1);
  2595. }
  2596. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  2597. if (target) {
  2598. // If the current document is reloaded,
  2599. // avoid creating duplicate entries in the history.
  2600. this._updatePreviousBookmark();
  2601. }
  2602. return;
  2603. }
  2604. if (this.nextHashParam) {
  2605. if (this.nextHashParam === params.hash) {
  2606. this.nextHashParam = null;
  2607. this.updatePreviousBookmark = true;
  2608. return;
  2609. } else {
  2610. this.nextHashParam = null;
  2611. }
  2612. }
  2613. if (params.hash) {
  2614. if (this.current.hash) {
  2615. if (this.current.hash !== params.hash) {
  2616. this._pushToHistory(params, true);
  2617. } else {
  2618. if (!this.current.page && params.page) {
  2619. this._pushToHistory(params, false, true);
  2620. }
  2621. this.updatePreviousBookmark = true;
  2622. }
  2623. } else {
  2624. this._pushToHistory(params, true);
  2625. }
  2626. } else if (this.current.page && params.page &&
  2627. this.current.page !== params.page) {
  2628. this._pushToHistory(params, true);
  2629. }
  2630. },
  2631. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  2632. beforeUnload) {
  2633. if (!(this.currentBookmark && this.currentPage)) {
  2634. return null;
  2635. } else if (this.updatePreviousBookmark) {
  2636. this.updatePreviousBookmark = false;
  2637. }
  2638. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  2639. // Prevent the history from getting stuck in the current state,
  2640. // effectively preventing the user from going back/forward in
  2641. // the history.
  2642. //
  2643. // This happens if the current position in the document didn't change
  2644. // when the history was previously updated. The reasons for this are
  2645. // either:
  2646. // 1. The current zoom value is such that the document does not need to,
  2647. // or cannot, be scrolled to display the destination.
  2648. // 2. The previous destination is broken, and doesn't actally point to a
  2649. // position within the document.
  2650. // (This is either due to a bad PDF generator, or the user making a
  2651. // mistake when entering a destination in the hash parameters.)
  2652. return null;
  2653. }
  2654. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  2655. if (this.previousBookmark === this.currentBookmark) {
  2656. return null;
  2657. }
  2658. } else if (this.current.page || onlyCheckPage) {
  2659. if (this.previousPage === this.currentPage) {
  2660. return null;
  2661. }
  2662. } else {
  2663. return null;
  2664. }
  2665. var params = {hash: this.currentBookmark, page: this.currentPage};
  2666. if (this.isViewerInPresentationMode) {
  2667. params.hash = null;
  2668. }
  2669. return params;
  2670. },
  2671. _stateObj: function pdfHistory_stateObj(params) {
  2672. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  2673. },
  2674. _pushToHistory: function pdfHistory_pushToHistory(params,
  2675. addPrevious, overwrite) {
  2676. if (!this.initialized) {
  2677. return;
  2678. }
  2679. if (!params.hash && params.page) {
  2680. params.hash = ('page=' + params.page);
  2681. }
  2682. if (addPrevious && !overwrite) {
  2683. var previousParams = this._getPreviousParams();
  2684. if (previousParams) {
  2685. var replacePrevious = (!this.current.dest &&
  2686. this.current.hash !== this.previousHash);
  2687. this._pushToHistory(previousParams, false, replacePrevious);
  2688. }
  2689. }
  2690. this._pushOrReplaceState(this._stateObj(params),
  2691. (overwrite || this.uid === 0));
  2692. this.currentUid = this.uid++;
  2693. this.current = params;
  2694. this.updatePreviousBookmark = true;
  2695. },
  2696. _goTo: function pdfHistory_goTo(state) {
  2697. if (!(this.initialized && this.historyUnlocked &&
  2698. this._isStateObjectDefined(state))) {
  2699. return;
  2700. }
  2701. if (!this.reInitialized && state.uid < this.currentUid) {
  2702. var previousParams = this._getPreviousParams(true);
  2703. if (previousParams) {
  2704. this._pushToHistory(this.current, false);
  2705. this._pushToHistory(previousParams, false);
  2706. this.currentUid = state.uid;
  2707. window.history.back();
  2708. return;
  2709. }
  2710. }
  2711. this.historyUnlocked = false;
  2712. if (state.target.dest) {
  2713. this.linkService.navigateTo(state.target.dest);
  2714. } else {
  2715. this.linkService.setHash(state.target.hash);
  2716. }
  2717. this.currentUid = state.uid;
  2718. if (state.uid > this.uid) {
  2719. this.uid = state.uid;
  2720. }
  2721. this.current = state.target;
  2722. this.updatePreviousBookmark = true;
  2723. var currentHash = window.location.hash.substring(1);
  2724. if (this.previousHash !== currentHash) {
  2725. this.allowHashChange = false;
  2726. }
  2727. this.previousHash = currentHash;
  2728. this.historyUnlocked = true;
  2729. },
  2730. back: function pdfHistoryBack() {
  2731. this.go(-1);
  2732. },
  2733. forward: function pdfHistoryForward() {
  2734. this.go(1);
  2735. },
  2736. go: function pdfHistoryGo(direction) {
  2737. if (this.initialized && this.historyUnlocked) {
  2738. var state = window.history.state;
  2739. if (direction === -1 && state && state.uid > 0) {
  2740. window.history.back();
  2741. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  2742. window.history.forward();
  2743. }
  2744. }
  2745. }
  2746. };
  2747. return PDFHistory;
  2748. })();
  2749. PDFJS.PDFViewer = PDFViewer;
  2750. PDFJS.PDFPageView = PDFPageView;
  2751. PDFJS.PDFLinkService = PDFLinkService;
  2752. PDFJS.TextLayerBuilder = TextLayerBuilder;
  2753. PDFJS.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2754. PDFJS.AnnotationsLayerBuilder = AnnotationsLayerBuilder;
  2755. PDFJS.DefaultAnnotationsLayerFactory = DefaultAnnotationsLayerFactory;
  2756. PDFJS.PDFHistory = PDFHistory;
  2757. PDFJS.getFileName = getFileName;
  2758. PDFJS.ProgressBar = ProgressBar;
  2759. }).call((typeof window === 'undefined') ? this : window);