pdf_viewer.js 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160
  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(keepZoomLayer, 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 currentZoomLayerNode = (keepZoomLayer && 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 (currentZoomLayerNode === node || currentAnnotationNode === node) {
  871. continue;
  872. }
  873. div.removeChild(node);
  874. }
  875. div.removeAttribute('data-loaded');
  876. if (currentAnnotationNode) {
  877. // Hide annotationLayer until all elements are resized
  878. // so they are not displayed on the already-resized page
  879. this.annotationLayer.hide();
  880. } else {
  881. this.annotationLayer = null;
  882. }
  883. if (this.canvas && !currentZoomLayerNode) {
  884. // Zeroing the width and height causes Firefox to release graphics
  885. // resources immediately, which can greatly reduce memory consumption.
  886. this.canvas.width = 0;
  887. this.canvas.height = 0;
  888. delete this.canvas;
  889. }
  890. this.loadingIconDiv = document.createElement('div');
  891. this.loadingIconDiv.className = 'loadingIcon';
  892. div.appendChild(this.loadingIconDiv);
  893. },
  894. update: function PDFPageView_update(scale, rotation) {
  895. this.scale = scale || this.scale;
  896. if (typeof rotation !== 'undefined') {
  897. this.rotation = rotation;
  898. }
  899. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  900. this.viewport = this.viewport.clone({
  901. scale: this.scale * CSS_UNITS,
  902. rotation: totalRotation
  903. });
  904. var isScalingRestricted = false;
  905. if (this.canvas && PDFJS.maxCanvasPixels > 0) {
  906. var ctx = this.canvas.getContext('2d');
  907. var outputScale = getOutputScale(ctx);
  908. var pixelsInViewport = this.viewport.width * this.viewport.height;
  909. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  910. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  911. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  912. PDFJS.maxCanvasPixels) {
  913. isScalingRestricted = true;
  914. }
  915. }
  916. if (this.canvas) {
  917. if (PDFJS.useOnlyCssZoom ||
  918. (this.hasRestrictedScaling && isScalingRestricted)) {
  919. this.cssTransform(this.canvas, true);
  920. return;
  921. }
  922. if (!this.zoomLayer) {
  923. this.zoomLayer = this.canvas.parentNode;
  924. this.zoomLayer.style.position = 'absolute';
  925. }
  926. }
  927. if (this.zoomLayer) {
  928. this.cssTransform(this.zoomLayer.firstChild);
  929. }
  930. this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ 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 && this.annotationLayer.div) {
  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 && this.annotationLayer.div) {
  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. // Zeroing the width and height causes Firefox to release graphics
  1115. // resources immediately, which can greatly reduce memory consumption.
  1116. var zoomLayerCanvas = self.zoomLayer.firstChild;
  1117. zoomLayerCanvas.width = 0;
  1118. zoomLayerCanvas.height = 0;
  1119. div.removeChild(self.zoomLayer);
  1120. self.zoomLayer = null;
  1121. }
  1122. self.error = error;
  1123. self.stats = pdfPage.stats;
  1124. if (self.onAfterDraw) {
  1125. self.onAfterDraw();
  1126. }
  1127. var event = document.createEvent('CustomEvent');
  1128. event.initCustomEvent('pagerendered', true, true, {
  1129. pageNumber: self.id
  1130. });
  1131. div.dispatchEvent(event);
  1132. if (!error) {
  1133. resolveRenderPromise(undefined);
  1134. } else {
  1135. rejectRenderPromise(error);
  1136. }
  1137. }
  1138. var renderContinueCallback = null;
  1139. if (this.renderingQueue) {
  1140. renderContinueCallback = function renderContinueCallback(cont) {
  1141. if (!self.renderingQueue.isHighestPriority(self)) {
  1142. self.renderingState = RenderingStates.PAUSED;
  1143. self.resume = function resumeCallback() {
  1144. self.renderingState = RenderingStates.RUNNING;
  1145. cont();
  1146. };
  1147. return;
  1148. }
  1149. cont();
  1150. };
  1151. }
  1152. var renderContext = {
  1153. canvasContext: ctx,
  1154. viewport: this.viewport,
  1155. // intent: 'default', // === 'display'
  1156. continueCallback: renderContinueCallback
  1157. };
  1158. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  1159. this.renderTask.promise.then(
  1160. function pdfPageRenderCallback() {
  1161. pageViewDrawCallback(null);
  1162. if (textLayer) {
  1163. self.pdfPage.getTextContent().then(
  1164. function textContentResolved(textContent) {
  1165. textLayer.setTextContent(textContent);
  1166. textLayer.render(TEXT_LAYER_RENDER_DELAY);
  1167. }
  1168. );
  1169. }
  1170. },
  1171. function pdfPageRenderError(error) {
  1172. pageViewDrawCallback(error);
  1173. }
  1174. );
  1175. if (this.annotationsLayerFactory) {
  1176. if (!this.annotationLayer) {
  1177. this.annotationLayer = this.annotationsLayerFactory.
  1178. createAnnotationsLayerBuilder(div, this.pdfPage);
  1179. }
  1180. this.annotationLayer.setupAnnotations(this.viewport);
  1181. }
  1182. div.setAttribute('data-loaded', true);
  1183. if (self.onBeforeDraw) {
  1184. self.onBeforeDraw();
  1185. }
  1186. return promise;
  1187. },
  1188. beforePrint: function PDFPageView_beforePrint() {
  1189. var pdfPage = this.pdfPage;
  1190. var viewport = pdfPage.getViewport(1);
  1191. // Use the same hack we use for high dpi displays for printing to get
  1192. // better output until bug 811002 is fixed in FF.
  1193. var PRINT_OUTPUT_SCALE = 2;
  1194. var canvas = document.createElement('canvas');
  1195. // The logical size of the canvas.
  1196. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  1197. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  1198. // The rendered size of the canvas, relative to the size of canvasWrapper.
  1199. canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
  1200. canvas.style.height = (PRINT_OUTPUT_SCALE * 100) + '%';
  1201. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  1202. (1 / PRINT_OUTPUT_SCALE) + ')';
  1203. CustomStyle.setProp('transform' , canvas, cssScale);
  1204. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  1205. var printContainer = document.getElementById('printContainer');
  1206. var canvasWrapper = document.createElement('div');
  1207. canvasWrapper.style.width = viewport.width + 'pt';
  1208. canvasWrapper.style.height = viewport.height + 'pt';
  1209. canvasWrapper.appendChild(canvas);
  1210. printContainer.appendChild(canvasWrapper);
  1211. canvas.mozPrintCallback = function(obj) {
  1212. var ctx = obj.context;
  1213. ctx.save();
  1214. ctx.fillStyle = 'rgb(255, 255, 255)';
  1215. ctx.fillRect(0, 0, canvas.width, canvas.height);
  1216. ctx.restore();
  1217. // Used by the mozCurrentTransform polyfill in src/display/canvas.js.
  1218. ctx._transformMatrix =
  1219. [PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
  1220. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  1221. var renderContext = {
  1222. canvasContext: ctx,
  1223. viewport: viewport,
  1224. intent: 'print'
  1225. };
  1226. pdfPage.render(renderContext).promise.then(function() {
  1227. // Tell the printEngine that rendering this canvas/page has finished.
  1228. obj.done();
  1229. }, function(error) {
  1230. console.error(error);
  1231. // Tell the printEngine that rendering this canvas/page has failed.
  1232. // This will make the print proces stop.
  1233. if ('abort' in obj) {
  1234. obj.abort();
  1235. } else {
  1236. obj.done();
  1237. }
  1238. });
  1239. };
  1240. },
  1241. };
  1242. return PDFPageView;
  1243. })();
  1244. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  1245. var NonWhitespaceRegexp = /\S/;
  1246. function isAllWhitespace(str) {
  1247. return !NonWhitespaceRegexp.test(str);
  1248. }
  1249. /**
  1250. * @typedef {Object} TextLayerBuilderOptions
  1251. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  1252. * @property {number} pageIndex - The page index.
  1253. * @property {PageViewport} viewport - The viewport of the text layer.
  1254. * @property {PDFFindController} findController
  1255. */
  1256. /**
  1257. * TextLayerBuilder provides text-selection functionality for the PDF.
  1258. * It does this by creating overlay divs over the PDF text. These divs
  1259. * contain text that matches the PDF text they are overlaying. This object
  1260. * also provides a way to highlight text that is being searched for.
  1261. * @class
  1262. */
  1263. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  1264. function TextLayerBuilder(options) {
  1265. this.textLayerDiv = options.textLayerDiv;
  1266. this.renderingDone = false;
  1267. this.divContentDone = false;
  1268. this.pageIdx = options.pageIndex;
  1269. this.pageNumber = this.pageIdx + 1;
  1270. this.matches = [];
  1271. this.viewport = options.viewport;
  1272. this.textDivs = [];
  1273. this.findController = options.findController || null;
  1274. }
  1275. TextLayerBuilder.prototype = {
  1276. _finishRendering: function TextLayerBuilder_finishRendering() {
  1277. this.renderingDone = true;
  1278. var event = document.createEvent('CustomEvent');
  1279. event.initCustomEvent('textlayerrendered', true, true, {
  1280. pageNumber: this.pageNumber
  1281. });
  1282. this.textLayerDiv.dispatchEvent(event);
  1283. },
  1284. renderLayer: function TextLayerBuilder_renderLayer() {
  1285. var textLayerFrag = document.createDocumentFragment();
  1286. var textDivs = this.textDivs;
  1287. var textDivsLength = textDivs.length;
  1288. var canvas = document.createElement('canvas');
  1289. var ctx = canvas.getContext('2d');
  1290. // No point in rendering many divs as it would make the browser
  1291. // unusable even after the divs are rendered.
  1292. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  1293. this._finishRendering();
  1294. return;
  1295. }
  1296. var lastFontSize;
  1297. var lastFontFamily;
  1298. for (var i = 0; i < textDivsLength; i++) {
  1299. var textDiv = textDivs[i];
  1300. if (textDiv.dataset.isWhitespace !== undefined) {
  1301. continue;
  1302. }
  1303. var fontSize = textDiv.style.fontSize;
  1304. var fontFamily = textDiv.style.fontFamily;
  1305. // Only build font string and set to context if different from last.
  1306. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  1307. ctx.font = fontSize + ' ' + fontFamily;
  1308. lastFontSize = fontSize;
  1309. lastFontFamily = fontFamily;
  1310. }
  1311. var width = ctx.measureText(textDiv.textContent).width;
  1312. if (width > 0) {
  1313. textLayerFrag.appendChild(textDiv);
  1314. var transform;
  1315. if (textDiv.dataset.canvasWidth !== undefined) {
  1316. // Dataset values come of type string.
  1317. var textScale = textDiv.dataset.canvasWidth / width;
  1318. transform = 'scaleX(' + textScale + ')';
  1319. } else {
  1320. transform = '';
  1321. }
  1322. var rotation = textDiv.dataset.angle;
  1323. if (rotation) {
  1324. transform = 'rotate(' + rotation + 'deg) ' + transform;
  1325. }
  1326. if (transform) {
  1327. CustomStyle.setProp('transform' , textDiv, transform);
  1328. }
  1329. }
  1330. }
  1331. this.textLayerDiv.appendChild(textLayerFrag);
  1332. this._finishRendering();
  1333. this.updateMatches();
  1334. },
  1335. /**
  1336. * Renders the text layer.
  1337. * @param {number} timeout (optional) if specified, the rendering waits
  1338. * for specified amount of ms.
  1339. */
  1340. render: function TextLayerBuilder_render(timeout) {
  1341. if (!this.divContentDone || this.renderingDone) {
  1342. return;
  1343. }
  1344. if (this.renderTimer) {
  1345. clearTimeout(this.renderTimer);
  1346. this.renderTimer = null;
  1347. }
  1348. if (!timeout) { // Render right away
  1349. this.renderLayer();
  1350. } else { // Schedule
  1351. var self = this;
  1352. this.renderTimer = setTimeout(function() {
  1353. self.renderLayer();
  1354. self.renderTimer = null;
  1355. }, timeout);
  1356. }
  1357. },
  1358. appendText: function TextLayerBuilder_appendText(geom, styles) {
  1359. var style = styles[geom.fontName];
  1360. var textDiv = document.createElement('div');
  1361. this.textDivs.push(textDiv);
  1362. if (isAllWhitespace(geom.str)) {
  1363. textDiv.dataset.isWhitespace = true;
  1364. return;
  1365. }
  1366. var tx = PDFJS.Util.transform(this.viewport.transform, geom.transform);
  1367. var angle = Math.atan2(tx[1], tx[0]);
  1368. if (style.vertical) {
  1369. angle += Math.PI / 2;
  1370. }
  1371. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  1372. var fontAscent = fontHeight;
  1373. if (style.ascent) {
  1374. fontAscent = style.ascent * fontAscent;
  1375. } else if (style.descent) {
  1376. fontAscent = (1 + style.descent) * fontAscent;
  1377. }
  1378. var left;
  1379. var top;
  1380. if (angle === 0) {
  1381. left = tx[4];
  1382. top = tx[5] - fontAscent;
  1383. } else {
  1384. left = tx[4] + (fontAscent * Math.sin(angle));
  1385. top = tx[5] - (fontAscent * Math.cos(angle));
  1386. }
  1387. textDiv.style.left = left + 'px';
  1388. textDiv.style.top = top + 'px';
  1389. textDiv.style.fontSize = fontHeight + 'px';
  1390. textDiv.style.fontFamily = style.fontFamily;
  1391. textDiv.textContent = geom.str;
  1392. // |fontName| is only used by the Font Inspector. This test will succeed
  1393. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  1394. // not worth the effort to do a more accurate test.
  1395. if (PDFJS.pdfBug) {
  1396. textDiv.dataset.fontName = geom.fontName;
  1397. }
  1398. // Storing into dataset will convert number into string.
  1399. if (angle !== 0) {
  1400. textDiv.dataset.angle = angle * (180 / Math.PI);
  1401. }
  1402. // We don't bother scaling single-char text divs, because it has very
  1403. // little effect on text highlighting. This makes scrolling on docs with
  1404. // lots of such divs a lot faster.
  1405. if (geom.str.length > 1) {
  1406. if (style.vertical) {
  1407. textDiv.dataset.canvasWidth = geom.height * this.viewport.scale;
  1408. } else {
  1409. textDiv.dataset.canvasWidth = geom.width * this.viewport.scale;
  1410. }
  1411. }
  1412. },
  1413. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  1414. this.textContent = textContent;
  1415. var textItems = textContent.items;
  1416. for (var i = 0, len = textItems.length; i < len; i++) {
  1417. this.appendText(textItems[i], textContent.styles);
  1418. }
  1419. this.divContentDone = true;
  1420. },
  1421. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  1422. var i = 0;
  1423. var iIndex = 0;
  1424. var bidiTexts = this.textContent.items;
  1425. var end = bidiTexts.length - 1;
  1426. var queryLen = (this.findController === null ?
  1427. 0 : this.findController.state.query.length);
  1428. var ret = [];
  1429. for (var m = 0, len = matches.length; m < len; m++) {
  1430. // Calculate the start position.
  1431. var matchIdx = matches[m];
  1432. // Loop over the divIdxs.
  1433. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  1434. iIndex += bidiTexts[i].str.length;
  1435. i++;
  1436. }
  1437. if (i === bidiTexts.length) {
  1438. console.error('Could not find a matching mapping');
  1439. }
  1440. var match = {
  1441. begin: {
  1442. divIdx: i,
  1443. offset: matchIdx - iIndex
  1444. }
  1445. };
  1446. // Calculate the end position.
  1447. matchIdx += queryLen;
  1448. // Somewhat the same array as above, but use > instead of >= to get
  1449. // the end position right.
  1450. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  1451. iIndex += bidiTexts[i].str.length;
  1452. i++;
  1453. }
  1454. match.end = {
  1455. divIdx: i,
  1456. offset: matchIdx - iIndex
  1457. };
  1458. ret.push(match);
  1459. }
  1460. return ret;
  1461. },
  1462. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  1463. // Early exit if there is nothing to render.
  1464. if (matches.length === 0) {
  1465. return;
  1466. }
  1467. var bidiTexts = this.textContent.items;
  1468. var textDivs = this.textDivs;
  1469. var prevEnd = null;
  1470. var pageIdx = this.pageIdx;
  1471. var isSelectedPage = (this.findController === null ?
  1472. false : (pageIdx === this.findController.selected.pageIdx));
  1473. var selectedMatchIdx = (this.findController === null ?
  1474. -1 : this.findController.selected.matchIdx);
  1475. var highlightAll = (this.findController === null ?
  1476. false : this.findController.state.highlightAll);
  1477. var infinity = {
  1478. divIdx: -1,
  1479. offset: undefined
  1480. };
  1481. function beginText(begin, className) {
  1482. var divIdx = begin.divIdx;
  1483. textDivs[divIdx].textContent = '';
  1484. appendTextToDiv(divIdx, 0, begin.offset, className);
  1485. }
  1486. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  1487. var div = textDivs[divIdx];
  1488. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  1489. var node = document.createTextNode(content);
  1490. if (className) {
  1491. var span = document.createElement('span');
  1492. span.className = className;
  1493. span.appendChild(node);
  1494. div.appendChild(span);
  1495. return;
  1496. }
  1497. div.appendChild(node);
  1498. }
  1499. var i0 = selectedMatchIdx, i1 = i0 + 1;
  1500. if (highlightAll) {
  1501. i0 = 0;
  1502. i1 = matches.length;
  1503. } else if (!isSelectedPage) {
  1504. // Not highlighting all and this isn't the selected page, so do nothing.
  1505. return;
  1506. }
  1507. for (var i = i0; i < i1; i++) {
  1508. var match = matches[i];
  1509. var begin = match.begin;
  1510. var end = match.end;
  1511. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  1512. var highlightSuffix = (isSelected ? ' selected' : '');
  1513. if (this.findController) {
  1514. this.findController.updateMatchPosition(pageIdx, i, textDivs,
  1515. begin.divIdx, end.divIdx);
  1516. }
  1517. // Match inside new div.
  1518. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  1519. // If there was a previous div, then add the text at the end.
  1520. if (prevEnd !== null) {
  1521. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1522. }
  1523. // Clear the divs and set the content until the starting point.
  1524. beginText(begin);
  1525. } else {
  1526. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  1527. }
  1528. if (begin.divIdx === end.divIdx) {
  1529. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  1530. 'highlight' + highlightSuffix);
  1531. } else {
  1532. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  1533. 'highlight begin' + highlightSuffix);
  1534. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  1535. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  1536. }
  1537. beginText(end, 'highlight end' + highlightSuffix);
  1538. }
  1539. prevEnd = end;
  1540. }
  1541. if (prevEnd) {
  1542. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1543. }
  1544. },
  1545. updateMatches: function TextLayerBuilder_updateMatches() {
  1546. // Only show matches when all rendering is done.
  1547. if (!this.renderingDone) {
  1548. return;
  1549. }
  1550. // Clear all matches.
  1551. var matches = this.matches;
  1552. var textDivs = this.textDivs;
  1553. var bidiTexts = this.textContent.items;
  1554. var clearedUntilDivIdx = -1;
  1555. // Clear all current matches.
  1556. for (var i = 0, len = matches.length; i < len; i++) {
  1557. var match = matches[i];
  1558. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  1559. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  1560. var div = textDivs[n];
  1561. div.textContent = bidiTexts[n].str;
  1562. div.className = '';
  1563. }
  1564. clearedUntilDivIdx = match.end.divIdx + 1;
  1565. }
  1566. if (this.findController === null || !this.findController.active) {
  1567. return;
  1568. }
  1569. // Convert the matches on the page controller into the match format
  1570. // used for the textLayer.
  1571. this.matches = this.convertMatches(this.findController === null ?
  1572. [] : (this.findController.pageMatches[this.pageIdx] || []));
  1573. this.renderMatches(this.matches);
  1574. }
  1575. };
  1576. return TextLayerBuilder;
  1577. })();
  1578. /**
  1579. * @constructor
  1580. * @implements IPDFTextLayerFactory
  1581. */
  1582. function DefaultTextLayerFactory() {}
  1583. DefaultTextLayerFactory.prototype = {
  1584. /**
  1585. * @param {HTMLDivElement} textLayerDiv
  1586. * @param {number} pageIndex
  1587. * @param {PageViewport} viewport
  1588. * @returns {TextLayerBuilder}
  1589. */
  1590. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  1591. return new TextLayerBuilder({
  1592. textLayerDiv: textLayerDiv,
  1593. pageIndex: pageIndex,
  1594. viewport: viewport
  1595. });
  1596. }
  1597. };
  1598. /**
  1599. * @typedef {Object} AnnotationsLayerBuilderOptions
  1600. * @property {HTMLDivElement} pageDiv
  1601. * @property {PDFPage} pdfPage
  1602. * @property {IPDFLinkService} linkService
  1603. */
  1604. /**
  1605. * @class
  1606. */
  1607. var AnnotationsLayerBuilder = (function AnnotationsLayerBuilderClosure() {
  1608. /**
  1609. * @param {AnnotationsLayerBuilderOptions} options
  1610. * @constructs AnnotationsLayerBuilder
  1611. */
  1612. function AnnotationsLayerBuilder(options) {
  1613. this.pageDiv = options.pageDiv;
  1614. this.pdfPage = options.pdfPage;
  1615. this.linkService = options.linkService;
  1616. this.div = null;
  1617. }
  1618. AnnotationsLayerBuilder.prototype =
  1619. /** @lends AnnotationsLayerBuilder.prototype */ {
  1620. /**
  1621. * @param {PageViewport} viewport
  1622. */
  1623. setupAnnotations:
  1624. function AnnotationsLayerBuilder_setupAnnotations(viewport) {
  1625. function bindLink(link, dest) {
  1626. link.href = linkService.getDestinationHash(dest);
  1627. link.onclick = function annotationsLayerBuilderLinksOnclick() {
  1628. if (dest) {
  1629. linkService.navigateTo(dest);
  1630. }
  1631. return false;
  1632. };
  1633. if (dest) {
  1634. link.className = 'internalLink';
  1635. }
  1636. }
  1637. function bindNamedAction(link, action) {
  1638. link.href = linkService.getAnchorUrl('');
  1639. link.onclick = function annotationsLayerBuilderNamedActionOnClick() {
  1640. linkService.executeNamedAction(action);
  1641. return false;
  1642. };
  1643. link.className = 'internalLink';
  1644. }
  1645. var linkService = this.linkService;
  1646. var pdfPage = this.pdfPage;
  1647. var self = this;
  1648. pdfPage.getAnnotations().then(function (annotationsData) {
  1649. viewport = viewport.clone({ dontFlip: true });
  1650. var transform = viewport.transform;
  1651. var transformStr = 'matrix(' + transform.join(',') + ')';
  1652. var data, element, i, ii;
  1653. if (self.div) {
  1654. // If an annotationLayer already exists, refresh its children's
  1655. // transformation matrices
  1656. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  1657. data = annotationsData[i];
  1658. element = self.div.querySelector(
  1659. '[data-annotation-id="' + data.id + '"]');
  1660. if (element) {
  1661. CustomStyle.setProp('transform', element, transformStr);
  1662. }
  1663. }
  1664. // See PDFPageView.reset()
  1665. self.div.removeAttribute('hidden');
  1666. } else {
  1667. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  1668. data = annotationsData[i];
  1669. if (!data || !data.hasHtml) {
  1670. continue;
  1671. }
  1672. element = PDFJS.AnnotationUtils.getHtmlElement(data,
  1673. pdfPage.commonObjs);
  1674. element.setAttribute('data-annotation-id', data.id);
  1675. if (typeof mozL10n !== 'undefined') {
  1676. mozL10n.translate(element);
  1677. }
  1678. var rect = data.rect;
  1679. var view = pdfPage.view;
  1680. rect = PDFJS.Util.normalizeRect([
  1681. rect[0],
  1682. view[3] - rect[1] + view[1],
  1683. rect[2],
  1684. view[3] - rect[3] + view[1]
  1685. ]);
  1686. element.style.left = rect[0] + 'px';
  1687. element.style.top = rect[1] + 'px';
  1688. element.style.position = 'absolute';
  1689. CustomStyle.setProp('transform', element, transformStr);
  1690. var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
  1691. CustomStyle.setProp('transformOrigin', element, transformOriginStr);
  1692. if (data.subtype === 'Link' && !data.url) {
  1693. var link = element.getElementsByTagName('a')[0];
  1694. if (link) {
  1695. if (data.action) {
  1696. bindNamedAction(link, data.action);
  1697. } else {
  1698. bindLink(link, ('dest' in data) ? data.dest : null);
  1699. }
  1700. }
  1701. }
  1702. if (!self.div) {
  1703. var annotationLayerDiv = document.createElement('div');
  1704. annotationLayerDiv.className = 'annotationLayer';
  1705. self.pageDiv.appendChild(annotationLayerDiv);
  1706. self.div = annotationLayerDiv;
  1707. }
  1708. self.div.appendChild(element);
  1709. }
  1710. }
  1711. });
  1712. },
  1713. hide: function () {
  1714. if (!this.div) {
  1715. return;
  1716. }
  1717. this.div.setAttribute('hidden', 'true');
  1718. }
  1719. };
  1720. return AnnotationsLayerBuilder;
  1721. })();
  1722. /**
  1723. * @constructor
  1724. * @implements IPDFAnnotationsLayerFactory
  1725. */
  1726. function DefaultAnnotationsLayerFactory() {}
  1727. DefaultAnnotationsLayerFactory.prototype = {
  1728. /**
  1729. * @param {HTMLDivElement} pageDiv
  1730. * @param {PDFPage} pdfPage
  1731. * @returns {AnnotationsLayerBuilder}
  1732. */
  1733. createAnnotationsLayerBuilder: function (pageDiv, pdfPage) {
  1734. return new AnnotationsLayerBuilder({
  1735. pageDiv: pageDiv,
  1736. pdfPage: pdfPage,
  1737. linkService: new SimpleLinkService(),
  1738. });
  1739. }
  1740. };
  1741. /**
  1742. * @typedef {Object} PDFViewerOptions
  1743. * @property {HTMLDivElement} container - The container for the viewer element.
  1744. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  1745. * @property {IPDFLinkService} linkService - The navigation/linking service.
  1746. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  1747. * queue object.
  1748. * @property {boolean} removePageBorders - (optional) Removes the border shadow
  1749. * around the pages. The default is false.
  1750. */
  1751. /**
  1752. * Simple viewer control to display PDF content/pages.
  1753. * @class
  1754. * @implements {IRenderableView}
  1755. */
  1756. var PDFViewer = (function pdfViewer() {
  1757. function PDFPageViewBuffer(size) {
  1758. var data = [];
  1759. this.push = function cachePush(view) {
  1760. var i = data.indexOf(view);
  1761. if (i >= 0) {
  1762. data.splice(i, 1);
  1763. }
  1764. data.push(view);
  1765. if (data.length > size) {
  1766. data.shift().destroy();
  1767. }
  1768. };
  1769. this.resize = function (newSize) {
  1770. size = newSize;
  1771. while (data.length > size) {
  1772. data.shift().destroy();
  1773. }
  1774. };
  1775. }
  1776. function isSameScale(oldScale, newScale) {
  1777. if (newScale === oldScale) {
  1778. return true;
  1779. }
  1780. if (Math.abs(newScale - oldScale) < 1e-15) {
  1781. // Prevent unnecessary re-rendering of all pages when the scale
  1782. // changes only because of limited numerical precision.
  1783. return true;
  1784. }
  1785. return false;
  1786. }
  1787. /**
  1788. * @constructs PDFViewer
  1789. * @param {PDFViewerOptions} options
  1790. */
  1791. function PDFViewer(options) {
  1792. this.container = options.container;
  1793. this.viewer = options.viewer || options.container.firstElementChild;
  1794. this.linkService = options.linkService || new SimpleLinkService();
  1795. this.removePageBorders = options.removePageBorders || false;
  1796. this.defaultRenderingQueue = !options.renderingQueue;
  1797. if (this.defaultRenderingQueue) {
  1798. // Custom rendering queue is not specified, using default one
  1799. this.renderingQueue = new PDFRenderingQueue();
  1800. this.renderingQueue.setViewer(this);
  1801. } else {
  1802. this.renderingQueue = options.renderingQueue;
  1803. }
  1804. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  1805. this.updateInProgress = false;
  1806. this.presentationModeState = PresentationModeState.UNKNOWN;
  1807. this._resetView();
  1808. if (this.removePageBorders) {
  1809. this.viewer.classList.add('removePageBorders');
  1810. }
  1811. }
  1812. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  1813. get pagesCount() {
  1814. return this._pages.length;
  1815. },
  1816. getPageView: function (index) {
  1817. return this._pages[index];
  1818. },
  1819. get currentPageNumber() {
  1820. return this._currentPageNumber;
  1821. },
  1822. set currentPageNumber(val) {
  1823. if (!this.pdfDocument) {
  1824. this._currentPageNumber = val;
  1825. return;
  1826. }
  1827. var event = document.createEvent('UIEvents');
  1828. event.initUIEvent('pagechange', true, true, window, 0);
  1829. event.updateInProgress = this.updateInProgress;
  1830. if (!(0 < val && val <= this.pagesCount)) {
  1831. event.pageNumber = this._currentPageNumber;
  1832. event.previousPageNumber = val;
  1833. this.container.dispatchEvent(event);
  1834. return;
  1835. }
  1836. event.previousPageNumber = this._currentPageNumber;
  1837. this._currentPageNumber = val;
  1838. event.pageNumber = val;
  1839. this.container.dispatchEvent(event);
  1840. // Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
  1841. if (this.updateInProgress) {
  1842. return;
  1843. }
  1844. this.scrollPageIntoView(val);
  1845. },
  1846. /**
  1847. * @returns {number}
  1848. */
  1849. get currentScale() {
  1850. return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
  1851. DEFAULT_SCALE;
  1852. },
  1853. /**
  1854. * @param {number} val - Scale of the pages in percents.
  1855. */
  1856. set currentScale(val) {
  1857. if (isNaN(val)) {
  1858. throw new Error('Invalid numeric scale');
  1859. }
  1860. if (!this.pdfDocument) {
  1861. this._currentScale = val;
  1862. this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
  1863. return;
  1864. }
  1865. this._setScale(val, false);
  1866. },
  1867. /**
  1868. * @returns {string}
  1869. */
  1870. get currentScaleValue() {
  1871. return this._currentScaleValue;
  1872. },
  1873. /**
  1874. * @param val - The scale of the pages (in percent or predefined value).
  1875. */
  1876. set currentScaleValue(val) {
  1877. if (!this.pdfDocument) {
  1878. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  1879. this._currentScaleValue = val;
  1880. return;
  1881. }
  1882. this._setScale(val, false);
  1883. },
  1884. /**
  1885. * @returns {number}
  1886. */
  1887. get pagesRotation() {
  1888. return this._pagesRotation;
  1889. },
  1890. /**
  1891. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  1892. */
  1893. set pagesRotation(rotation) {
  1894. this._pagesRotation = rotation;
  1895. for (var i = 0, l = this._pages.length; i < l; i++) {
  1896. var pageView = this._pages[i];
  1897. pageView.update(pageView.scale, rotation);
  1898. }
  1899. this._setScale(this._currentScaleValue, true);
  1900. if (this.defaultRenderingQueue) {
  1901. this.update();
  1902. }
  1903. },
  1904. /**
  1905. * @param pdfDocument {PDFDocument}
  1906. */
  1907. setDocument: function (pdfDocument) {
  1908. if (this.pdfDocument) {
  1909. this._resetView();
  1910. }
  1911. this.pdfDocument = pdfDocument;
  1912. if (!pdfDocument) {
  1913. return;
  1914. }
  1915. var pagesCount = pdfDocument.numPages;
  1916. var self = this;
  1917. var resolvePagesPromise;
  1918. var pagesPromise = new Promise(function (resolve) {
  1919. resolvePagesPromise = resolve;
  1920. });
  1921. this.pagesPromise = pagesPromise;
  1922. pagesPromise.then(function () {
  1923. var event = document.createEvent('CustomEvent');
  1924. event.initCustomEvent('pagesloaded', true, true, {
  1925. pagesCount: pagesCount
  1926. });
  1927. self.container.dispatchEvent(event);
  1928. });
  1929. var isOnePageRenderedResolved = false;
  1930. var resolveOnePageRendered = null;
  1931. var onePageRendered = new Promise(function (resolve) {
  1932. resolveOnePageRendered = resolve;
  1933. });
  1934. this.onePageRendered = onePageRendered;
  1935. var bindOnAfterAndBeforeDraw = function (pageView) {
  1936. pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
  1937. // Add the page to the buffer at the start of drawing. That way it can
  1938. // be evicted from the buffer and destroyed even if we pause its
  1939. // rendering.
  1940. self._buffer.push(this);
  1941. };
  1942. // when page is painted, using the image as thumbnail base
  1943. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  1944. if (!isOnePageRenderedResolved) {
  1945. isOnePageRenderedResolved = true;
  1946. resolveOnePageRendered();
  1947. }
  1948. };
  1949. };
  1950. var firstPagePromise = pdfDocument.getPage(1);
  1951. this.firstPagePromise = firstPagePromise;
  1952. // Fetch a single page so we can get a viewport that will be the default
  1953. // viewport for all pages
  1954. return firstPagePromise.then(function(pdfPage) {
  1955. var scale = this.currentScale;
  1956. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  1957. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1958. var textLayerFactory = null;
  1959. if (!PDFJS.disableTextLayer) {
  1960. textLayerFactory = this;
  1961. }
  1962. var pageView = new PDFPageView({
  1963. container: this.viewer,
  1964. id: pageNum,
  1965. scale: scale,
  1966. defaultViewport: viewport.clone(),
  1967. renderingQueue: this.renderingQueue,
  1968. textLayerFactory: textLayerFactory,
  1969. annotationsLayerFactory: this
  1970. });
  1971. bindOnAfterAndBeforeDraw(pageView);
  1972. this._pages.push(pageView);
  1973. }
  1974. var linkService = this.linkService;
  1975. // Fetch all the pages since the viewport is needed before printing
  1976. // starts to create the correct size canvas. Wait until one page is
  1977. // rendered so we don't tie up too many resources early on.
  1978. onePageRendered.then(function () {
  1979. if (!PDFJS.disableAutoFetch) {
  1980. var getPagesLeft = pagesCount;
  1981. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1982. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  1983. var pageView = self._pages[pageNum - 1];
  1984. if (!pageView.pdfPage) {
  1985. pageView.setPdfPage(pdfPage);
  1986. }
  1987. linkService.cachePageRef(pageNum, pdfPage.ref);
  1988. getPagesLeft--;
  1989. if (!getPagesLeft) {
  1990. resolvePagesPromise();
  1991. }
  1992. }.bind(null, pageNum));
  1993. }
  1994. } else {
  1995. // XXX: Printing is semi-broken with auto fetch disabled.
  1996. resolvePagesPromise();
  1997. }
  1998. });
  1999. var event = document.createEvent('CustomEvent');
  2000. event.initCustomEvent('pagesinit', true, true, null);
  2001. self.container.dispatchEvent(event);
  2002. if (this.defaultRenderingQueue) {
  2003. this.update();
  2004. }
  2005. if (this.findController) {
  2006. this.findController.resolveFirstPage();
  2007. }
  2008. }.bind(this));
  2009. },
  2010. _resetView: function () {
  2011. this._pages = [];
  2012. this._currentPageNumber = 1;
  2013. this._currentScale = UNKNOWN_SCALE;
  2014. this._currentScaleValue = null;
  2015. this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  2016. this._location = null;
  2017. this._pagesRotation = 0;
  2018. this._pagesRequests = [];
  2019. var container = this.viewer;
  2020. while (container.hasChildNodes()) {
  2021. container.removeChild(container.lastChild);
  2022. }
  2023. },
  2024. _scrollUpdate: function PDFViewer_scrollUpdate() {
  2025. if (this.pagesCount === 0) {
  2026. return;
  2027. }
  2028. this.update();
  2029. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2030. this._pages[i].updatePosition();
  2031. }
  2032. },
  2033. _setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
  2034. newScale, newValue, preset) {
  2035. var event = document.createEvent('UIEvents');
  2036. event.initUIEvent('scalechange', true, true, window, 0);
  2037. event.scale = newScale;
  2038. if (preset) {
  2039. event.presetValue = newValue;
  2040. }
  2041. this.container.dispatchEvent(event);
  2042. },
  2043. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  2044. newScale, newValue, noScroll, preset) {
  2045. this._currentScaleValue = newValue;
  2046. if (isSameScale(this._currentScale, newScale)) {
  2047. if (preset) {
  2048. this._setScaleDispatchEvent(newScale, newValue, true);
  2049. }
  2050. return;
  2051. }
  2052. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2053. this._pages[i].update(newScale);
  2054. }
  2055. this._currentScale = newScale;
  2056. if (!noScroll) {
  2057. var page = this._currentPageNumber, dest;
  2058. if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
  2059. !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  2060. page = this._location.pageNumber;
  2061. dest = [null, { name: 'XYZ' }, this._location.left,
  2062. this._location.top, null];
  2063. }
  2064. this.scrollPageIntoView(page, dest);
  2065. }
  2066. this._setScaleDispatchEvent(newScale, newValue, preset);
  2067. if (this.defaultRenderingQueue) {
  2068. this.update();
  2069. }
  2070. },
  2071. _setScale: function pdfViewer_setScale(value, noScroll) {
  2072. var scale = parseFloat(value);
  2073. if (scale > 0) {
  2074. this._setScaleUpdatePages(scale, value, noScroll, false);
  2075. } else {
  2076. var currentPage = this._pages[this._currentPageNumber - 1];
  2077. if (!currentPage) {
  2078. return;
  2079. }
  2080. var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
  2081. 0 : SCROLLBAR_PADDING;
  2082. var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
  2083. 0 : VERTICAL_PADDING;
  2084. var pageWidthScale = (this.container.clientWidth - hPadding) /
  2085. currentPage.width * currentPage.scale;
  2086. var pageHeightScale = (this.container.clientHeight - vPadding) /
  2087. currentPage.height * currentPage.scale;
  2088. switch (value) {
  2089. case 'page-actual':
  2090. scale = 1;
  2091. break;
  2092. case 'page-width':
  2093. scale = pageWidthScale;
  2094. break;
  2095. case 'page-height':
  2096. scale = pageHeightScale;
  2097. break;
  2098. case 'page-fit':
  2099. scale = Math.min(pageWidthScale, pageHeightScale);
  2100. break;
  2101. case 'auto':
  2102. var isLandscape = (currentPage.width > currentPage.height);
  2103. // For pages in landscape mode, fit the page height to the viewer
  2104. // *unless* the page would thus become too wide to fit horizontally.
  2105. var horizontalScale = isLandscape ?
  2106. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  2107. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  2108. break;
  2109. default:
  2110. console.error('pdfViewSetScale: \'' + value +
  2111. '\' is an unknown zoom value.');
  2112. return;
  2113. }
  2114. this._setScaleUpdatePages(scale, value, noScroll, true);
  2115. }
  2116. },
  2117. /**
  2118. * Scrolls page into view.
  2119. * @param {number} pageNumber
  2120. * @param {Array} dest - (optional) original PDF destination array:
  2121. * <page-ref> </XYZ|FitXXX> <args..>
  2122. */
  2123. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  2124. dest) {
  2125. var pageView = this._pages[pageNumber - 1];
  2126. if (this.isInPresentationMode) {
  2127. if (this._currentPageNumber !== pageView.id) {
  2128. // Avoid breaking getVisiblePages in presentation mode.
  2129. this.currentPageNumber = pageView.id;
  2130. return;
  2131. }
  2132. dest = null;
  2133. // Fixes the case when PDF has different page sizes.
  2134. this._setScale(this._currentScaleValue, true);
  2135. }
  2136. if (!dest) {
  2137. scrollIntoView(pageView.div);
  2138. return;
  2139. }
  2140. var x = 0, y = 0;
  2141. var width = 0, height = 0, widthScale, heightScale;
  2142. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  2143. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  2144. pageView.scale / CSS_UNITS;
  2145. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  2146. pageView.scale / CSS_UNITS;
  2147. var scale = 0;
  2148. switch (dest[1].name) {
  2149. case 'XYZ':
  2150. x = dest[2];
  2151. y = dest[3];
  2152. scale = dest[4];
  2153. // If x and/or y coordinates are not supplied, default to
  2154. // _top_ left of the page (not the obvious bottom left,
  2155. // since aligning the bottom of the intended page with the
  2156. // top of the window is rarely helpful).
  2157. x = x !== null ? x : 0;
  2158. y = y !== null ? y : pageHeight;
  2159. break;
  2160. case 'Fit':
  2161. case 'FitB':
  2162. scale = 'page-fit';
  2163. break;
  2164. case 'FitH':
  2165. case 'FitBH':
  2166. y = dest[2];
  2167. scale = 'page-width';
  2168. break;
  2169. case 'FitV':
  2170. case 'FitBV':
  2171. x = dest[2];
  2172. width = pageWidth;
  2173. height = pageHeight;
  2174. scale = 'page-height';
  2175. break;
  2176. case 'FitR':
  2177. x = dest[2];
  2178. y = dest[3];
  2179. width = dest[4] - x;
  2180. height = dest[5] - y;
  2181. var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
  2182. var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
  2183. widthScale = (this.container.clientWidth - hPadding) /
  2184. width / CSS_UNITS;
  2185. heightScale = (this.container.clientHeight - vPadding) /
  2186. height / CSS_UNITS;
  2187. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  2188. break;
  2189. default:
  2190. return;
  2191. }
  2192. if (scale && scale !== this._currentScale) {
  2193. this.currentScaleValue = scale;
  2194. } else if (this._currentScale === UNKNOWN_SCALE) {
  2195. this.currentScaleValue = DEFAULT_SCALE_VALUE;
  2196. }
  2197. if (scale === 'page-fit' && !dest[4]) {
  2198. scrollIntoView(pageView.div);
  2199. return;
  2200. }
  2201. var boundingRect = [
  2202. pageView.viewport.convertToViewportPoint(x, y),
  2203. pageView.viewport.convertToViewportPoint(x + width, y + height)
  2204. ];
  2205. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  2206. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  2207. scrollIntoView(pageView.div, { left: left, top: top });
  2208. },
  2209. _updateLocation: function (firstPage) {
  2210. var currentScale = this._currentScale;
  2211. var currentScaleValue = this._currentScaleValue;
  2212. var normalizedScaleValue =
  2213. parseFloat(currentScaleValue) === currentScale ?
  2214. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  2215. var pageNumber = firstPage.id;
  2216. var pdfOpenParams = '#page=' + pageNumber;
  2217. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  2218. var currentPageView = this._pages[pageNumber - 1];
  2219. var container = this.container;
  2220. var topLeft = currentPageView.getPagePoint(
  2221. (container.scrollLeft - firstPage.x),
  2222. (container.scrollTop - firstPage.y));
  2223. var intLeft = Math.round(topLeft[0]);
  2224. var intTop = Math.round(topLeft[1]);
  2225. pdfOpenParams += ',' + intLeft + ',' + intTop;
  2226. this._location = {
  2227. pageNumber: pageNumber,
  2228. scale: normalizedScaleValue,
  2229. top: intTop,
  2230. left: intLeft,
  2231. pdfOpenParams: pdfOpenParams
  2232. };
  2233. },
  2234. update: function PDFViewer_update() {
  2235. var visible = this._getVisiblePages();
  2236. var visiblePages = visible.views;
  2237. if (visiblePages.length === 0) {
  2238. return;
  2239. }
  2240. this.updateInProgress = true;
  2241. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  2242. 2 * visiblePages.length + 1);
  2243. this._buffer.resize(suggestedCacheSize);
  2244. this.renderingQueue.renderHighestPriority(visible);
  2245. var currentId = this._currentPageNumber;
  2246. var firstPage = visible.first;
  2247. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  2248. i < ii; ++i) {
  2249. var page = visiblePages[i];
  2250. if (page.percent < 100) {
  2251. break;
  2252. }
  2253. if (page.id === currentId) {
  2254. stillFullyVisible = true;
  2255. break;
  2256. }
  2257. }
  2258. if (!stillFullyVisible) {
  2259. currentId = visiblePages[0].id;
  2260. }
  2261. if (!this.isInPresentationMode) {
  2262. this.currentPageNumber = currentId;
  2263. }
  2264. this._updateLocation(firstPage);
  2265. this.updateInProgress = false;
  2266. var event = document.createEvent('UIEvents');
  2267. event.initUIEvent('updateviewarea', true, true, window, 0);
  2268. event.location = this._location;
  2269. this.container.dispatchEvent(event);
  2270. },
  2271. containsElement: function (element) {
  2272. return this.container.contains(element);
  2273. },
  2274. focus: function () {
  2275. this.container.focus();
  2276. },
  2277. get isInPresentationMode() {
  2278. return this.presentationModeState === PresentationModeState.FULLSCREEN;
  2279. },
  2280. get isChangingPresentationMode() {
  2281. return this.PresentationModeState === PresentationModeState.CHANGING;
  2282. },
  2283. get isHorizontalScrollbarEnabled() {
  2284. return (this.isInPresentationMode ?
  2285. false : (this.container.scrollWidth > this.container.clientWidth));
  2286. },
  2287. _getVisiblePages: function () {
  2288. if (!this.isInPresentationMode) {
  2289. return getVisibleElements(this.container, this._pages, true);
  2290. } else {
  2291. // The algorithm in getVisibleElements doesn't work in all browsers and
  2292. // configurations when presentation mode is active.
  2293. var visible = [];
  2294. var currentPage = this._pages[this._currentPageNumber - 1];
  2295. visible.push({ id: currentPage.id, view: currentPage });
  2296. return { first: currentPage, last: currentPage, views: visible };
  2297. }
  2298. },
  2299. cleanup: function () {
  2300. for (var i = 0, ii = this._pages.length; i < ii; i++) {
  2301. if (this._pages[i] &&
  2302. this._pages[i].renderingState !== RenderingStates.FINISHED) {
  2303. this._pages[i].reset();
  2304. }
  2305. }
  2306. },
  2307. /**
  2308. * @param {PDFPageView} pageView
  2309. * @returns {PDFPage}
  2310. * @private
  2311. */
  2312. _ensurePdfPageLoaded: function (pageView) {
  2313. if (pageView.pdfPage) {
  2314. return Promise.resolve(pageView.pdfPage);
  2315. }
  2316. var pageNumber = pageView.id;
  2317. if (this._pagesRequests[pageNumber]) {
  2318. return this._pagesRequests[pageNumber];
  2319. }
  2320. var promise = this.pdfDocument.getPage(pageNumber).then(
  2321. function (pdfPage) {
  2322. pageView.setPdfPage(pdfPage);
  2323. this._pagesRequests[pageNumber] = null;
  2324. return pdfPage;
  2325. }.bind(this));
  2326. this._pagesRequests[pageNumber] = promise;
  2327. return promise;
  2328. },
  2329. forceRendering: function (currentlyVisiblePages) {
  2330. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  2331. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  2332. this._pages,
  2333. this.scroll.down);
  2334. if (pageView) {
  2335. this._ensurePdfPageLoaded(pageView).then(function () {
  2336. this.renderingQueue.renderView(pageView);
  2337. }.bind(this));
  2338. return true;
  2339. }
  2340. return false;
  2341. },
  2342. getPageTextContent: function (pageIndex) {
  2343. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  2344. return page.getTextContent();
  2345. });
  2346. },
  2347. /**
  2348. * @param {HTMLDivElement} textLayerDiv
  2349. * @param {number} pageIndex
  2350. * @param {PageViewport} viewport
  2351. * @returns {TextLayerBuilder}
  2352. */
  2353. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  2354. return new TextLayerBuilder({
  2355. textLayerDiv: textLayerDiv,
  2356. pageIndex: pageIndex,
  2357. viewport: viewport,
  2358. findController: this.isInPresentationMode ? null : this.findController
  2359. });
  2360. },
  2361. /**
  2362. * @param {HTMLDivElement} pageDiv
  2363. * @param {PDFPage} pdfPage
  2364. * @returns {AnnotationsLayerBuilder}
  2365. */
  2366. createAnnotationsLayerBuilder: function (pageDiv, pdfPage) {
  2367. return new AnnotationsLayerBuilder({
  2368. pageDiv: pageDiv,
  2369. pdfPage: pdfPage,
  2370. linkService: this.linkService
  2371. });
  2372. },
  2373. setFindController: function (findController) {
  2374. this.findController = findController;
  2375. },
  2376. };
  2377. return PDFViewer;
  2378. })();
  2379. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  2380. function SimpleLinkService() {}
  2381. SimpleLinkService.prototype = {
  2382. /**
  2383. * @returns {number}
  2384. */
  2385. get page() {
  2386. return 0;
  2387. },
  2388. /**
  2389. * @param {number} value
  2390. */
  2391. set page(value) {},
  2392. /**
  2393. * @param dest - The PDF destination object.
  2394. */
  2395. navigateTo: function (dest) {},
  2396. /**
  2397. * @param dest - The PDF destination object.
  2398. * @returns {string} The hyperlink to the PDF object.
  2399. */
  2400. getDestinationHash: function (dest) {
  2401. return '#';
  2402. },
  2403. /**
  2404. * @param hash - The PDF parameters/hash.
  2405. * @returns {string} The hyperlink to the PDF object.
  2406. */
  2407. getAnchorUrl: function (hash) {
  2408. return '#';
  2409. },
  2410. /**
  2411. * @param {string} hash
  2412. */
  2413. setHash: function (hash) {},
  2414. /**
  2415. * @param {string} action
  2416. */
  2417. executeNamedAction: function (action) {},
  2418. /**
  2419. * @param {number} pageNum - page number.
  2420. * @param {Object} pageRef - reference to the page.
  2421. */
  2422. cachePageRef: function (pageNum, pageRef) {}
  2423. };
  2424. return SimpleLinkService;
  2425. })();
  2426. var PDFHistory = (function () {
  2427. function PDFHistory(options) {
  2428. this.linkService = options.linkService;
  2429. this.initialized = false;
  2430. this.initialDestination = null;
  2431. this.initialBookmark = null;
  2432. }
  2433. PDFHistory.prototype = {
  2434. /**
  2435. * @param {string} fingerprint
  2436. * @param {IPDFLinkService} linkService
  2437. */
  2438. initialize: function pdfHistoryInitialize(fingerprint) {
  2439. this.initialized = true;
  2440. this.reInitialized = false;
  2441. this.allowHashChange = true;
  2442. this.historyUnlocked = true;
  2443. this.isViewerInPresentationMode = false;
  2444. this.previousHash = window.location.hash.substring(1);
  2445. this.currentBookmark = '';
  2446. this.currentPage = 0;
  2447. this.updatePreviousBookmark = false;
  2448. this.previousBookmark = '';
  2449. this.previousPage = 0;
  2450. this.nextHashParam = '';
  2451. this.fingerprint = fingerprint;
  2452. this.currentUid = this.uid = 0;
  2453. this.current = {};
  2454. var state = window.history.state;
  2455. if (this._isStateObjectDefined(state)) {
  2456. // This corresponds to navigating back to the document
  2457. // from another page in the browser history.
  2458. if (state.target.dest) {
  2459. this.initialDestination = state.target.dest;
  2460. } else {
  2461. this.initialBookmark = state.target.hash;
  2462. }
  2463. this.currentUid = state.uid;
  2464. this.uid = state.uid + 1;
  2465. this.current = state.target;
  2466. } else {
  2467. // This corresponds to the loading of a new document.
  2468. if (state && state.fingerprint &&
  2469. this.fingerprint !== state.fingerprint) {
  2470. // Reinitialize the browsing history when a new document
  2471. // is opened in the web viewer.
  2472. this.reInitialized = true;
  2473. }
  2474. this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
  2475. }
  2476. var self = this;
  2477. window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
  2478. if (!self.historyUnlocked) {
  2479. return;
  2480. }
  2481. if (evt.state) {
  2482. // Move back/forward in the history.
  2483. self._goTo(evt.state);
  2484. return;
  2485. }
  2486. // If the state is not set, then the user tried to navigate to a
  2487. // different hash by manually editing the URL and pressing Enter, or by
  2488. // clicking on an in-page link (e.g. the "current view" link).
  2489. // Save the current view state to the browser history.
  2490. // Note: In Firefox, history.null could also be null after an in-page
  2491. // navigation to the same URL, and without dispatching the popstate
  2492. // event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
  2493. if (self.uid === 0) {
  2494. // Replace the previous state if it was not explicitly set.
  2495. var previousParams = (self.previousHash && self.currentBookmark &&
  2496. self.previousHash !== self.currentBookmark) ?
  2497. {hash: self.currentBookmark, page: self.currentPage} :
  2498. {page: 1};
  2499. replacePreviousHistoryState(previousParams, function() {
  2500. updateHistoryWithCurrentHash();
  2501. });
  2502. } else {
  2503. updateHistoryWithCurrentHash();
  2504. }
  2505. }, false);
  2506. function updateHistoryWithCurrentHash() {
  2507. self.previousHash = window.location.hash.slice(1);
  2508. self._pushToHistory({hash: self.previousHash}, false, true);
  2509. self._updatePreviousBookmark();
  2510. }
  2511. function replacePreviousHistoryState(params, callback) {
  2512. // To modify the previous history entry, the following happens:
  2513. // 1. history.back()
  2514. // 2. _pushToHistory, which calls history.replaceState( ... )
  2515. // 3. history.forward()
  2516. // Because a navigation via the history API does not immediately update
  2517. // the history state, the popstate event is used for synchronization.
  2518. self.historyUnlocked = false;
  2519. // Suppress the hashchange event to avoid side effects caused by
  2520. // navigating back and forward.
  2521. self.allowHashChange = false;
  2522. window.addEventListener('popstate', rewriteHistoryAfterBack);
  2523. history.back();
  2524. function rewriteHistoryAfterBack() {
  2525. window.removeEventListener('popstate', rewriteHistoryAfterBack);
  2526. window.addEventListener('popstate', rewriteHistoryAfterForward);
  2527. self._pushToHistory(params, false, true);
  2528. history.forward();
  2529. }
  2530. function rewriteHistoryAfterForward() {
  2531. window.removeEventListener('popstate', rewriteHistoryAfterForward);
  2532. self.allowHashChange = true;
  2533. self.historyUnlocked = true;
  2534. callback();
  2535. }
  2536. }
  2537. function pdfHistoryBeforeUnload() {
  2538. var previousParams = self._getPreviousParams(null, true);
  2539. if (previousParams) {
  2540. var replacePrevious = (!self.current.dest &&
  2541. self.current.hash !== self.previousHash);
  2542. self._pushToHistory(previousParams, false, replacePrevious);
  2543. self._updatePreviousBookmark();
  2544. }
  2545. // Remove the event listener when navigating away from the document,
  2546. // since 'beforeunload' prevents Firefox from caching the document.
  2547. window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
  2548. false);
  2549. }
  2550. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2551. window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
  2552. // If the entire viewer (including the PDF file) is cached in
  2553. // the browser, we need to reattach the 'beforeunload' event listener
  2554. // since the 'DOMContentLoaded' event is not fired on 'pageshow'.
  2555. window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
  2556. }, false);
  2557. window.addEventListener('presentationmodechanged', function(e) {
  2558. self.isViewerInPresentationMode = !!e.detail.active;
  2559. });
  2560. },
  2561. clearHistoryState: function pdfHistory_clearHistoryState() {
  2562. this._pushOrReplaceState(null, true);
  2563. },
  2564. _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
  2565. return (state && state.uid >= 0 &&
  2566. state.fingerprint && this.fingerprint === state.fingerprint &&
  2567. state.target && state.target.hash) ? true : false;
  2568. },
  2569. _pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
  2570. replace) {
  2571. if (replace) {
  2572. window.history.replaceState(stateObj, '');
  2573. } else {
  2574. window.history.pushState(stateObj, '');
  2575. }
  2576. },
  2577. get isHashChangeUnlocked() {
  2578. if (!this.initialized) {
  2579. return true;
  2580. }
  2581. return this.allowHashChange;
  2582. },
  2583. _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
  2584. if (this.updatePreviousBookmark &&
  2585. this.currentBookmark && this.currentPage) {
  2586. this.previousBookmark = this.currentBookmark;
  2587. this.previousPage = this.currentPage;
  2588. this.updatePreviousBookmark = false;
  2589. }
  2590. },
  2591. updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
  2592. pageNum) {
  2593. if (this.initialized) {
  2594. this.currentBookmark = bookmark.substring(1);
  2595. this.currentPage = pageNum | 0;
  2596. this._updatePreviousBookmark();
  2597. }
  2598. },
  2599. updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
  2600. if (this.initialized) {
  2601. this.nextHashParam = param;
  2602. }
  2603. },
  2604. push: function pdfHistoryPush(params, isInitialBookmark) {
  2605. if (!(this.initialized && this.historyUnlocked)) {
  2606. return;
  2607. }
  2608. if (params.dest && !params.hash) {
  2609. params.hash = (this.current.hash && this.current.dest &&
  2610. this.current.dest === params.dest) ?
  2611. this.current.hash :
  2612. this.linkService.getDestinationHash(params.dest).split('#')[1];
  2613. }
  2614. if (params.page) {
  2615. params.page |= 0;
  2616. }
  2617. if (isInitialBookmark) {
  2618. var target = window.history.state.target;
  2619. if (!target) {
  2620. // Invoked when the user specifies an initial bookmark,
  2621. // thus setting initialBookmark, when the document is loaded.
  2622. this._pushToHistory(params, false);
  2623. this.previousHash = window.location.hash.substring(1);
  2624. }
  2625. this.updatePreviousBookmark = this.nextHashParam ? false : true;
  2626. if (target) {
  2627. // If the current document is reloaded,
  2628. // avoid creating duplicate entries in the history.
  2629. this._updatePreviousBookmark();
  2630. }
  2631. return;
  2632. }
  2633. if (this.nextHashParam) {
  2634. if (this.nextHashParam === params.hash) {
  2635. this.nextHashParam = null;
  2636. this.updatePreviousBookmark = true;
  2637. return;
  2638. } else {
  2639. this.nextHashParam = null;
  2640. }
  2641. }
  2642. if (params.hash) {
  2643. if (this.current.hash) {
  2644. if (this.current.hash !== params.hash) {
  2645. this._pushToHistory(params, true);
  2646. } else {
  2647. if (!this.current.page && params.page) {
  2648. this._pushToHistory(params, false, true);
  2649. }
  2650. this.updatePreviousBookmark = true;
  2651. }
  2652. } else {
  2653. this._pushToHistory(params, true);
  2654. }
  2655. } else if (this.current.page && params.page &&
  2656. this.current.page !== params.page) {
  2657. this._pushToHistory(params, true);
  2658. }
  2659. },
  2660. _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
  2661. beforeUnload) {
  2662. if (!(this.currentBookmark && this.currentPage)) {
  2663. return null;
  2664. } else if (this.updatePreviousBookmark) {
  2665. this.updatePreviousBookmark = false;
  2666. }
  2667. if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
  2668. // Prevent the history from getting stuck in the current state,
  2669. // effectively preventing the user from going back/forward in
  2670. // the history.
  2671. //
  2672. // This happens if the current position in the document didn't change
  2673. // when the history was previously updated. The reasons for this are
  2674. // either:
  2675. // 1. The current zoom value is such that the document does not need to,
  2676. // or cannot, be scrolled to display the destination.
  2677. // 2. The previous destination is broken, and doesn't actally point to a
  2678. // position within the document.
  2679. // (This is either due to a bad PDF generator, or the user making a
  2680. // mistake when entering a destination in the hash parameters.)
  2681. return null;
  2682. }
  2683. if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
  2684. if (this.previousBookmark === this.currentBookmark) {
  2685. return null;
  2686. }
  2687. } else if (this.current.page || onlyCheckPage) {
  2688. if (this.previousPage === this.currentPage) {
  2689. return null;
  2690. }
  2691. } else {
  2692. return null;
  2693. }
  2694. var params = {hash: this.currentBookmark, page: this.currentPage};
  2695. if (this.isViewerInPresentationMode) {
  2696. params.hash = null;
  2697. }
  2698. return params;
  2699. },
  2700. _stateObj: function pdfHistory_stateObj(params) {
  2701. return {fingerprint: this.fingerprint, uid: this.uid, target: params};
  2702. },
  2703. _pushToHistory: function pdfHistory_pushToHistory(params,
  2704. addPrevious, overwrite) {
  2705. if (!this.initialized) {
  2706. return;
  2707. }
  2708. if (!params.hash && params.page) {
  2709. params.hash = ('page=' + params.page);
  2710. }
  2711. if (addPrevious && !overwrite) {
  2712. var previousParams = this._getPreviousParams();
  2713. if (previousParams) {
  2714. var replacePrevious = (!this.current.dest &&
  2715. this.current.hash !== this.previousHash);
  2716. this._pushToHistory(previousParams, false, replacePrevious);
  2717. }
  2718. }
  2719. this._pushOrReplaceState(this._stateObj(params),
  2720. (overwrite || this.uid === 0));
  2721. this.currentUid = this.uid++;
  2722. this.current = params;
  2723. this.updatePreviousBookmark = true;
  2724. },
  2725. _goTo: function pdfHistory_goTo(state) {
  2726. if (!(this.initialized && this.historyUnlocked &&
  2727. this._isStateObjectDefined(state))) {
  2728. return;
  2729. }
  2730. if (!this.reInitialized && state.uid < this.currentUid) {
  2731. var previousParams = this._getPreviousParams(true);
  2732. if (previousParams) {
  2733. this._pushToHistory(this.current, false);
  2734. this._pushToHistory(previousParams, false);
  2735. this.currentUid = state.uid;
  2736. window.history.back();
  2737. return;
  2738. }
  2739. }
  2740. this.historyUnlocked = false;
  2741. if (state.target.dest) {
  2742. this.linkService.navigateTo(state.target.dest);
  2743. } else {
  2744. this.linkService.setHash(state.target.hash);
  2745. }
  2746. this.currentUid = state.uid;
  2747. if (state.uid > this.uid) {
  2748. this.uid = state.uid;
  2749. }
  2750. this.current = state.target;
  2751. this.updatePreviousBookmark = true;
  2752. var currentHash = window.location.hash.substring(1);
  2753. if (this.previousHash !== currentHash) {
  2754. this.allowHashChange = false;
  2755. }
  2756. this.previousHash = currentHash;
  2757. this.historyUnlocked = true;
  2758. },
  2759. back: function pdfHistoryBack() {
  2760. this.go(-1);
  2761. },
  2762. forward: function pdfHistoryForward() {
  2763. this.go(1);
  2764. },
  2765. go: function pdfHistoryGo(direction) {
  2766. if (this.initialized && this.historyUnlocked) {
  2767. var state = window.history.state;
  2768. if (direction === -1 && state && state.uid > 0) {
  2769. window.history.back();
  2770. } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
  2771. window.history.forward();
  2772. }
  2773. }
  2774. }
  2775. };
  2776. return PDFHistory;
  2777. })();
  2778. PDFJS.PDFViewer = PDFViewer;
  2779. PDFJS.PDFPageView = PDFPageView;
  2780. PDFJS.PDFLinkService = PDFLinkService;
  2781. PDFJS.TextLayerBuilder = TextLayerBuilder;
  2782. PDFJS.DefaultTextLayerFactory = DefaultTextLayerFactory;
  2783. PDFJS.AnnotationsLayerBuilder = AnnotationsLayerBuilder;
  2784. PDFJS.DefaultAnnotationsLayerFactory = DefaultAnnotationsLayerFactory;
  2785. PDFJS.PDFHistory = PDFHistory;
  2786. PDFJS.getFileName = getFileName;
  2787. PDFJS.ProgressBar = ProgressBar;
  2788. }).call((typeof window === 'undefined') ? this : window);