pdf_viewer.js 97 KB

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