pdf_viewer.js 103 KB

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