2
0

pdf_viewer.js 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  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 */
  19. // Initializing PDFJS global object (if still undefined)
  20. if (typeof PDFJS === 'undefined') {
  21. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  22. }
  23. (function pdfViewerWrapper() {
  24. 'use strict';
  25. var CSS_UNITS = 96.0 / 72.0;
  26. var DEFAULT_SCALE = 'auto';
  27. var UNKNOWN_SCALE = 0;
  28. var MAX_AUTO_SCALE = 1.25;
  29. var SCROLLBAR_PADDING = 40;
  30. var VERTICAL_PADDING = 5;
  31. var DEFAULT_CACHE_SIZE = 10;
  32. // optimised CSS custom property getter/setter
  33. var CustomStyle = (function CustomStyleClosure() {
  34. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  35. // animate-css-transforms-firefox-webkit.html
  36. // in some versions of IE9 it is critical that ms appear in this list
  37. // before Moz
  38. var prefixes = ['ms', 'Moz', 'Webkit', 'O'];
  39. var _cache = {};
  40. function CustomStyle() {}
  41. CustomStyle.getProp = function get(propName, element) {
  42. // check cache only when no element is given
  43. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  44. return _cache[propName];
  45. }
  46. element = element || document.documentElement;
  47. var style = element.style, prefixed, uPropName;
  48. // test standard property first
  49. if (typeof style[propName] === 'string') {
  50. return (_cache[propName] = propName);
  51. }
  52. // capitalize
  53. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  54. // test vendor specific properties
  55. for (var i = 0, l = prefixes.length; i < l; i++) {
  56. prefixed = prefixes[i] + uPropName;
  57. if (typeof style[prefixed] === 'string') {
  58. return (_cache[propName] = prefixed);
  59. }
  60. }
  61. //if all fails then set to undefined
  62. return (_cache[propName] = 'undefined');
  63. };
  64. CustomStyle.setProp = function set(propName, element, str) {
  65. var prop = this.getProp(propName);
  66. if (prop !== 'undefined') {
  67. element.style[prop] = str;
  68. }
  69. };
  70. return CustomStyle;
  71. })();
  72. function getFileName(url) {
  73. var anchor = url.indexOf('#');
  74. var query = url.indexOf('?');
  75. var end = Math.min(
  76. anchor > 0 ? anchor : url.length,
  77. query > 0 ? query : url.length);
  78. return url.substring(url.lastIndexOf('/', end) + 1, end);
  79. }
  80. /**
  81. * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
  82. * @return {Object} The object with horizontal (sx) and vertical (sy)
  83. scales. The scaled property is set to false if scaling is
  84. not required, true otherwise.
  85. */
  86. function getOutputScale(ctx) {
  87. var devicePixelRatio = window.devicePixelRatio || 1;
  88. var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
  89. ctx.mozBackingStorePixelRatio ||
  90. ctx.msBackingStorePixelRatio ||
  91. ctx.oBackingStorePixelRatio ||
  92. ctx.backingStorePixelRatio || 1;
  93. var pixelRatio = devicePixelRatio / backingStoreRatio;
  94. return {
  95. sx: pixelRatio,
  96. sy: pixelRatio,
  97. scaled: pixelRatio !== 1
  98. };
  99. }
  100. /**
  101. * Scrolls specified element into view of its parent.
  102. * element {Object} The element to be visible.
  103. * spot {Object} An object with optional top and left properties,
  104. * specifying the offset from the top left edge.
  105. */
  106. function scrollIntoView(element, spot) {
  107. // Assuming offsetParent is available (it's not available when viewer is in
  108. // hidden iframe or object). We have to scroll: if the offsetParent is not set
  109. // producing the error. See also animationStartedClosure.
  110. var parent = element.offsetParent;
  111. var offsetY = element.offsetTop + element.clientTop;
  112. var offsetX = element.offsetLeft + element.clientLeft;
  113. if (!parent) {
  114. console.error('offsetParent is not set -- cannot scroll');
  115. return;
  116. }
  117. while (parent.clientHeight === parent.scrollHeight) {
  118. if (parent.dataset._scaleY) {
  119. offsetY /= parent.dataset._scaleY;
  120. offsetX /= parent.dataset._scaleX;
  121. }
  122. offsetY += parent.offsetTop;
  123. offsetX += parent.offsetLeft;
  124. parent = parent.offsetParent;
  125. if (!parent) {
  126. return; // no need to scroll
  127. }
  128. }
  129. if (spot) {
  130. if (spot.top !== undefined) {
  131. offsetY += spot.top;
  132. }
  133. if (spot.left !== undefined) {
  134. offsetX += spot.left;
  135. parent.scrollLeft = offsetX;
  136. }
  137. }
  138. parent.scrollTop = offsetY;
  139. }
  140. /**
  141. * Helper function to start monitoring the scroll event and converting them into
  142. * PDF.js friendly one: with scroll debounce and scroll direction.
  143. */
  144. function watchScroll(viewAreaElement, callback) {
  145. var debounceScroll = function debounceScroll(evt) {
  146. if (rAF) {
  147. return;
  148. }
  149. // schedule an invocation of scroll for next animation frame.
  150. rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
  151. rAF = null;
  152. var currentY = viewAreaElement.scrollTop;
  153. var lastY = state.lastY;
  154. if (currentY > lastY) {
  155. state.down = true;
  156. } else if (currentY < lastY) {
  157. state.down = false;
  158. }
  159. state.lastY = currentY;
  160. // else do nothing and use previous value
  161. callback(state);
  162. });
  163. };
  164. var state = {
  165. down: true,
  166. lastY: viewAreaElement.scrollTop,
  167. _eventHandler: debounceScroll
  168. };
  169. var rAF = null;
  170. viewAreaElement.addEventListener('scroll', debounceScroll, true);
  171. return state;
  172. }
  173. /**
  174. * Generic helper to find out what elements are visible within a scroll pane.
  175. */
  176. function getVisibleElements(scrollEl, views, sortByVisibility) {
  177. var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
  178. var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
  179. var visible = [], view;
  180. var currentHeight, viewHeight, hiddenHeight, percentHeight;
  181. var currentWidth, viewWidth;
  182. for (var i = 0, ii = views.length; i < ii; ++i) {
  183. view = views[i];
  184. currentHeight = view.el.offsetTop + view.el.clientTop;
  185. viewHeight = view.el.clientHeight;
  186. if ((currentHeight + viewHeight) < top) {
  187. continue;
  188. }
  189. if (currentHeight > bottom) {
  190. break;
  191. }
  192. currentWidth = view.el.offsetLeft + view.el.clientLeft;
  193. viewWidth = view.el.clientWidth;
  194. if ((currentWidth + viewWidth) < left || currentWidth > right) {
  195. continue;
  196. }
  197. hiddenHeight = Math.max(0, top - currentHeight) +
  198. Math.max(0, currentHeight + viewHeight - bottom);
  199. percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
  200. visible.push({ id: view.id, x: currentWidth, y: currentHeight,
  201. view: view, percent: percentHeight });
  202. }
  203. var first = visible[0];
  204. var last = visible[visible.length - 1];
  205. if (sortByVisibility) {
  206. visible.sort(function(a, b) {
  207. var pc = a.percent - b.percent;
  208. if (Math.abs(pc) > 0.001) {
  209. return -pc;
  210. }
  211. return a.id - b.id; // ensure stability
  212. });
  213. }
  214. return {first: first, last: last, views: visible};
  215. }
  216. /**
  217. * Event handler to suppress context menu.
  218. */
  219. function noContextMenuHandler(e) {
  220. e.preventDefault();
  221. }
  222. /**
  223. * Returns the filename or guessed filename from the url (see issue 3455).
  224. * url {String} The original PDF location.
  225. * @return {String} Guessed PDF file name.
  226. */
  227. function getPDFFileNameFromURL(url) {
  228. var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  229. // SCHEME HOST 1.PATH 2.QUERY 3.REF
  230. // Pattern to get last matching NAME.pdf
  231. var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  232. var splitURI = reURI.exec(url);
  233. var suggestedFilename = reFilename.exec(splitURI[1]) ||
  234. reFilename.exec(splitURI[2]) ||
  235. reFilename.exec(splitURI[3]);
  236. if (suggestedFilename) {
  237. suggestedFilename = suggestedFilename[0];
  238. if (suggestedFilename.indexOf('%') !== -1) {
  239. // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
  240. try {
  241. suggestedFilename =
  242. reFilename.exec(decodeURIComponent(suggestedFilename))[0];
  243. } catch(e) { // Possible (extremely rare) errors:
  244. // URIError "Malformed URI", e.g. for "%AA.pdf"
  245. // TypeError "null has no properties", e.g. for "%2F.pdf"
  246. }
  247. }
  248. }
  249. return suggestedFilename || 'document.pdf';
  250. }
  251. var ProgressBar = (function ProgressBarClosure() {
  252. function clamp(v, min, max) {
  253. return Math.min(Math.max(v, min), max);
  254. }
  255. function ProgressBar(id, opts) {
  256. // Fetch the sub-elements for later.
  257. this.div = document.querySelector(id + ' .progress');
  258. // Get the loading bar element, so it can be resized to fit the viewer.
  259. this.bar = this.div.parentNode;
  260. // Get options, with sensible defaults.
  261. this.height = opts.height || 100;
  262. this.width = opts.width || 100;
  263. this.units = opts.units || '%';
  264. // Initialize heights.
  265. this.div.style.height = this.height + this.units;
  266. this.percent = 0;
  267. }
  268. ProgressBar.prototype = {
  269. updateBar: function ProgressBar_updateBar() {
  270. if (this._indeterminate) {
  271. this.div.classList.add('indeterminate');
  272. this.div.style.width = this.width + this.units;
  273. return;
  274. }
  275. this.div.classList.remove('indeterminate');
  276. var progressSize = this.width * this._percent / 100;
  277. this.div.style.width = progressSize + this.units;
  278. },
  279. get percent() {
  280. return this._percent;
  281. },
  282. set percent(val) {
  283. this._indeterminate = isNaN(val);
  284. this._percent = clamp(val, 0, 100);
  285. this.updateBar();
  286. },
  287. setWidth: function ProgressBar_setWidth(viewer) {
  288. if (viewer) {
  289. var container = viewer.parentNode;
  290. var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
  291. if (scrollbarWidth > 0) {
  292. this.bar.setAttribute('style', 'width: calc(100% - ' +
  293. scrollbarWidth + 'px);');
  294. }
  295. }
  296. },
  297. hide: function ProgressBar_hide() {
  298. this.bar.classList.add('hidden');
  299. this.bar.removeAttribute('style');
  300. }
  301. };
  302. return ProgressBar;
  303. })();
  304. var Cache = function cacheCache(size) {
  305. var data = [];
  306. this.push = function cachePush(view) {
  307. var i = data.indexOf(view);
  308. if (i >= 0) {
  309. data.splice(i, 1);
  310. }
  311. data.push(view);
  312. if (data.length > size) {
  313. data.shift().destroy();
  314. }
  315. };
  316. this.resize = function (newSize) {
  317. size = newSize;
  318. while (data.length > size) {
  319. data.shift().destroy();
  320. }
  321. };
  322. };
  323. var PresentationModeState = {
  324. UNKNOWN: 0,
  325. NORMAL: 1,
  326. CHANGING: 2,
  327. FULLSCREEN: 3,
  328. };
  329. var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
  330. var CLEANUP_TIMEOUT = 30000;
  331. var RenderingStates = {
  332. INITIAL: 0,
  333. RUNNING: 1,
  334. PAUSED: 2,
  335. FINISHED: 3
  336. };
  337. /**
  338. * Controls rendering of the views for pages and thumbnails.
  339. * @class
  340. */
  341. var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
  342. /**
  343. * @constructs
  344. */
  345. function PDFRenderingQueue() {
  346. this.pdfViewer = null;
  347. this.pdfThumbnailViewer = null;
  348. this.onIdle = null;
  349. this.highestPriorityPage = null;
  350. this.idleTimeout = null;
  351. this.printing = false;
  352. this.isThumbnailViewEnabled = false;
  353. }
  354. PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
  355. /**
  356. * @param {PDFViewer} pdfViewer
  357. */
  358. setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
  359. this.pdfViewer = pdfViewer;
  360. },
  361. /**
  362. * @param {PDFThumbnailViewer} pdfThumbnailViewer
  363. */
  364. setThumbnailViewer:
  365. function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
  366. this.pdfThumbnailViewer = pdfThumbnailViewer;
  367. },
  368. /**
  369. * @param {IRenderableView} view
  370. * @returns {boolean}
  371. */
  372. isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
  373. return this.highestPriorityPage === view.renderingId;
  374. },
  375. renderHighestPriority: function
  376. PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
  377. if (this.idleTimeout) {
  378. clearTimeout(this.idleTimeout);
  379. this.idleTimeout = null;
  380. }
  381. // Pages have a higher priority than thumbnails, so check them first.
  382. if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
  383. return;
  384. }
  385. // No pages needed rendering so check thumbnails.
  386. if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
  387. if (this.pdfThumbnailViewer.forceRendering()) {
  388. return;
  389. }
  390. }
  391. if (this.printing) {
  392. // If printing is currently ongoing do not reschedule cleanup.
  393. return;
  394. }
  395. if (this.onIdle) {
  396. this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
  397. }
  398. },
  399. getHighestPriority: function
  400. PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
  401. // The state has changed figure out which page has the highest priority to
  402. // render next (if any).
  403. // Priority:
  404. // 1 visible pages
  405. // 2 if last scrolled down page after the visible pages
  406. // 2 if last scrolled up page before the visible pages
  407. var visibleViews = visible.views;
  408. var numVisible = visibleViews.length;
  409. if (numVisible === 0) {
  410. return false;
  411. }
  412. for (var i = 0; i < numVisible; ++i) {
  413. var view = visibleViews[i].view;
  414. if (!this.isViewFinished(view)) {
  415. return view;
  416. }
  417. }
  418. // All the visible views have rendered, try to render next/previous pages.
  419. if (scrolledDown) {
  420. var nextPageIndex = visible.last.id;
  421. // ID's start at 1 so no need to add 1.
  422. if (views[nextPageIndex] &&
  423. !this.isViewFinished(views[nextPageIndex])) {
  424. return views[nextPageIndex];
  425. }
  426. } else {
  427. var previousPageIndex = visible.first.id - 2;
  428. if (views[previousPageIndex] &&
  429. !this.isViewFinished(views[previousPageIndex])) {
  430. return views[previousPageIndex];
  431. }
  432. }
  433. // Everything that needs to be rendered has been.
  434. return null;
  435. },
  436. /**
  437. * @param {IRenderableView} view
  438. * @returns {boolean}
  439. */
  440. isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
  441. return view.renderingState === RenderingStates.FINISHED;
  442. },
  443. /**
  444. * Render a page or thumbnail view. This calls the appropriate function
  445. * based on the views state. If the view is already rendered it will return
  446. * false.
  447. * @param {IRenderableView} view
  448. */
  449. renderView: function PDFRenderingQueue_renderView(view) {
  450. var state = view.renderingState;
  451. switch (state) {
  452. case RenderingStates.FINISHED:
  453. return false;
  454. case RenderingStates.PAUSED:
  455. this.highestPriorityPage = view.renderingId;
  456. view.resume();
  457. break;
  458. case RenderingStates.RUNNING:
  459. this.highestPriorityPage = view.renderingId;
  460. break;
  461. case RenderingStates.INITIAL:
  462. this.highestPriorityPage = view.renderingId;
  463. view.draw(this.renderHighestPriority.bind(this));
  464. break;
  465. }
  466. return true;
  467. },
  468. };
  469. return PDFRenderingQueue;
  470. })();
  471. /**
  472. * @constructor
  473. * @param {HTMLDivElement} container - The viewer element.
  474. * @param {number} id - The page unique ID (normally its number).
  475. * @param {number} scale - The page scale display.
  476. * @param {PageViewport} defaultViewport - The page viewport.
  477. * @param {IPDFLinkService} linkService - The navigation/linking service.
  478. * @param {PDFRenderingQueue} renderingQueue - The rendering queue object.
  479. * @param {Cache} cache - The page cache.
  480. * @param {PDFPageSource} pageSource
  481. * @param {PDFViewer} viewer
  482. *
  483. * @implements {IRenderableView}
  484. */
  485. var PageView = function pageView(container, id, scale, defaultViewport,
  486. linkService, renderingQueue, cache,
  487. pageSource, viewer) {
  488. this.id = id;
  489. this.renderingId = 'page' + id;
  490. this.rotation = 0;
  491. this.scale = scale || 1.0;
  492. this.viewport = defaultViewport;
  493. this.pdfPageRotate = defaultViewport.rotation;
  494. this.hasRestrictedScaling = false;
  495. this.linkService = linkService;
  496. this.renderingQueue = renderingQueue;
  497. this.cache = cache;
  498. this.pageSource = pageSource;
  499. this.viewer = viewer;
  500. this.renderingState = RenderingStates.INITIAL;
  501. this.resume = null;
  502. this.textLayer = null;
  503. this.zoomLayer = null;
  504. this.annotationLayer = null;
  505. var anchor = document.createElement('a');
  506. anchor.name = '' + this.id;
  507. var div = this.el = document.createElement('div');
  508. div.id = 'pageContainer' + this.id;
  509. div.className = 'page';
  510. div.style.width = Math.floor(this.viewport.width) + 'px';
  511. div.style.height = Math.floor(this.viewport.height) + 'px';
  512. container.appendChild(anchor);
  513. container.appendChild(div);
  514. this.setPdfPage = function pageViewSetPdfPage(pdfPage) {
  515. this.pdfPage = pdfPage;
  516. this.pdfPageRotate = pdfPage.rotate;
  517. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  518. this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation);
  519. this.stats = pdfPage.stats;
  520. this.reset();
  521. };
  522. this.destroy = function pageViewDestroy() {
  523. this.zoomLayer = null;
  524. this.reset();
  525. if (this.pdfPage) {
  526. this.pdfPage.destroy();
  527. }
  528. };
  529. this.reset = function pageViewReset(keepAnnotations) {
  530. if (this.renderTask) {
  531. this.renderTask.cancel();
  532. }
  533. this.resume = null;
  534. this.renderingState = RenderingStates.INITIAL;
  535. div.style.width = Math.floor(this.viewport.width) + 'px';
  536. div.style.height = Math.floor(this.viewport.height) + 'px';
  537. var childNodes = div.childNodes;
  538. for (var i = div.childNodes.length - 1; i >= 0; i--) {
  539. var node = childNodes[i];
  540. if ((this.zoomLayer && this.zoomLayer === node) ||
  541. (keepAnnotations && this.annotationLayer === node)) {
  542. continue;
  543. }
  544. div.removeChild(node);
  545. }
  546. div.removeAttribute('data-loaded');
  547. if (keepAnnotations) {
  548. if (this.annotationLayer) {
  549. // Hide annotationLayer until all elements are resized
  550. // so they are not displayed on the already-resized page
  551. this.annotationLayer.setAttribute('hidden', 'true');
  552. }
  553. } else {
  554. this.annotationLayer = null;
  555. }
  556. if (this.canvas) {
  557. // Zeroing the width and height causes Firefox to release graphics
  558. // resources immediately, which can greatly reduce memory consumption.
  559. this.canvas.width = 0;
  560. this.canvas.height = 0;
  561. delete this.canvas;
  562. }
  563. this.loadingIconDiv = document.createElement('div');
  564. this.loadingIconDiv.className = 'loadingIcon';
  565. div.appendChild(this.loadingIconDiv);
  566. };
  567. this.update = function pageViewUpdate(scale, rotation) {
  568. this.scale = scale || this.scale;
  569. if (typeof rotation !== 'undefined') {
  570. this.rotation = rotation;
  571. }
  572. var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  573. this.viewport = this.viewport.clone({
  574. scale: this.scale * CSS_UNITS,
  575. rotation: totalRotation
  576. });
  577. var isScalingRestricted = false;
  578. if (this.canvas && PDFJS.maxCanvasPixels > 0) {
  579. var ctx = this.canvas.getContext('2d');
  580. var outputScale = getOutputScale(ctx);
  581. var pixelsInViewport = this.viewport.width * this.viewport.height;
  582. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  583. if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
  584. ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
  585. PDFJS.maxCanvasPixels) {
  586. isScalingRestricted = true;
  587. }
  588. }
  589. if (this.canvas &&
  590. (PDFJS.useOnlyCssZoom ||
  591. (this.hasRestrictedScaling && isScalingRestricted))) {
  592. this.cssTransform(this.canvas, true);
  593. return;
  594. } else if (this.canvas && !this.zoomLayer) {
  595. this.zoomLayer = this.canvas.parentNode;
  596. this.zoomLayer.style.position = 'absolute';
  597. }
  598. if (this.zoomLayer) {
  599. this.cssTransform(this.zoomLayer.firstChild);
  600. }
  601. this.reset(true);
  602. };
  603. this.cssTransform = function pageCssTransform(canvas, redrawAnnotations) {
  604. // Scale canvas, canvas wrapper, and page container.
  605. var width = this.viewport.width;
  606. var height = this.viewport.height;
  607. canvas.style.width = canvas.parentNode.style.width = div.style.width =
  608. Math.floor(width) + 'px';
  609. canvas.style.height = canvas.parentNode.style.height = div.style.height =
  610. Math.floor(height) + 'px';
  611. // The canvas may have been originally rotated, so rotate relative to that.
  612. var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
  613. var absRotation = Math.abs(relativeRotation);
  614. var scaleX = 1, scaleY = 1;
  615. if (absRotation === 90 || absRotation === 270) {
  616. // Scale x and y because of the rotation.
  617. scaleX = height / width;
  618. scaleY = width / height;
  619. }
  620. var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
  621. 'scale(' + scaleX + ',' + scaleY + ')';
  622. CustomStyle.setProp('transform', canvas, cssTransform);
  623. if (this.textLayer) {
  624. // Rotating the text layer is more complicated since the divs inside the
  625. // the text layer are rotated.
  626. // TODO: This could probably be simplified by drawing the text layer in
  627. // one orientation then rotating overall.
  628. var textLayerViewport = this.textLayer.viewport;
  629. var textRelativeRotation = this.viewport.rotation -
  630. textLayerViewport.rotation;
  631. var textAbsRotation = Math.abs(textRelativeRotation);
  632. var scale = width / textLayerViewport.width;
  633. if (textAbsRotation === 90 || textAbsRotation === 270) {
  634. scale = width / textLayerViewport.height;
  635. }
  636. var textLayerDiv = this.textLayer.textLayerDiv;
  637. var transX, transY;
  638. switch (textAbsRotation) {
  639. case 0:
  640. transX = transY = 0;
  641. break;
  642. case 90:
  643. transX = 0;
  644. transY = '-' + textLayerDiv.style.height;
  645. break;
  646. case 180:
  647. transX = '-' + textLayerDiv.style.width;
  648. transY = '-' + textLayerDiv.style.height;
  649. break;
  650. case 270:
  651. transX = '-' + textLayerDiv.style.width;
  652. transY = 0;
  653. break;
  654. default:
  655. console.error('Bad rotation value.');
  656. break;
  657. }
  658. CustomStyle.setProp('transform', textLayerDiv,
  659. 'rotate(' + textAbsRotation + 'deg) ' +
  660. 'scale(' + scale + ', ' + scale + ') ' +
  661. 'translate(' + transX + ', ' + transY + ')');
  662. CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
  663. }
  664. if (redrawAnnotations && this.annotationLayer) {
  665. setupAnnotations(div, this.pdfPage, this.viewport);
  666. }
  667. };
  668. Object.defineProperty(this, 'width', {
  669. get: function PageView_getWidth() {
  670. return this.viewport.width;
  671. },
  672. enumerable: true
  673. });
  674. Object.defineProperty(this, 'height', {
  675. get: function PageView_getHeight() {
  676. return this.viewport.height;
  677. },
  678. enumerable: true
  679. });
  680. var self = this;
  681. function setupAnnotations(pageDiv, pdfPage, viewport) {
  682. function bindLink(link, dest) {
  683. link.href = linkService.getDestinationHash(dest);
  684. link.onclick = function pageViewSetupLinksOnclick() {
  685. if (dest) {
  686. linkService.navigateTo(dest);
  687. }
  688. return false;
  689. };
  690. if (dest) {
  691. link.className = 'internalLink';
  692. }
  693. }
  694. function bindNamedAction(link, action) {
  695. link.href = linkService.getAnchorUrl('');
  696. link.onclick = function pageViewSetupNamedActionOnClick() {
  697. linkService.executeNamedAction(action);
  698. return false;
  699. };
  700. link.className = 'internalLink';
  701. }
  702. pdfPage.getAnnotations().then(function(annotationsData) {
  703. viewport = viewport.clone({ dontFlip: true });
  704. var transform = viewport.transform;
  705. var transformStr = 'matrix(' + transform.join(',') + ')';
  706. var data, element, i, ii;
  707. if (self.annotationLayer) {
  708. // If an annotationLayer already exists, refresh its children's
  709. // transformation matrices
  710. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  711. data = annotationsData[i];
  712. element = self.annotationLayer.querySelector(
  713. '[data-annotation-id="' + data.id + '"]');
  714. if (element) {
  715. CustomStyle.setProp('transform', element, transformStr);
  716. }
  717. }
  718. // See this.reset()
  719. self.annotationLayer.removeAttribute('hidden');
  720. } else {
  721. for (i = 0, ii = annotationsData.length; i < ii; i++) {
  722. data = annotationsData[i];
  723. if (!data || !data.hasHtml) {
  724. continue;
  725. }
  726. element = PDFJS.AnnotationUtils.getHtmlElement(data,
  727. pdfPage.commonObjs);
  728. element.setAttribute('data-annotation-id', data.id);
  729. mozL10n.translate(element);
  730. var rect = data.rect;
  731. var view = pdfPage.view;
  732. rect = PDFJS.Util.normalizeRect([
  733. rect[0],
  734. view[3] - rect[1] + view[1],
  735. rect[2],
  736. view[3] - rect[3] + view[1]
  737. ]);
  738. element.style.left = rect[0] + 'px';
  739. element.style.top = rect[1] + 'px';
  740. element.style.position = 'absolute';
  741. CustomStyle.setProp('transform', element, transformStr);
  742. var transformOriginStr = -rect[0] + 'px ' + -rect[1] + 'px';
  743. CustomStyle.setProp('transformOrigin', element, transformOriginStr);
  744. if (data.subtype === 'Link' && !data.url) {
  745. var link = element.getElementsByTagName('a')[0];
  746. if (link) {
  747. if (data.action) {
  748. bindNamedAction(link, data.action);
  749. } else {
  750. bindLink(link, ('dest' in data) ? data.dest : null);
  751. }
  752. }
  753. }
  754. if (!self.annotationLayer) {
  755. var annotationLayerDiv = document.createElement('div');
  756. annotationLayerDiv.className = 'annotationLayer';
  757. pageDiv.appendChild(annotationLayerDiv);
  758. self.annotationLayer = annotationLayerDiv;
  759. }
  760. self.annotationLayer.appendChild(element);
  761. }
  762. }
  763. });
  764. }
  765. this.getPagePoint = function pageViewGetPagePoint(x, y) {
  766. return this.viewport.convertToPdfPoint(x, y);
  767. };
  768. this.draw = function pageviewDraw(callback) {
  769. var pdfPage = this.pdfPage;
  770. if (this.pagePdfPromise) {
  771. return;
  772. }
  773. if (!pdfPage) {
  774. var promise = this.pageSource.getPage();
  775. promise.then(function(pdfPage) {
  776. delete this.pagePdfPromise;
  777. this.setPdfPage(pdfPage);
  778. this.draw(callback);
  779. }.bind(this));
  780. this.pagePdfPromise = promise;
  781. return;
  782. }
  783. if (this.renderingState !== RenderingStates.INITIAL) {
  784. console.error('Must be in new state before drawing');
  785. }
  786. this.renderingState = RenderingStates.RUNNING;
  787. var viewport = this.viewport;
  788. // Wrap the canvas so if it has a css transform for highdpi the overflow
  789. // will be hidden in FF.
  790. var canvasWrapper = document.createElement('div');
  791. canvasWrapper.style.width = div.style.width;
  792. canvasWrapper.style.height = div.style.height;
  793. canvasWrapper.classList.add('canvasWrapper');
  794. var canvas = document.createElement('canvas');
  795. canvas.id = 'page' + this.id;
  796. canvasWrapper.appendChild(canvas);
  797. if (this.annotationLayer) {
  798. // annotationLayer needs to stay on top
  799. div.insertBefore(canvasWrapper, this.annotationLayer);
  800. } else {
  801. div.appendChild(canvasWrapper);
  802. }
  803. this.canvas = canvas;
  804. var ctx = canvas.getContext('2d');
  805. var outputScale = getOutputScale(ctx);
  806. if (PDFJS.useOnlyCssZoom) {
  807. var actualSizeViewport = viewport.clone({ scale: CSS_UNITS });
  808. // Use a scale that will make the canvas be the original intended size
  809. // of the page.
  810. outputScale.sx *= actualSizeViewport.width / viewport.width;
  811. outputScale.sy *= actualSizeViewport.height / viewport.height;
  812. outputScale.scaled = true;
  813. }
  814. if (PDFJS.maxCanvasPixels > 0) {
  815. var pixelsInViewport = viewport.width * viewport.height;
  816. var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
  817. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  818. outputScale.sx = maxScale;
  819. outputScale.sy = maxScale;
  820. outputScale.scaled = true;
  821. this.hasRestrictedScaling = true;
  822. } else {
  823. this.hasRestrictedScaling = false;
  824. }
  825. }
  826. canvas.width = (Math.floor(viewport.width) * outputScale.sx) | 0;
  827. canvas.height = (Math.floor(viewport.height) * outputScale.sy) | 0;
  828. canvas.style.width = Math.floor(viewport.width) + 'px';
  829. canvas.style.height = Math.floor(viewport.height) + 'px';
  830. // Add the viewport so it's known what it was originally drawn with.
  831. canvas._viewport = viewport;
  832. var textLayerDiv = null;
  833. var textLayer = null;
  834. if (!PDFJS.disableTextLayer) {
  835. textLayerDiv = document.createElement('div');
  836. textLayerDiv.className = 'textLayer';
  837. textLayerDiv.style.width = canvas.style.width;
  838. textLayerDiv.style.height = canvas.style.height;
  839. if (this.annotationLayer) {
  840. // annotationLayer needs to stay on top
  841. div.insertBefore(textLayerDiv, this.annotationLayer);
  842. } else {
  843. div.appendChild(textLayerDiv);
  844. }
  845. textLayer = this.viewer.createTextLayerBuilder(textLayerDiv, this.id - 1,
  846. this.viewport);
  847. }
  848. this.textLayer = textLayer;
  849. // TODO(mack): use data attributes to store these
  850. ctx._scaleX = outputScale.sx;
  851. ctx._scaleY = outputScale.sy;
  852. if (outputScale.scaled) {
  853. ctx.scale(outputScale.sx, outputScale.sy);
  854. }
  855. // Rendering area
  856. var self = this;
  857. function pageViewDrawCallback(error) {
  858. // The renderTask may have been replaced by a new one, so only remove the
  859. // reference to the renderTask if it matches the one that is triggering
  860. // this callback.
  861. if (renderTask === self.renderTask) {
  862. self.renderTask = null;
  863. }
  864. if (error === 'cancelled') {
  865. return;
  866. }
  867. self.renderingState = RenderingStates.FINISHED;
  868. if (self.loadingIconDiv) {
  869. div.removeChild(self.loadingIconDiv);
  870. delete self.loadingIconDiv;
  871. }
  872. if (self.zoomLayer) {
  873. div.removeChild(self.zoomLayer);
  874. self.zoomLayer = null;
  875. }
  876. self.error = error;
  877. self.stats = pdfPage.stats;
  878. self.updateStats();
  879. if (self.onAfterDraw) {
  880. self.onAfterDraw();
  881. }
  882. var event = document.createEvent('CustomEvent');
  883. event.initCustomEvent('pagerender', true, true, {
  884. pageNumber: pdfPage.pageNumber
  885. });
  886. div.dispatchEvent(event);
  887. callback();
  888. }
  889. var renderContext = {
  890. canvasContext: ctx,
  891. viewport: this.viewport,
  892. // intent: 'default', // === 'display'
  893. continueCallback: function pdfViewcContinueCallback(cont) {
  894. if (!self.renderingQueue.isHighestPriority(self)) {
  895. self.renderingState = RenderingStates.PAUSED;
  896. self.resume = function resumeCallback() {
  897. self.renderingState = RenderingStates.RUNNING;
  898. cont();
  899. };
  900. return;
  901. }
  902. cont();
  903. }
  904. };
  905. var renderTask = this.renderTask = this.pdfPage.render(renderContext);
  906. this.renderTask.promise.then(
  907. function pdfPageRenderCallback() {
  908. pageViewDrawCallback(null);
  909. if (textLayer) {
  910. self.pdfPage.getTextContent().then(
  911. function textContentResolved(textContent) {
  912. textLayer.setTextContent(textContent);
  913. }
  914. );
  915. }
  916. },
  917. function pdfPageRenderError(error) {
  918. pageViewDrawCallback(error);
  919. }
  920. );
  921. setupAnnotations(div, pdfPage, this.viewport);
  922. div.setAttribute('data-loaded', true);
  923. // Add the page to the cache at the start of drawing. That way it can be
  924. // evicted from the cache and destroyed even if we pause its rendering.
  925. cache.push(this);
  926. };
  927. this.beforePrint = function pageViewBeforePrint() {
  928. var pdfPage = this.pdfPage;
  929. var viewport = pdfPage.getViewport(1);
  930. // Use the same hack we use for high dpi displays for printing to get better
  931. // output until bug 811002 is fixed in FF.
  932. var PRINT_OUTPUT_SCALE = 2;
  933. var canvas = document.createElement('canvas');
  934. canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
  935. canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
  936. canvas.style.width = (PRINT_OUTPUT_SCALE * viewport.width) + 'pt';
  937. canvas.style.height = (PRINT_OUTPUT_SCALE * viewport.height) + 'pt';
  938. var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
  939. (1 / PRINT_OUTPUT_SCALE) + ')';
  940. CustomStyle.setProp('transform' , canvas, cssScale);
  941. CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
  942. var printContainer = document.getElementById('printContainer');
  943. var canvasWrapper = document.createElement('div');
  944. canvasWrapper.style.width = viewport.width + 'pt';
  945. canvasWrapper.style.height = viewport.height + 'pt';
  946. canvasWrapper.appendChild(canvas);
  947. printContainer.appendChild(canvasWrapper);
  948. canvas.mozPrintCallback = function(obj) {
  949. var ctx = obj.context;
  950. ctx.save();
  951. ctx.fillStyle = 'rgb(255, 255, 255)';
  952. ctx.fillRect(0, 0, canvas.width, canvas.height);
  953. ctx.restore();
  954. ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
  955. var renderContext = {
  956. canvasContext: ctx,
  957. viewport: viewport,
  958. intent: 'print'
  959. };
  960. pdfPage.render(renderContext).promise.then(function() {
  961. // Tell the printEngine that rendering this canvas/page has finished.
  962. obj.done();
  963. }, function(error) {
  964. console.error(error);
  965. // Tell the printEngine that rendering this canvas/page has failed.
  966. // This will make the print proces stop.
  967. if ('abort' in obj) {
  968. obj.abort();
  969. } else {
  970. obj.done();
  971. }
  972. });
  973. };
  974. };
  975. this.updateStats = function pageViewUpdateStats() {
  976. if (!this.stats) {
  977. return;
  978. }
  979. if (PDFJS.pdfBug && Stats.enabled) {
  980. var stats = this.stats;
  981. Stats.add(this.id, stats);
  982. }
  983. };
  984. };
  985. var FIND_SCROLL_OFFSET_TOP = -50;
  986. var FIND_SCROLL_OFFSET_LEFT = -400;
  987. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  988. var RENDER_DELAY = 200; // ms
  989. var NonWhitespaceRegexp = /\S/;
  990. function isAllWhitespace(str) {
  991. return !NonWhitespaceRegexp.test(str);
  992. }
  993. /**
  994. * @typedef {Object} TextLayerBuilderOptions
  995. * @property {HTMLDivElement} textLayerDiv - The text layer container.
  996. * @property {number} pageIndex - The page index.
  997. * @property {PageViewport} viewport - The viewport of the text layer.
  998. * @property {ILastScrollSource} lastScrollSource - The object that records when
  999. * last time scroll happened.
  1000. * @property {boolean} isViewerInPresentationMode
  1001. * @property {PDFFindController} findController
  1002. */
  1003. /**
  1004. * TextLayerBuilder provides text-selection functionality for the PDF.
  1005. * It does this by creating overlay divs over the PDF text. These divs
  1006. * contain text that matches the PDF text they are overlaying. This object
  1007. * also provides a way to highlight text that is being searched for.
  1008. * @class
  1009. */
  1010. var TextLayerBuilder = (function TextLayerBuilderClosure() {
  1011. function TextLayerBuilder(options) {
  1012. this.textLayerDiv = options.textLayerDiv;
  1013. this.layoutDone = false;
  1014. this.divContentDone = false;
  1015. this.pageIdx = options.pageIndex;
  1016. this.matches = [];
  1017. this.lastScrollSource = options.lastScrollSource || null;
  1018. this.viewport = options.viewport;
  1019. this.isViewerInPresentationMode = options.isViewerInPresentationMode;
  1020. this.textDivs = [];
  1021. this.findController = options.findController || null;
  1022. }
  1023. TextLayerBuilder.prototype = {
  1024. renderLayer: function TextLayerBuilder_renderLayer() {
  1025. var textLayerFrag = document.createDocumentFragment();
  1026. var textDivs = this.textDivs;
  1027. var textDivsLength = textDivs.length;
  1028. var canvas = document.createElement('canvas');
  1029. var ctx = canvas.getContext('2d');
  1030. // No point in rendering many divs as it would make the browser
  1031. // unusable even after the divs are rendered.
  1032. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  1033. return;
  1034. }
  1035. var lastFontSize;
  1036. var lastFontFamily;
  1037. for (var i = 0; i < textDivsLength; i++) {
  1038. var textDiv = textDivs[i];
  1039. if (textDiv.dataset.isWhitespace !== undefined) {
  1040. continue;
  1041. }
  1042. var fontSize = textDiv.style.fontSize;
  1043. var fontFamily = textDiv.style.fontFamily;
  1044. // Only build font string and set to context if different from last.
  1045. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  1046. ctx.font = fontSize + ' ' + fontFamily;
  1047. lastFontSize = fontSize;
  1048. lastFontFamily = fontFamily;
  1049. }
  1050. var width = ctx.measureText(textDiv.textContent).width;
  1051. if (width > 0) {
  1052. textLayerFrag.appendChild(textDiv);
  1053. var transform;
  1054. if (textDiv.dataset.canvasWidth !== undefined) {
  1055. // Dataset values come of type string.
  1056. var textScale = textDiv.dataset.canvasWidth / width;
  1057. transform = 'scaleX(' + textScale + ')';
  1058. } else {
  1059. transform = '';
  1060. }
  1061. var rotation = textDiv.dataset.angle;
  1062. if (rotation) {
  1063. transform = 'rotate(' + rotation + 'deg) ' + transform;
  1064. }
  1065. if (transform) {
  1066. CustomStyle.setProp('transform' , textDiv, transform);
  1067. }
  1068. }
  1069. }
  1070. this.textLayerDiv.appendChild(textLayerFrag);
  1071. this.renderingDone = true;
  1072. this.updateMatches();
  1073. },
  1074. setupRenderLayoutTimer:
  1075. function TextLayerBuilder_setupRenderLayoutTimer() {
  1076. // Schedule renderLayout() if the user has been scrolling,
  1077. // otherwise run it right away.
  1078. var self = this;
  1079. var lastScroll = (this.lastScrollSource === null ?
  1080. 0 : this.lastScrollSource.lastScroll);
  1081. if (Date.now() - lastScroll > RENDER_DELAY) { // Render right away
  1082. this.renderLayer();
  1083. } else { // Schedule
  1084. if (this.renderTimer) {
  1085. clearTimeout(this.renderTimer);
  1086. }
  1087. this.renderTimer = setTimeout(function() {
  1088. self.setupRenderLayoutTimer();
  1089. }, RENDER_DELAY);
  1090. }
  1091. },
  1092. appendText: function TextLayerBuilder_appendText(geom, styles) {
  1093. var style = styles[geom.fontName];
  1094. var textDiv = document.createElement('div');
  1095. this.textDivs.push(textDiv);
  1096. if (isAllWhitespace(geom.str)) {
  1097. textDiv.dataset.isWhitespace = true;
  1098. return;
  1099. }
  1100. var tx = PDFJS.Util.transform(this.viewport.transform, geom.transform);
  1101. var angle = Math.atan2(tx[1], tx[0]);
  1102. if (style.vertical) {
  1103. angle += Math.PI / 2;
  1104. }
  1105. var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3]));
  1106. var fontAscent = fontHeight;
  1107. if (style.ascent) {
  1108. fontAscent = style.ascent * fontAscent;
  1109. } else if (style.descent) {
  1110. fontAscent = (1 + style.descent) * fontAscent;
  1111. }
  1112. var left;
  1113. var top;
  1114. if (angle === 0) {
  1115. left = tx[4];
  1116. top = tx[5] - fontAscent;
  1117. } else {
  1118. left = tx[4] + (fontAscent * Math.sin(angle));
  1119. top = tx[5] - (fontAscent * Math.cos(angle));
  1120. }
  1121. textDiv.style.left = left + 'px';
  1122. textDiv.style.top = top + 'px';
  1123. textDiv.style.fontSize = fontHeight + 'px';
  1124. textDiv.style.fontFamily = style.fontFamily;
  1125. textDiv.textContent = geom.str;
  1126. // |fontName| is only used by the Font Inspector. This test will succeed
  1127. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  1128. // not worth the effort to do a more accurate test.
  1129. if (PDFJS.pdfBug) {
  1130. textDiv.dataset.fontName = geom.fontName;
  1131. }
  1132. // Storing into dataset will convert number into string.
  1133. if (angle !== 0) {
  1134. textDiv.dataset.angle = angle * (180 / Math.PI);
  1135. }
  1136. // We don't bother scaling single-char text divs, because it has very
  1137. // little effect on text highlighting. This makes scrolling on docs with
  1138. // lots of such divs a lot faster.
  1139. if (textDiv.textContent.length > 1) {
  1140. if (style.vertical) {
  1141. textDiv.dataset.canvasWidth = geom.height * this.viewport.scale;
  1142. } else {
  1143. textDiv.dataset.canvasWidth = geom.width * this.viewport.scale;
  1144. }
  1145. }
  1146. },
  1147. setTextContent: function TextLayerBuilder_setTextContent(textContent) {
  1148. this.textContent = textContent;
  1149. var textItems = textContent.items;
  1150. for (var i = 0, len = textItems.length; i < len; i++) {
  1151. this.appendText(textItems[i], textContent.styles);
  1152. }
  1153. this.divContentDone = true;
  1154. this.setupRenderLayoutTimer();
  1155. },
  1156. convertMatches: function TextLayerBuilder_convertMatches(matches) {
  1157. var i = 0;
  1158. var iIndex = 0;
  1159. var bidiTexts = this.textContent.items;
  1160. var end = bidiTexts.length - 1;
  1161. var queryLen = (this.findController === null ?
  1162. 0 : this.findController.state.query.length);
  1163. var ret = [];
  1164. for (var m = 0, len = matches.length; m < len; m++) {
  1165. // Calculate the start position.
  1166. var matchIdx = matches[m];
  1167. // Loop over the divIdxs.
  1168. while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
  1169. iIndex += bidiTexts[i].str.length;
  1170. i++;
  1171. }
  1172. if (i === bidiTexts.length) {
  1173. console.error('Could not find a matching mapping');
  1174. }
  1175. var match = {
  1176. begin: {
  1177. divIdx: i,
  1178. offset: matchIdx - iIndex
  1179. }
  1180. };
  1181. // Calculate the end position.
  1182. matchIdx += queryLen;
  1183. // Somewhat the same array as above, but use > instead of >= to get
  1184. // the end position right.
  1185. while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
  1186. iIndex += bidiTexts[i].str.length;
  1187. i++;
  1188. }
  1189. match.end = {
  1190. divIdx: i,
  1191. offset: matchIdx - iIndex
  1192. };
  1193. ret.push(match);
  1194. }
  1195. return ret;
  1196. },
  1197. renderMatches: function TextLayerBuilder_renderMatches(matches) {
  1198. // Early exit if there is nothing to render.
  1199. if (matches.length === 0) {
  1200. return;
  1201. }
  1202. var bidiTexts = this.textContent.items;
  1203. var textDivs = this.textDivs;
  1204. var prevEnd = null;
  1205. var isSelectedPage = (this.findController === null ?
  1206. false : (this.pageIdx === this.findController.selected.pageIdx));
  1207. var selectedMatchIdx = (this.findController === null ?
  1208. -1 : this.findController.selected.matchIdx);
  1209. var highlightAll = (this.findController === null ?
  1210. false : this.findController.state.highlightAll);
  1211. var infinity = {
  1212. divIdx: -1,
  1213. offset: undefined
  1214. };
  1215. function beginText(begin, className) {
  1216. var divIdx = begin.divIdx;
  1217. textDivs[divIdx].textContent = '';
  1218. appendTextToDiv(divIdx, 0, begin.offset, className);
  1219. }
  1220. function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
  1221. var div = textDivs[divIdx];
  1222. var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
  1223. var node = document.createTextNode(content);
  1224. if (className) {
  1225. var span = document.createElement('span');
  1226. span.className = className;
  1227. span.appendChild(node);
  1228. div.appendChild(span);
  1229. return;
  1230. }
  1231. div.appendChild(node);
  1232. }
  1233. var i0 = selectedMatchIdx, i1 = i0 + 1;
  1234. if (highlightAll) {
  1235. i0 = 0;
  1236. i1 = matches.length;
  1237. } else if (!isSelectedPage) {
  1238. // Not highlighting all and this isn't the selected page, so do nothing.
  1239. return;
  1240. }
  1241. for (var i = i0; i < i1; i++) {
  1242. var match = matches[i];
  1243. var begin = match.begin;
  1244. var end = match.end;
  1245. var isSelected = (isSelectedPage && i === selectedMatchIdx);
  1246. var highlightSuffix = (isSelected ? ' selected' : '');
  1247. if (isSelected && !this.isViewerInPresentationMode) {
  1248. scrollIntoView(textDivs[begin.divIdx],
  1249. { top: FIND_SCROLL_OFFSET_TOP,
  1250. left: FIND_SCROLL_OFFSET_LEFT });
  1251. }
  1252. // Match inside new div.
  1253. if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
  1254. // If there was a previous div, then add the text at the end.
  1255. if (prevEnd !== null) {
  1256. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1257. }
  1258. // Clear the divs and set the content until the starting point.
  1259. beginText(begin);
  1260. } else {
  1261. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
  1262. }
  1263. if (begin.divIdx === end.divIdx) {
  1264. appendTextToDiv(begin.divIdx, begin.offset, end.offset,
  1265. 'highlight' + highlightSuffix);
  1266. } else {
  1267. appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
  1268. 'highlight begin' + highlightSuffix);
  1269. for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
  1270. textDivs[n0].className = 'highlight middle' + highlightSuffix;
  1271. }
  1272. beginText(end, 'highlight end' + highlightSuffix);
  1273. }
  1274. prevEnd = end;
  1275. }
  1276. if (prevEnd) {
  1277. appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
  1278. }
  1279. },
  1280. updateMatches: function TextLayerBuilder_updateMatches() {
  1281. // Only show matches when all rendering is done.
  1282. if (!this.renderingDone) {
  1283. return;
  1284. }
  1285. // Clear all matches.
  1286. var matches = this.matches;
  1287. var textDivs = this.textDivs;
  1288. var bidiTexts = this.textContent.items;
  1289. var clearedUntilDivIdx = -1;
  1290. // Clear all current matches.
  1291. for (var i = 0, len = matches.length; i < len; i++) {
  1292. var match = matches[i];
  1293. var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
  1294. for (var n = begin, end = match.end.divIdx; n <= end; n++) {
  1295. var div = textDivs[n];
  1296. div.textContent = bidiTexts[n].str;
  1297. div.className = '';
  1298. }
  1299. clearedUntilDivIdx = match.end.divIdx + 1;
  1300. }
  1301. if (this.findController === null || !this.findController.active) {
  1302. return;
  1303. }
  1304. // Convert the matches on the page controller into the match format
  1305. // used for the textLayer.
  1306. this.matches = this.convertMatches(this.findController === null ?
  1307. [] : (this.findController.pageMatches[this.pageIdx] || []));
  1308. this.renderMatches(this.matches);
  1309. }
  1310. };
  1311. return TextLayerBuilder;
  1312. })();
  1313. /**
  1314. * @typedef {Object} PDFViewerOptions
  1315. * @property {HTMLDivElement} container - The container for the viewer element.
  1316. * @property {HTMLDivElement} viewer - (optional) The viewer element.
  1317. * @property {IPDFLinkService} linkService - The navigation/linking service.
  1318. * @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
  1319. * queue object.
  1320. */
  1321. /**
  1322. * Simple viewer control to display PDF content/pages.
  1323. * @class
  1324. * @implements {ILastScrollSource}
  1325. * @implements {IRenderableView}
  1326. */
  1327. var PDFViewer = (function pdfViewer() {
  1328. /**
  1329. * @constructs PDFViewer
  1330. * @param {PDFViewerOptions} options
  1331. */
  1332. function PDFViewer(options) {
  1333. this.container = options.container;
  1334. this.viewer = options.viewer || options.container.firstElementChild;
  1335. this.linkService = options.linkService || new SimpleLinkService(this);
  1336. this.defaultRenderingQueue = !options.renderingQueue;
  1337. if (this.defaultRenderingQueue) {
  1338. // Custom rendering queue is not specified, using default one
  1339. this.renderingQueue = new PDFRenderingQueue();
  1340. this.renderingQueue.setViewer(this);
  1341. } else {
  1342. this.renderingQueue = options.renderingQueue;
  1343. }
  1344. this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
  1345. this.lastScroll = 0;
  1346. this.updateInProgress = false;
  1347. this.presentationModeState = PresentationModeState.UNKNOWN;
  1348. this._resetView();
  1349. }
  1350. PDFViewer.prototype = /** @lends PDFViewer.prototype */{
  1351. get pagesCount() {
  1352. return this.pages.length;
  1353. },
  1354. getPageView: function (index) {
  1355. return this.pages[index];
  1356. },
  1357. get currentPageNumber() {
  1358. return this._currentPageNumber;
  1359. },
  1360. set currentPageNumber(val) {
  1361. if (!this.pdfDocument) {
  1362. this._currentPageNumber = val;
  1363. return;
  1364. }
  1365. var event = document.createEvent('UIEvents');
  1366. event.initUIEvent('pagechange', true, true, window, 0);
  1367. event.updateInProgress = this.updateInProgress;
  1368. if (!(0 < val && val <= this.pagesCount)) {
  1369. event.pageNumber = this._currentPageNumber;
  1370. event.previousPageNumber = val;
  1371. this.container.dispatchEvent(event);
  1372. return;
  1373. }
  1374. this.pages[val - 1].updateStats();
  1375. event.previousPageNumber = this._currentPageNumber;
  1376. this._currentPageNumber = val;
  1377. event.pageNumber = val;
  1378. this.container.dispatchEvent(event);
  1379. },
  1380. /**
  1381. * @returns {number}
  1382. */
  1383. get currentScale() {
  1384. return this._currentScale;
  1385. },
  1386. /**
  1387. * @param {number} val - Scale of the pages in percents.
  1388. */
  1389. set currentScale(val) {
  1390. if (isNaN(val)) {
  1391. throw new Error('Invalid numeric scale');
  1392. }
  1393. if (!this.pdfDocument) {
  1394. this._currentScale = val;
  1395. this._currentScaleValue = val.toString();
  1396. return;
  1397. }
  1398. this._setScale(val, false);
  1399. },
  1400. /**
  1401. * @returns {string}
  1402. */
  1403. get currentScaleValue() {
  1404. return this._currentScaleValue;
  1405. },
  1406. /**
  1407. * @param val - The scale of the pages (in percent or predefined value).
  1408. */
  1409. set currentScaleValue(val) {
  1410. if (!this.pdfDocument) {
  1411. this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
  1412. this._currentScaleValue = val;
  1413. return;
  1414. }
  1415. this._setScale(val, false);
  1416. },
  1417. /**
  1418. * @returns {number}
  1419. */
  1420. get pagesRotation() {
  1421. return this._pagesRotation;
  1422. },
  1423. /**
  1424. * @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
  1425. */
  1426. set pagesRotation(rotation) {
  1427. this._pagesRotation = rotation;
  1428. for (var i = 0, l = this.pages.length; i < l; i++) {
  1429. var page = this.pages[i];
  1430. page.update(page.scale, rotation);
  1431. }
  1432. this._setScale(this._currentScaleValue, true);
  1433. },
  1434. /**
  1435. * @param pdfDocument {PDFDocument}
  1436. */
  1437. setDocument: function (pdfDocument) {
  1438. if (this.pdfDocument) {
  1439. this._resetView();
  1440. }
  1441. this.pdfDocument = pdfDocument;
  1442. if (!pdfDocument) {
  1443. return;
  1444. }
  1445. var pagesCount = pdfDocument.numPages;
  1446. var pagesRefMap = this.pagesRefMap = {};
  1447. var self = this;
  1448. var resolvePagesPromise;
  1449. var pagesPromise = new Promise(function (resolve) {
  1450. resolvePagesPromise = resolve;
  1451. });
  1452. this.pagesPromise = pagesPromise;
  1453. pagesPromise.then(function () {
  1454. var event = document.createEvent('CustomEvent');
  1455. event.initCustomEvent('pagesloaded', true, true, {
  1456. pagesCount: pagesCount
  1457. });
  1458. self.container.dispatchEvent(event);
  1459. });
  1460. var isOnePageRenderedResolved = false;
  1461. var resolveOnePageRendered = null;
  1462. var onePageRendered = new Promise(function (resolve) {
  1463. resolveOnePageRendered = resolve;
  1464. });
  1465. this.onePageRendered = onePageRendered;
  1466. var bindOnAfterDraw = function (pageView) {
  1467. // when page is painted, using the image as thumbnail base
  1468. pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
  1469. if (!isOnePageRenderedResolved) {
  1470. isOnePageRenderedResolved = true;
  1471. resolveOnePageRendered();
  1472. }
  1473. var event = document.createEvent('CustomEvent');
  1474. event.initCustomEvent('pagerendered', true, true, {
  1475. pageNumber: pageView.id
  1476. });
  1477. self.container.dispatchEvent(event);
  1478. };
  1479. };
  1480. var firstPagePromise = pdfDocument.getPage(1);
  1481. this.firstPagePromise = firstPagePromise;
  1482. // Fetch a single page so we can get a viewport that will be the default
  1483. // viewport for all pages
  1484. return firstPagePromise.then(function(pdfPage) {
  1485. var scale = this._currentScale || 1.0;
  1486. var viewport = pdfPage.getViewport(scale * CSS_UNITS);
  1487. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1488. var pageSource = new PDFPageSource(pdfDocument, pageNum);
  1489. var pageView = new PageView(this.viewer, pageNum, scale,
  1490. viewport.clone(), this.linkService,
  1491. this.renderingQueue, this.cache,
  1492. pageSource, this);
  1493. bindOnAfterDraw(pageView);
  1494. this.pages.push(pageView);
  1495. }
  1496. // Fetch all the pages since the viewport is needed before printing
  1497. // starts to create the correct size canvas. Wait until one page is
  1498. // rendered so we don't tie up too many resources early on.
  1499. onePageRendered.then(function () {
  1500. if (!PDFJS.disableAutoFetch) {
  1501. var getPagesLeft = pagesCount;
  1502. for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  1503. pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
  1504. var pageView = self.pages[pageNum - 1];
  1505. if (!pageView.pdfPage) {
  1506. pageView.setPdfPage(pdfPage);
  1507. }
  1508. var refStr = pdfPage.ref.num + ' ' + pdfPage.ref.gen + ' R';
  1509. pagesRefMap[refStr] = pageNum;
  1510. getPagesLeft--;
  1511. if (!getPagesLeft) {
  1512. resolvePagesPromise();
  1513. }
  1514. }.bind(null, pageNum));
  1515. }
  1516. } else {
  1517. // XXX: Printing is semi-broken with auto fetch disabled.
  1518. resolvePagesPromise();
  1519. }
  1520. });
  1521. var event = document.createEvent('CustomEvent');
  1522. event.initCustomEvent('pagesinit', true, true, null);
  1523. self.container.dispatchEvent(event);
  1524. if (this.defaultRenderingQueue) {
  1525. this.update();
  1526. }
  1527. }.bind(this));
  1528. },
  1529. _resetView: function () {
  1530. this.cache = new Cache(DEFAULT_CACHE_SIZE);
  1531. this.pages = [];
  1532. this._currentPageNumber = 1;
  1533. this._currentScale = UNKNOWN_SCALE;
  1534. this._currentScaleValue = null;
  1535. this.location = null;
  1536. this._pagesRotation = 0;
  1537. var container = this.viewer;
  1538. while (container.hasChildNodes()) {
  1539. container.removeChild(container.lastChild);
  1540. }
  1541. },
  1542. _scrollUpdate: function () {
  1543. this.lastScroll = Date.now();
  1544. if (this.pagesCount === 0) {
  1545. return;
  1546. }
  1547. this.update();
  1548. },
  1549. _setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
  1550. newScale, newValue, noScroll, preset) {
  1551. this._currentScaleValue = newValue;
  1552. if (newScale === this._currentScale) {
  1553. return;
  1554. }
  1555. for (var i = 0, ii = this.pages.length; i < ii; i++) {
  1556. this.pages[i].update(newScale);
  1557. }
  1558. this._currentScale = newScale;
  1559. if (!noScroll) {
  1560. var page = this._currentPageNumber, dest;
  1561. var inPresentationMode =
  1562. this.presentationModeState === PresentationModeState.CHANGING ||
  1563. this.presentationModeState === PresentationModeState.FULLSCREEN;
  1564. if (this.location && !inPresentationMode &&
  1565. !IGNORE_CURRENT_POSITION_ON_ZOOM) {
  1566. page = this.location.pageNumber;
  1567. dest = [null, { name: 'XYZ' }, this.location.left,
  1568. this.location.top, null];
  1569. }
  1570. this.scrollPageIntoView(page, dest);
  1571. }
  1572. var event = document.createEvent('UIEvents');
  1573. event.initUIEvent('scalechange', true, true, window, 0);
  1574. event.scale = newScale;
  1575. if (preset) {
  1576. event.presetValue = newValue;
  1577. }
  1578. this.container.dispatchEvent(event);
  1579. },
  1580. _setScale: function pdfViewer_setScale(value, noScroll) {
  1581. if (value === 'custom') {
  1582. return;
  1583. }
  1584. var scale = parseFloat(value);
  1585. if (scale > 0) {
  1586. this._setScaleUpdatePages(scale, value, noScroll, false);
  1587. } else {
  1588. var currentPage = this.pages[this._currentPageNumber - 1];
  1589. if (!currentPage) {
  1590. return;
  1591. }
  1592. var inPresentationMode =
  1593. this.presentationModeState === PresentationModeState.FULLSCREEN;
  1594. var hPadding = inPresentationMode ? 0 : SCROLLBAR_PADDING;
  1595. var vPadding = inPresentationMode ? 0 : VERTICAL_PADDING;
  1596. var pageWidthScale = (this.container.clientWidth - hPadding) /
  1597. currentPage.width * currentPage.scale;
  1598. var pageHeightScale = (this.container.clientHeight - vPadding) /
  1599. currentPage.height * currentPage.scale;
  1600. switch (value) {
  1601. case 'page-actual':
  1602. scale = 1;
  1603. break;
  1604. case 'page-width':
  1605. scale = pageWidthScale;
  1606. break;
  1607. case 'page-height':
  1608. scale = pageHeightScale;
  1609. break;
  1610. case 'page-fit':
  1611. scale = Math.min(pageWidthScale, pageHeightScale);
  1612. break;
  1613. case 'auto':
  1614. var isLandscape = (currentPage.width > currentPage.height);
  1615. // For pages in landscape mode, fit the page height to the viewer
  1616. // *unless* the page would thus become too wide to fit horizontally.
  1617. var horizontalScale = isLandscape ?
  1618. Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
  1619. scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
  1620. break;
  1621. default:
  1622. console.error('pdfViewSetScale: \'' + value +
  1623. '\' is an unknown zoom value.');
  1624. return;
  1625. }
  1626. this._setScaleUpdatePages(scale, value, noScroll, true);
  1627. }
  1628. },
  1629. /**
  1630. * Scrolls page into view.
  1631. * @param {number} pageNumber
  1632. * @param {Array} dest - (optional) original PDF destination array:
  1633. * <page-ref> </XYZ|FitXXX> <args..>
  1634. */
  1635. scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
  1636. dest) {
  1637. var pageView = this.pages[pageNumber - 1];
  1638. var pageViewDiv = pageView.el;
  1639. if (this.presentationModeState ===
  1640. PresentationModeState.FULLSCREEN) {
  1641. if (this.linkService.page !== pageView.id) {
  1642. // Avoid breaking getVisiblePages in presentation mode.
  1643. this.linkService.page = pageView.id;
  1644. return;
  1645. }
  1646. dest = null;
  1647. // Fixes the case when PDF has different page sizes.
  1648. this._setScale(this.currentScaleValue, true);
  1649. }
  1650. if (!dest) {
  1651. scrollIntoView(pageViewDiv);
  1652. return;
  1653. }
  1654. var x = 0, y = 0;
  1655. var width = 0, height = 0, widthScale, heightScale;
  1656. var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
  1657. var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
  1658. pageView.scale / CSS_UNITS;
  1659. var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
  1660. pageView.scale / CSS_UNITS;
  1661. var scale = 0;
  1662. switch (dest[1].name) {
  1663. case 'XYZ':
  1664. x = dest[2];
  1665. y = dest[3];
  1666. scale = dest[4];
  1667. // If x and/or y coordinates are not supplied, default to
  1668. // _top_ left of the page (not the obvious bottom left,
  1669. // since aligning the bottom of the intended page with the
  1670. // top of the window is rarely helpful).
  1671. x = x !== null ? x : 0;
  1672. y = y !== null ? y : pageHeight;
  1673. break;
  1674. case 'Fit':
  1675. case 'FitB':
  1676. scale = 'page-fit';
  1677. break;
  1678. case 'FitH':
  1679. case 'FitBH':
  1680. y = dest[2];
  1681. scale = 'page-width';
  1682. break;
  1683. case 'FitV':
  1684. case 'FitBV':
  1685. x = dest[2];
  1686. width = pageWidth;
  1687. height = pageHeight;
  1688. scale = 'page-height';
  1689. break;
  1690. case 'FitR':
  1691. x = dest[2];
  1692. y = dest[3];
  1693. width = dest[4] - x;
  1694. height = dest[5] - y;
  1695. var viewerContainer = this.container;
  1696. widthScale = (viewerContainer.clientWidth - SCROLLBAR_PADDING) /
  1697. width / CSS_UNITS;
  1698. heightScale = (viewerContainer.clientHeight - SCROLLBAR_PADDING) /
  1699. height / CSS_UNITS;
  1700. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  1701. break;
  1702. default:
  1703. return;
  1704. }
  1705. if (scale && scale !== this.currentScale) {
  1706. this.currentScaleValue = scale;
  1707. } else if (this.currentScale === UNKNOWN_SCALE) {
  1708. this.currentScaleValue = DEFAULT_SCALE;
  1709. }
  1710. if (scale === 'page-fit' && !dest[4]) {
  1711. scrollIntoView(pageViewDiv);
  1712. return;
  1713. }
  1714. var boundingRect = [
  1715. pageView.viewport.convertToViewportPoint(x, y),
  1716. pageView.viewport.convertToViewportPoint(x + width, y + height)
  1717. ];
  1718. var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  1719. var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  1720. scrollIntoView(pageViewDiv, { left: left, top: top });
  1721. },
  1722. _updateLocation: function (firstPage) {
  1723. var currentScale = this._currentScale;
  1724. var currentScaleValue = this._currentScaleValue;
  1725. var normalizedScaleValue =
  1726. parseFloat(currentScaleValue) === currentScale ?
  1727. Math.round(currentScale * 10000) / 100 : currentScaleValue;
  1728. var pageNumber = firstPage.id;
  1729. var pdfOpenParams = '#page=' + pageNumber;
  1730. pdfOpenParams += '&zoom=' + normalizedScaleValue;
  1731. var currentPageView = this.pages[pageNumber - 1];
  1732. var container = this.container;
  1733. var topLeft = currentPageView.getPagePoint(
  1734. (container.scrollLeft - firstPage.x),
  1735. (container.scrollTop - firstPage.y));
  1736. var intLeft = Math.round(topLeft[0]);
  1737. var intTop = Math.round(topLeft[1]);
  1738. pdfOpenParams += ',' + intLeft + ',' + intTop;
  1739. this.location = {
  1740. pageNumber: pageNumber,
  1741. scale: normalizedScaleValue,
  1742. top: intTop,
  1743. left: intLeft,
  1744. pdfOpenParams: pdfOpenParams
  1745. };
  1746. },
  1747. update: function () {
  1748. var visible = this._getVisiblePages();
  1749. var visiblePages = visible.views;
  1750. if (visiblePages.length === 0) {
  1751. return;
  1752. }
  1753. this.updateInProgress = true;
  1754. var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
  1755. 2 * visiblePages.length + 1);
  1756. this.cache.resize(suggestedCacheSize);
  1757. this.renderingQueue.renderHighestPriority(visible);
  1758. var currentId = this.currentPageNumber;
  1759. var firstPage = visible.first;
  1760. for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
  1761. i < ii; ++i) {
  1762. var page = visiblePages[i];
  1763. if (page.percent < 100) {
  1764. break;
  1765. }
  1766. if (page.id === currentId) {
  1767. stillFullyVisible = true;
  1768. break;
  1769. }
  1770. }
  1771. if (!stillFullyVisible) {
  1772. currentId = visiblePages[0].id;
  1773. }
  1774. if (this.presentationModeState !== PresentationModeState.FULLSCREEN) {
  1775. this.currentPageNumber = currentId;
  1776. }
  1777. this._updateLocation(firstPage);
  1778. this.updateInProgress = false;
  1779. var event = document.createEvent('UIEvents');
  1780. event.initUIEvent('updateviewarea', true, true, window, 0);
  1781. this.container.dispatchEvent(event);
  1782. },
  1783. containsElement: function (element) {
  1784. return this.container.contains(element);
  1785. },
  1786. focus: function () {
  1787. this.container.focus();
  1788. },
  1789. blur: function () {
  1790. this.container.blur();
  1791. },
  1792. get isHorizontalScrollbarEnabled() {
  1793. return (this.presentationModeState === PresentationModeState.FULLSCREEN ?
  1794. false : (this.container.scrollWidth > this.container.clientWidth));
  1795. },
  1796. _getVisiblePages: function () {
  1797. if (this.presentationModeState !== PresentationModeState.FULLSCREEN) {
  1798. return getVisibleElements(this.container, this.pages, true);
  1799. } else {
  1800. // The algorithm in getVisibleElements doesn't work in all browsers and
  1801. // configurations when presentation mode is active.
  1802. var visible = [];
  1803. var currentPage = this.pages[this._currentPageNumber - 1];
  1804. visible.push({ id: currentPage.id, view: currentPage });
  1805. return { first: currentPage, last: currentPage, views: visible };
  1806. }
  1807. },
  1808. cleanup: function () {
  1809. for (var i = 0, ii = this.pages.length; i < ii; i++) {
  1810. if (this.pages[i] &&
  1811. this.pages[i].renderingState !== RenderingStates.FINISHED) {
  1812. this.pages[i].reset();
  1813. }
  1814. }
  1815. },
  1816. forceRendering: function (currentlyVisiblePages) {
  1817. var visiblePages = currentlyVisiblePages || this._getVisiblePages();
  1818. var pageView = this.renderingQueue.getHighestPriority(visiblePages,
  1819. this.pages,
  1820. this.scroll.down);
  1821. if (pageView) {
  1822. this.renderingQueue.renderView(pageView);
  1823. return true;
  1824. }
  1825. return false;
  1826. },
  1827. getPageTextContent: function (pageIndex) {
  1828. return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
  1829. return page.getTextContent();
  1830. });
  1831. },
  1832. /**
  1833. * @param textLayerDiv {HTMLDivElement}
  1834. * @param pageIndex {number}
  1835. * @param viewport {PageViewport}
  1836. * @returns {TextLayerBuilder}
  1837. */
  1838. createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
  1839. var isViewerInPresentationMode =
  1840. this.presentationModeState === PresentationModeState.FULLSCREEN;
  1841. return new TextLayerBuilder({
  1842. textLayerDiv: textLayerDiv,
  1843. pageIndex: pageIndex,
  1844. viewport: viewport,
  1845. lastScrollSource: this,
  1846. isViewerInPresentationMode: isViewerInPresentationMode,
  1847. findController: this.findController
  1848. });
  1849. },
  1850. setFindController: function (findController) {
  1851. this.findController = findController;
  1852. },
  1853. };
  1854. return PDFViewer;
  1855. })();
  1856. var SimpleLinkService = (function SimpleLinkServiceClosure() {
  1857. function SimpleLinkService(pdfViewer) {
  1858. this.pdfViewer = pdfViewer;
  1859. }
  1860. SimpleLinkService.prototype = {
  1861. /**
  1862. * @returns {number}
  1863. */
  1864. get page() {
  1865. return this.pdfViewer.currentPageNumber;
  1866. },
  1867. /**
  1868. * @param {number} value
  1869. */
  1870. set page(value) {
  1871. this.pdfViewer.currentPageNumber = value;
  1872. },
  1873. /**
  1874. * @param dest - The PDF destination object.
  1875. */
  1876. navigateTo: function (dest) {},
  1877. /**
  1878. * @param dest - The PDF destination object.
  1879. * @returns {string} The hyperlink to the PDF object.
  1880. */
  1881. getDestinationHash: function (dest) {
  1882. return '#';
  1883. },
  1884. /**
  1885. * @param hash - The PDF parameters/hash.
  1886. * @returns {string} The hyperlink to the PDF object.
  1887. */
  1888. getAnchorUrl: function (hash) {
  1889. return '#';
  1890. },
  1891. /**
  1892. * @param {string} hash
  1893. */
  1894. setHash: function (hash) {},
  1895. /**
  1896. * @param {string} action
  1897. */
  1898. executeNamedAction: function (action) {},
  1899. };
  1900. return SimpleLinkService;
  1901. })();
  1902. /**
  1903. * PDFPage object source.
  1904. * @class
  1905. */
  1906. var PDFPageSource = (function PDFPageSourceClosure() {
  1907. /**
  1908. * @constructs
  1909. * @param {PDFDocument} pdfDocument
  1910. * @param {number} pageNumber
  1911. * @constructor
  1912. */
  1913. function PDFPageSource(pdfDocument, pageNumber) {
  1914. this.pdfDocument = pdfDocument;
  1915. this.pageNumber = pageNumber;
  1916. }
  1917. PDFPageSource.prototype = /** @lends PDFPageSource.prototype */ {
  1918. /**
  1919. * @returns {Promise<PDFPage>}
  1920. */
  1921. getPage: function () {
  1922. return this.pdfDocument.getPage(this.pageNumber);
  1923. }
  1924. };
  1925. return PDFPageSource;
  1926. })();
  1927. PDFJS.PDFViewer = PDFViewer;
  1928. }).call((typeof window === 'undefined') ? this : window);