pdf_viewer.js 101 KB

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