pdf_viewer.js 97 KB

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