pdf_viewer.js 96 KB

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