pdf_viewer.js 98 KB

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