pdf_viewer.js 96 KB

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