pdf_viewer.js 102 KB

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