pdf_viewer.js 100 KB

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