pdf_viewer.js 97 KB

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