pdf_viewer.js 96 KB

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