pdf_viewer.js 99 KB

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