pdf_viewer.js 98 KB

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