pdf_viewer.js 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PagesCountLimit = exports.PDFViewer = exports.PDFPageViewBuffer = void 0;
  27. var _pdf = require("../pdf");
  28. var _ui_utils = require("./ui_utils.js");
  29. var _annotation_editor_layer_builder = require("./annotation_editor_layer_builder.js");
  30. var _annotation_layer_builder = require("./annotation_layer_builder.js");
  31. var _l10n_utils = require("./l10n_utils.js");
  32. var _pdf_page_view = require("./pdf_page_view.js");
  33. var _pdf_rendering_queue = require("./pdf_rendering_queue.js");
  34. var _pdf_link_service = require("./pdf_link_service.js");
  35. var _struct_tree_layer_builder = require("./struct_tree_layer_builder.js");
  36. var _text_highlighter = require("./text_highlighter.js");
  37. var _text_layer_builder = require("./text_layer_builder.js");
  38. var _xfa_layer_builder = require("./xfa_layer_builder.js");
  39. const DEFAULT_CACHE_SIZE = 10;
  40. const ENABLE_PERMISSIONS_CLASS = "enablePermissions";
  41. const PagesCountLimit = {
  42. FORCE_SCROLL_MODE_PAGE: 15000,
  43. FORCE_LAZY_PAGE_INIT: 7500,
  44. PAUSE_EAGER_PAGE_INIT: 250
  45. };
  46. exports.PagesCountLimit = PagesCountLimit;
  47. function isValidAnnotationEditorMode(mode) {
  48. return Object.values(_pdf.AnnotationEditorType).includes(mode) && mode !== _pdf.AnnotationEditorType.DISABLE;
  49. }
  50. class PDFPageViewBuffer {
  51. #buf = new Set();
  52. #size = 0;
  53. constructor(size) {
  54. this.#size = size;
  55. }
  56. push(view) {
  57. const buf = this.#buf;
  58. if (buf.has(view)) {
  59. buf.delete(view);
  60. }
  61. buf.add(view);
  62. if (buf.size > this.#size) {
  63. this.#destroyFirstView();
  64. }
  65. }
  66. resize(newSize, idsToKeep = null) {
  67. this.#size = newSize;
  68. const buf = this.#buf;
  69. if (idsToKeep) {
  70. const ii = buf.size;
  71. let i = 1;
  72. for (const view of buf) {
  73. if (idsToKeep.has(view.id)) {
  74. buf.delete(view);
  75. buf.add(view);
  76. }
  77. if (++i > ii) {
  78. break;
  79. }
  80. }
  81. }
  82. while (buf.size > this.#size) {
  83. this.#destroyFirstView();
  84. }
  85. }
  86. has(view) {
  87. return this.#buf.has(view);
  88. }
  89. [Symbol.iterator]() {
  90. return this.#buf.keys();
  91. }
  92. #destroyFirstView() {
  93. const firstView = this.#buf.keys().next().value;
  94. firstView?.destroy();
  95. this.#buf.delete(firstView);
  96. }
  97. }
  98. exports.PDFPageViewBuffer = PDFPageViewBuffer;
  99. class PDFViewer {
  100. #buffer = null;
  101. #annotationEditorMode = _pdf.AnnotationEditorType.NONE;
  102. #annotationEditorUIManager = null;
  103. #annotationMode = _pdf.AnnotationMode.ENABLE_FORMS;
  104. #enablePermissions = false;
  105. #previousContainerHeight = 0;
  106. #scrollModePageState = null;
  107. #onVisibilityChange = null;
  108. constructor(options) {
  109. const viewerVersion = '3.1.81';
  110. if (_pdf.version !== viewerVersion) {
  111. throw new Error(`The API version "${_pdf.version}" does not match the Viewer version "${viewerVersion}".`);
  112. }
  113. this.container = options.container;
  114. this.viewer = options.viewer || options.container.firstElementChild;
  115. if (!(this.container?.tagName.toUpperCase() === "DIV" && this.viewer?.tagName.toUpperCase() === "DIV")) {
  116. throw new Error("Invalid `container` and/or `viewer` option.");
  117. }
  118. if (this.container.offsetParent && getComputedStyle(this.container).position !== "absolute") {
  119. throw new Error("The `container` must be absolutely positioned.");
  120. }
  121. this.eventBus = options.eventBus;
  122. this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService();
  123. this.downloadManager = options.downloadManager || null;
  124. this.findController = options.findController || null;
  125. this._scriptingManager = options.scriptingManager || null;
  126. this.removePageBorders = options.removePageBorders || false;
  127. this.textLayerMode = options.textLayerMode ?? _ui_utils.TextLayerMode.ENABLE;
  128. this.#annotationMode = options.annotationMode ?? _pdf.AnnotationMode.ENABLE_FORMS;
  129. this.#annotationEditorMode = options.annotationEditorMode ?? _pdf.AnnotationEditorType.NONE;
  130. this.imageResourcesPath = options.imageResourcesPath || "";
  131. this.enablePrintAutoRotate = options.enablePrintAutoRotate || false;
  132. this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;
  133. this.useOnlyCssZoom = options.useOnlyCssZoom || false;
  134. this.maxCanvasPixels = options.maxCanvasPixels;
  135. this.l10n = options.l10n || _l10n_utils.NullL10n;
  136. this.#enablePermissions = options.enablePermissions || false;
  137. this.pageColors = options.pageColors || null;
  138. if (this.pageColors && !(CSS.supports("color", this.pageColors.background) && CSS.supports("color", this.pageColors.foreground))) {
  139. if (this.pageColors.background || this.pageColors.foreground) {
  140. console.warn("PDFViewer: Ignoring `pageColors`-option, since the browser doesn't support the values used.");
  141. }
  142. this.pageColors = null;
  143. }
  144. this.defaultRenderingQueue = !options.renderingQueue;
  145. if (this.defaultRenderingQueue) {
  146. this.renderingQueue = new _pdf_rendering_queue.PDFRenderingQueue();
  147. this.renderingQueue.setViewer(this);
  148. } else {
  149. this.renderingQueue = options.renderingQueue;
  150. }
  151. this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdate.bind(this));
  152. this.presentationModeState = _ui_utils.PresentationModeState.UNKNOWN;
  153. this._onBeforeDraw = this._onAfterDraw = null;
  154. this._resetView();
  155. if (this.removePageBorders) {
  156. this.viewer.classList.add("removePageBorders");
  157. }
  158. this.updateContainerHeightCss();
  159. }
  160. get pagesCount() {
  161. return this._pages.length;
  162. }
  163. getPageView(index) {
  164. return this._pages[index];
  165. }
  166. get pageViewsReady() {
  167. if (!this._pagesCapability.settled) {
  168. return false;
  169. }
  170. return this._pages.every(function (pageView) {
  171. return pageView?.pdfPage;
  172. });
  173. }
  174. get renderForms() {
  175. return this.#annotationMode === _pdf.AnnotationMode.ENABLE_FORMS;
  176. }
  177. get enableScripting() {
  178. return !!this._scriptingManager;
  179. }
  180. get currentPageNumber() {
  181. return this._currentPageNumber;
  182. }
  183. set currentPageNumber(val) {
  184. if (!Number.isInteger(val)) {
  185. throw new Error("Invalid page number.");
  186. }
  187. if (!this.pdfDocument) {
  188. return;
  189. }
  190. if (!this._setCurrentPageNumber(val, true)) {
  191. console.error(`currentPageNumber: "${val}" is not a valid page.`);
  192. }
  193. }
  194. _setCurrentPageNumber(val, resetCurrentPageView = false) {
  195. if (this._currentPageNumber === val) {
  196. if (resetCurrentPageView) {
  197. this.#resetCurrentPageView();
  198. }
  199. return true;
  200. }
  201. if (!(0 < val && val <= this.pagesCount)) {
  202. return false;
  203. }
  204. const previous = this._currentPageNumber;
  205. this._currentPageNumber = val;
  206. this.eventBus.dispatch("pagechanging", {
  207. source: this,
  208. pageNumber: val,
  209. pageLabel: this._pageLabels?.[val - 1] ?? null,
  210. previous
  211. });
  212. if (resetCurrentPageView) {
  213. this.#resetCurrentPageView();
  214. }
  215. return true;
  216. }
  217. get currentPageLabel() {
  218. return this._pageLabels?.[this._currentPageNumber - 1] ?? null;
  219. }
  220. set currentPageLabel(val) {
  221. if (!this.pdfDocument) {
  222. return;
  223. }
  224. let page = val | 0;
  225. if (this._pageLabels) {
  226. const i = this._pageLabels.indexOf(val);
  227. if (i >= 0) {
  228. page = i + 1;
  229. }
  230. }
  231. if (!this._setCurrentPageNumber(page, true)) {
  232. console.error(`currentPageLabel: "${val}" is not a valid page.`);
  233. }
  234. }
  235. get currentScale() {
  236. return this._currentScale !== _ui_utils.UNKNOWN_SCALE ? this._currentScale : _ui_utils.DEFAULT_SCALE;
  237. }
  238. set currentScale(val) {
  239. if (isNaN(val)) {
  240. throw new Error("Invalid numeric scale.");
  241. }
  242. if (!this.pdfDocument) {
  243. return;
  244. }
  245. this._setScale(val, false);
  246. }
  247. get currentScaleValue() {
  248. return this._currentScaleValue;
  249. }
  250. set currentScaleValue(val) {
  251. if (!this.pdfDocument) {
  252. return;
  253. }
  254. this._setScale(val, false);
  255. }
  256. get pagesRotation() {
  257. return this._pagesRotation;
  258. }
  259. set pagesRotation(rotation) {
  260. if (!(0, _ui_utils.isValidRotation)(rotation)) {
  261. throw new Error("Invalid pages rotation angle.");
  262. }
  263. if (!this.pdfDocument) {
  264. return;
  265. }
  266. rotation %= 360;
  267. if (rotation < 0) {
  268. rotation += 360;
  269. }
  270. if (this._pagesRotation === rotation) {
  271. return;
  272. }
  273. this._pagesRotation = rotation;
  274. const pageNumber = this._currentPageNumber;
  275. const updateArgs = {
  276. rotation
  277. };
  278. for (const pageView of this._pages) {
  279. pageView.update(updateArgs);
  280. }
  281. if (this._currentScaleValue) {
  282. this._setScale(this._currentScaleValue, true);
  283. }
  284. this.eventBus.dispatch("rotationchanging", {
  285. source: this,
  286. pagesRotation: rotation,
  287. pageNumber
  288. });
  289. if (this.defaultRenderingQueue) {
  290. this.update();
  291. }
  292. }
  293. get firstPagePromise() {
  294. return this.pdfDocument ? this._firstPageCapability.promise : null;
  295. }
  296. get onePageRendered() {
  297. return this.pdfDocument ? this._onePageRenderedCapability.promise : null;
  298. }
  299. get pagesPromise() {
  300. return this.pdfDocument ? this._pagesCapability.promise : null;
  301. }
  302. #initializePermissions(permissions) {
  303. const params = {
  304. annotationEditorMode: this.#annotationEditorMode,
  305. annotationMode: this.#annotationMode,
  306. textLayerMode: this.textLayerMode
  307. };
  308. if (!permissions) {
  309. return params;
  310. }
  311. if (!permissions.includes(_pdf.PermissionFlag.COPY)) {
  312. this.viewer.classList.add(ENABLE_PERMISSIONS_CLASS);
  313. }
  314. if (!permissions.includes(_pdf.PermissionFlag.MODIFY_CONTENTS)) {
  315. params.annotationEditorMode = _pdf.AnnotationEditorType.DISABLE;
  316. }
  317. if (!permissions.includes(_pdf.PermissionFlag.MODIFY_ANNOTATIONS) && !permissions.includes(_pdf.PermissionFlag.FILL_INTERACTIVE_FORMS) && this.#annotationMode === _pdf.AnnotationMode.ENABLE_FORMS) {
  318. params.annotationMode = _pdf.AnnotationMode.ENABLE;
  319. }
  320. return params;
  321. }
  322. #onePageRenderedOrForceFetch() {
  323. if (document.visibilityState === "hidden" || !this.container.offsetParent || this._getVisiblePages().views.length === 0) {
  324. return Promise.resolve();
  325. }
  326. const visibilityChangePromise = new Promise(resolve => {
  327. this.#onVisibilityChange = () => {
  328. if (document.visibilityState !== "hidden") {
  329. return;
  330. }
  331. resolve();
  332. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  333. this.#onVisibilityChange = null;
  334. };
  335. document.addEventListener("visibilitychange", this.#onVisibilityChange);
  336. });
  337. return Promise.race([this._onePageRenderedCapability.promise, visibilityChangePromise]);
  338. }
  339. setDocument(pdfDocument) {
  340. if (this.pdfDocument) {
  341. this.eventBus.dispatch("pagesdestroy", {
  342. source: this
  343. });
  344. this._cancelRendering();
  345. this._resetView();
  346. this.findController?.setDocument(null);
  347. this._scriptingManager?.setDocument(null);
  348. if (this.#annotationEditorUIManager) {
  349. this.#annotationEditorUIManager.destroy();
  350. this.#annotationEditorUIManager = null;
  351. }
  352. }
  353. this.pdfDocument = pdfDocument;
  354. if (!pdfDocument) {
  355. return;
  356. }
  357. const isPureXfa = pdfDocument.isPureXfa;
  358. const pagesCount = pdfDocument.numPages;
  359. const firstPagePromise = pdfDocument.getPage(1);
  360. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();
  361. const permissionsPromise = this.#enablePermissions ? pdfDocument.getPermissions() : Promise.resolve();
  362. if (pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  363. console.warn("Forcing PAGE-scrolling for performance reasons, given the length of the document.");
  364. const mode = this._scrollMode = _ui_utils.ScrollMode.PAGE;
  365. this.eventBus.dispatch("scrollmodechanged", {
  366. source: this,
  367. mode
  368. });
  369. }
  370. this._pagesCapability.promise.then(() => {
  371. this.eventBus.dispatch("pagesloaded", {
  372. source: this,
  373. pagesCount
  374. });
  375. }, () => {});
  376. this._onBeforeDraw = evt => {
  377. const pageView = this._pages[evt.pageNumber - 1];
  378. if (!pageView) {
  379. return;
  380. }
  381. this.#buffer.push(pageView);
  382. };
  383. this.eventBus._on("pagerender", this._onBeforeDraw);
  384. this._onAfterDraw = evt => {
  385. if (evt.cssTransform || this._onePageRenderedCapability.settled) {
  386. return;
  387. }
  388. this._onePageRenderedCapability.resolve({
  389. timestamp: evt.timestamp
  390. });
  391. this.eventBus._off("pagerendered", this._onAfterDraw);
  392. this._onAfterDraw = null;
  393. if (this.#onVisibilityChange) {
  394. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  395. this.#onVisibilityChange = null;
  396. }
  397. };
  398. this.eventBus._on("pagerendered", this._onAfterDraw);
  399. Promise.all([firstPagePromise, permissionsPromise]).then(([firstPdfPage, permissions]) => {
  400. if (pdfDocument !== this.pdfDocument) {
  401. return;
  402. }
  403. this._firstPageCapability.resolve(firstPdfPage);
  404. this._optionalContentConfigPromise = optionalContentConfigPromise;
  405. const {
  406. annotationEditorMode,
  407. annotationMode,
  408. textLayerMode
  409. } = this.#initializePermissions(permissions);
  410. if (annotationEditorMode !== _pdf.AnnotationEditorType.DISABLE) {
  411. const mode = annotationEditorMode;
  412. if (isPureXfa) {
  413. console.warn("Warning: XFA-editing is not implemented.");
  414. } else if (isValidAnnotationEditorMode(mode)) {
  415. this.#annotationEditorUIManager = new _pdf.AnnotationEditorUIManager(this.container, this.eventBus);
  416. if (mode !== _pdf.AnnotationEditorType.NONE) {
  417. this.#annotationEditorUIManager.updateMode(mode);
  418. }
  419. } else {
  420. console.error(`Invalid AnnotationEditor mode: ${mode}`);
  421. }
  422. }
  423. const viewerElement = this._scrollMode === _ui_utils.ScrollMode.PAGE ? null : this.viewer;
  424. const scale = this.currentScale;
  425. const viewport = firstPdfPage.getViewport({
  426. scale: scale * _pdf.PixelsPerInch.PDF_TO_CSS_UNITS
  427. });
  428. const textLayerFactory = textLayerMode !== _ui_utils.TextLayerMode.DISABLE && !isPureXfa ? this : null;
  429. const annotationLayerFactory = annotationMode !== _pdf.AnnotationMode.DISABLE ? this : null;
  430. const xfaLayerFactory = isPureXfa ? this : null;
  431. const annotationEditorLayerFactory = this.#annotationEditorUIManager ? this : null;
  432. for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
  433. const pageView = new _pdf_page_view.PDFPageView({
  434. container: viewerElement,
  435. eventBus: this.eventBus,
  436. id: pageNum,
  437. scale,
  438. defaultViewport: viewport.clone(),
  439. optionalContentConfigPromise,
  440. renderingQueue: this.renderingQueue,
  441. textLayerFactory,
  442. textLayerMode,
  443. annotationLayerFactory,
  444. annotationMode,
  445. xfaLayerFactory,
  446. annotationEditorLayerFactory,
  447. textHighlighterFactory: this,
  448. structTreeLayerFactory: this,
  449. imageResourcesPath: this.imageResourcesPath,
  450. renderer: this.renderer,
  451. useOnlyCssZoom: this.useOnlyCssZoom,
  452. maxCanvasPixels: this.maxCanvasPixels,
  453. pageColors: this.pageColors,
  454. l10n: this.l10n
  455. });
  456. this._pages.push(pageView);
  457. }
  458. const firstPageView = this._pages[0];
  459. if (firstPageView) {
  460. firstPageView.setPdfPage(firstPdfPage);
  461. this.linkService.cachePageRef(1, firstPdfPage.ref);
  462. }
  463. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  464. this.#ensurePageViewVisible();
  465. } else if (this._spreadMode !== _ui_utils.SpreadMode.NONE) {
  466. this._updateSpreadMode();
  467. }
  468. this.#onePageRenderedOrForceFetch().then(async () => {
  469. this.findController?.setDocument(pdfDocument);
  470. this._scriptingManager?.setDocument(pdfDocument);
  471. if (this.#annotationEditorUIManager) {
  472. this.eventBus.dispatch("annotationeditormodechanged", {
  473. source: this,
  474. mode: this.#annotationEditorMode
  475. });
  476. }
  477. if (pdfDocument.loadingParams.disableAutoFetch || pagesCount > PagesCountLimit.FORCE_LAZY_PAGE_INIT) {
  478. this._pagesCapability.resolve();
  479. return;
  480. }
  481. let getPagesLeft = pagesCount - 1;
  482. if (getPagesLeft <= 0) {
  483. this._pagesCapability.resolve();
  484. return;
  485. }
  486. for (let pageNum = 2; pageNum <= pagesCount; ++pageNum) {
  487. const promise = pdfDocument.getPage(pageNum).then(pdfPage => {
  488. const pageView = this._pages[pageNum - 1];
  489. if (!pageView.pdfPage) {
  490. pageView.setPdfPage(pdfPage);
  491. }
  492. this.linkService.cachePageRef(pageNum, pdfPage.ref);
  493. if (--getPagesLeft === 0) {
  494. this._pagesCapability.resolve();
  495. }
  496. }, reason => {
  497. console.error(`Unable to get page ${pageNum} to initialize viewer`, reason);
  498. if (--getPagesLeft === 0) {
  499. this._pagesCapability.resolve();
  500. }
  501. });
  502. if (pageNum % PagesCountLimit.PAUSE_EAGER_PAGE_INIT === 0) {
  503. await promise;
  504. }
  505. }
  506. });
  507. this.eventBus.dispatch("pagesinit", {
  508. source: this
  509. });
  510. pdfDocument.getMetadata().then(({
  511. info
  512. }) => {
  513. if (pdfDocument !== this.pdfDocument) {
  514. return;
  515. }
  516. if (info.Language) {
  517. this.viewer.lang = info.Language;
  518. }
  519. });
  520. if (this.defaultRenderingQueue) {
  521. this.update();
  522. }
  523. }).catch(reason => {
  524. console.error("Unable to initialize viewer", reason);
  525. this._pagesCapability.reject(reason);
  526. });
  527. }
  528. setPageLabels(labels) {
  529. if (!this.pdfDocument) {
  530. return;
  531. }
  532. if (!labels) {
  533. this._pageLabels = null;
  534. } else if (!(Array.isArray(labels) && this.pdfDocument.numPages === labels.length)) {
  535. this._pageLabels = null;
  536. console.error(`setPageLabels: Invalid page labels.`);
  537. } else {
  538. this._pageLabels = labels;
  539. }
  540. for (let i = 0, ii = this._pages.length; i < ii; i++) {
  541. this._pages[i].setPageLabel(this._pageLabels?.[i] ?? null);
  542. }
  543. }
  544. _resetView() {
  545. this._pages = [];
  546. this._currentPageNumber = 1;
  547. this._currentScale = _ui_utils.UNKNOWN_SCALE;
  548. this._currentScaleValue = null;
  549. this._pageLabels = null;
  550. this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
  551. this._location = null;
  552. this._pagesRotation = 0;
  553. this._optionalContentConfigPromise = null;
  554. this._firstPageCapability = (0, _pdf.createPromiseCapability)();
  555. this._onePageRenderedCapability = (0, _pdf.createPromiseCapability)();
  556. this._pagesCapability = (0, _pdf.createPromiseCapability)();
  557. this._scrollMode = _ui_utils.ScrollMode.VERTICAL;
  558. this._previousScrollMode = _ui_utils.ScrollMode.UNKNOWN;
  559. this._spreadMode = _ui_utils.SpreadMode.NONE;
  560. this.#scrollModePageState = {
  561. previousPageNumber: 1,
  562. scrollDown: true,
  563. pages: []
  564. };
  565. if (this._onBeforeDraw) {
  566. this.eventBus._off("pagerender", this._onBeforeDraw);
  567. this._onBeforeDraw = null;
  568. }
  569. if (this._onAfterDraw) {
  570. this.eventBus._off("pagerendered", this._onAfterDraw);
  571. this._onAfterDraw = null;
  572. }
  573. if (this.#onVisibilityChange) {
  574. document.removeEventListener("visibilitychange", this.#onVisibilityChange);
  575. this.#onVisibilityChange = null;
  576. }
  577. this.viewer.textContent = "";
  578. this._updateScrollMode();
  579. this.viewer.removeAttribute("lang");
  580. this.viewer.classList.remove(ENABLE_PERMISSIONS_CLASS);
  581. }
  582. #ensurePageViewVisible() {
  583. if (this._scrollMode !== _ui_utils.ScrollMode.PAGE) {
  584. throw new Error("#ensurePageViewVisible: Invalid scrollMode value.");
  585. }
  586. const pageNumber = this._currentPageNumber,
  587. state = this.#scrollModePageState,
  588. viewer = this.viewer;
  589. viewer.textContent = "";
  590. state.pages.length = 0;
  591. if (this._spreadMode === _ui_utils.SpreadMode.NONE && !this.isInPresentationMode) {
  592. const pageView = this._pages[pageNumber - 1];
  593. viewer.append(pageView.div);
  594. state.pages.push(pageView);
  595. } else {
  596. const pageIndexSet = new Set(),
  597. parity = this._spreadMode - 1;
  598. if (parity === -1) {
  599. pageIndexSet.add(pageNumber - 1);
  600. } else if (pageNumber % 2 !== parity) {
  601. pageIndexSet.add(pageNumber - 1);
  602. pageIndexSet.add(pageNumber);
  603. } else {
  604. pageIndexSet.add(pageNumber - 2);
  605. pageIndexSet.add(pageNumber - 1);
  606. }
  607. const spread = document.createElement("div");
  608. spread.className = "spread";
  609. if (this.isInPresentationMode) {
  610. const dummyPage = document.createElement("div");
  611. dummyPage.className = "dummyPage";
  612. spread.append(dummyPage);
  613. }
  614. for (const i of pageIndexSet) {
  615. const pageView = this._pages[i];
  616. if (!pageView) {
  617. continue;
  618. }
  619. spread.append(pageView.div);
  620. state.pages.push(pageView);
  621. }
  622. viewer.append(spread);
  623. }
  624. state.scrollDown = pageNumber >= state.previousPageNumber;
  625. state.previousPageNumber = pageNumber;
  626. }
  627. _scrollUpdate() {
  628. if (this.pagesCount === 0) {
  629. return;
  630. }
  631. this.update();
  632. }
  633. #scrollIntoView(pageView, pageSpot = null) {
  634. const {
  635. div,
  636. id
  637. } = pageView;
  638. if (this._currentPageNumber !== id) {
  639. this._setCurrentPageNumber(id);
  640. }
  641. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  642. this.#ensurePageViewVisible();
  643. this.update();
  644. }
  645. if (!pageSpot && !this.isInPresentationMode) {
  646. const left = div.offsetLeft + div.clientLeft,
  647. right = left + div.clientWidth;
  648. const {
  649. scrollLeft,
  650. clientWidth
  651. } = this.container;
  652. if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL || left < scrollLeft || right > scrollLeft + clientWidth) {
  653. pageSpot = {
  654. left: 0,
  655. top: 0
  656. };
  657. }
  658. }
  659. (0, _ui_utils.scrollIntoView)(div, pageSpot);
  660. if (!this._currentScaleValue && this._location) {
  661. this._location = null;
  662. }
  663. }
  664. #isSameScale(newScale) {
  665. return newScale === this._currentScale || Math.abs(newScale - this._currentScale) < 1e-15;
  666. }
  667. _setScaleUpdatePages(newScale, newValue, noScroll = false, preset = false) {
  668. this._currentScaleValue = newValue.toString();
  669. if (this.#isSameScale(newScale)) {
  670. if (preset) {
  671. this.eventBus.dispatch("scalechanging", {
  672. source: this,
  673. scale: newScale,
  674. presetValue: newValue
  675. });
  676. }
  677. return;
  678. }
  679. _ui_utils.docStyle.setProperty("--scale-factor", newScale * _pdf.PixelsPerInch.PDF_TO_CSS_UNITS);
  680. const updateArgs = {
  681. scale: newScale
  682. };
  683. for (const pageView of this._pages) {
  684. pageView.update(updateArgs);
  685. }
  686. this._currentScale = newScale;
  687. if (!noScroll) {
  688. let page = this._currentPageNumber,
  689. dest;
  690. if (this._location && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
  691. page = this._location.pageNumber;
  692. dest = [null, {
  693. name: "XYZ"
  694. }, this._location.left, this._location.top, null];
  695. }
  696. this.scrollPageIntoView({
  697. pageNumber: page,
  698. destArray: dest,
  699. allowNegativeOffset: true
  700. });
  701. }
  702. this.eventBus.dispatch("scalechanging", {
  703. source: this,
  704. scale: newScale,
  705. presetValue: preset ? newValue : undefined
  706. });
  707. if (this.defaultRenderingQueue) {
  708. this.update();
  709. }
  710. this.updateContainerHeightCss();
  711. }
  712. get _pageWidthScaleFactor() {
  713. if (this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL) {
  714. return 2;
  715. }
  716. return 1;
  717. }
  718. _setScale(value, noScroll = false) {
  719. let scale = parseFloat(value);
  720. if (scale > 0) {
  721. this._setScaleUpdatePages(scale, value, noScroll, false);
  722. } else {
  723. const currentPage = this._pages[this._currentPageNumber - 1];
  724. if (!currentPage) {
  725. return;
  726. }
  727. let hPadding = _ui_utils.SCROLLBAR_PADDING,
  728. vPadding = _ui_utils.VERTICAL_PADDING;
  729. if (this.isInPresentationMode) {
  730. hPadding = vPadding = 4;
  731. } else if (this.removePageBorders) {
  732. hPadding = vPadding = 0;
  733. } else if (this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL) {
  734. [hPadding, vPadding] = [vPadding, hPadding];
  735. }
  736. const pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale / this._pageWidthScaleFactor;
  737. const pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
  738. switch (value) {
  739. case "page-actual":
  740. scale = 1;
  741. break;
  742. case "page-width":
  743. scale = pageWidthScale;
  744. break;
  745. case "page-height":
  746. scale = pageHeightScale;
  747. break;
  748. case "page-fit":
  749. scale = Math.min(pageWidthScale, pageHeightScale);
  750. break;
  751. case "auto":
  752. const horizontalScale = (0, _ui_utils.isPortraitOrientation)(currentPage) ? pageWidthScale : Math.min(pageHeightScale, pageWidthScale);
  753. scale = Math.min(_ui_utils.MAX_AUTO_SCALE, horizontalScale);
  754. break;
  755. default:
  756. console.error(`_setScale: "${value}" is an unknown zoom value.`);
  757. return;
  758. }
  759. this._setScaleUpdatePages(scale, value, noScroll, true);
  760. }
  761. }
  762. #resetCurrentPageView() {
  763. const pageView = this._pages[this._currentPageNumber - 1];
  764. if (this.isInPresentationMode) {
  765. this._setScale(this._currentScaleValue, true);
  766. }
  767. this.#scrollIntoView(pageView);
  768. }
  769. pageLabelToPageNumber(label) {
  770. if (!this._pageLabels) {
  771. return null;
  772. }
  773. const i = this._pageLabels.indexOf(label);
  774. if (i < 0) {
  775. return null;
  776. }
  777. return i + 1;
  778. }
  779. scrollPageIntoView({
  780. pageNumber,
  781. destArray = null,
  782. allowNegativeOffset = false,
  783. ignoreDestinationZoom = false
  784. }) {
  785. if (!this.pdfDocument) {
  786. return;
  787. }
  788. const pageView = Number.isInteger(pageNumber) && this._pages[pageNumber - 1];
  789. if (!pageView) {
  790. console.error(`scrollPageIntoView: "${pageNumber}" is not a valid pageNumber parameter.`);
  791. return;
  792. }
  793. if (this.isInPresentationMode || !destArray) {
  794. this._setCurrentPageNumber(pageNumber, true);
  795. return;
  796. }
  797. let x = 0,
  798. y = 0;
  799. let width = 0,
  800. height = 0,
  801. widthScale,
  802. heightScale;
  803. const changeOrientation = pageView.rotation % 180 !== 0;
  804. const pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / _pdf.PixelsPerInch.PDF_TO_CSS_UNITS;
  805. const pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / _pdf.PixelsPerInch.PDF_TO_CSS_UNITS;
  806. let scale = 0;
  807. switch (destArray[1].name) {
  808. case "XYZ":
  809. x = destArray[2];
  810. y = destArray[3];
  811. scale = destArray[4];
  812. x = x !== null ? x : 0;
  813. y = y !== null ? y : pageHeight;
  814. break;
  815. case "Fit":
  816. case "FitB":
  817. scale = "page-fit";
  818. break;
  819. case "FitH":
  820. case "FitBH":
  821. y = destArray[2];
  822. scale = "page-width";
  823. if (y === null && this._location) {
  824. x = this._location.left;
  825. y = this._location.top;
  826. } else if (typeof y !== "number" || y < 0) {
  827. y = pageHeight;
  828. }
  829. break;
  830. case "FitV":
  831. case "FitBV":
  832. x = destArray[2];
  833. width = pageWidth;
  834. height = pageHeight;
  835. scale = "page-height";
  836. break;
  837. case "FitR":
  838. x = destArray[2];
  839. y = destArray[3];
  840. width = destArray[4] - x;
  841. height = destArray[5] - y;
  842. const hPadding = this.removePageBorders ? 0 : _ui_utils.SCROLLBAR_PADDING;
  843. const vPadding = this.removePageBorders ? 0 : _ui_utils.VERTICAL_PADDING;
  844. widthScale = (this.container.clientWidth - hPadding) / width / _pdf.PixelsPerInch.PDF_TO_CSS_UNITS;
  845. heightScale = (this.container.clientHeight - vPadding) / height / _pdf.PixelsPerInch.PDF_TO_CSS_UNITS;
  846. scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
  847. break;
  848. default:
  849. console.error(`scrollPageIntoView: "${destArray[1].name}" is not a valid destination type.`);
  850. return;
  851. }
  852. if (!ignoreDestinationZoom) {
  853. if (scale && scale !== this._currentScale) {
  854. this.currentScaleValue = scale;
  855. } else if (this._currentScale === _ui_utils.UNKNOWN_SCALE) {
  856. this.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
  857. }
  858. }
  859. if (scale === "page-fit" && !destArray[4]) {
  860. this.#scrollIntoView(pageView);
  861. return;
  862. }
  863. const boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)];
  864. let left = Math.min(boundingRect[0][0], boundingRect[1][0]);
  865. let top = Math.min(boundingRect[0][1], boundingRect[1][1]);
  866. if (!allowNegativeOffset) {
  867. left = Math.max(left, 0);
  868. top = Math.max(top, 0);
  869. }
  870. this.#scrollIntoView(pageView, {
  871. left,
  872. top
  873. });
  874. }
  875. _updateLocation(firstPage) {
  876. const currentScale = this._currentScale;
  877. const currentScaleValue = this._currentScaleValue;
  878. const normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
  879. const pageNumber = firstPage.id;
  880. const currentPageView = this._pages[pageNumber - 1];
  881. const container = this.container;
  882. const topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
  883. const intLeft = Math.round(topLeft[0]);
  884. const intTop = Math.round(topLeft[1]);
  885. let pdfOpenParams = `#page=${pageNumber}`;
  886. if (!this.isInPresentationMode) {
  887. pdfOpenParams += `&zoom=${normalizedScaleValue},${intLeft},${intTop}`;
  888. }
  889. this._location = {
  890. pageNumber,
  891. scale: normalizedScaleValue,
  892. top: intTop,
  893. left: intLeft,
  894. rotation: this._pagesRotation,
  895. pdfOpenParams
  896. };
  897. }
  898. update() {
  899. const visible = this._getVisiblePages();
  900. const visiblePages = visible.views,
  901. numVisiblePages = visiblePages.length;
  902. if (numVisiblePages === 0) {
  903. return;
  904. }
  905. const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1);
  906. this.#buffer.resize(newCacheSize, visible.ids);
  907. this.renderingQueue.renderHighestPriority(visible);
  908. const isSimpleLayout = this._spreadMode === _ui_utils.SpreadMode.NONE && (this._scrollMode === _ui_utils.ScrollMode.PAGE || this._scrollMode === _ui_utils.ScrollMode.VERTICAL);
  909. const currentId = this._currentPageNumber;
  910. let stillFullyVisible = false;
  911. for (const page of visiblePages) {
  912. if (page.percent < 100) {
  913. break;
  914. }
  915. if (page.id === currentId && isSimpleLayout) {
  916. stillFullyVisible = true;
  917. break;
  918. }
  919. }
  920. this._setCurrentPageNumber(stillFullyVisible ? currentId : visiblePages[0].id);
  921. this._updateLocation(visible.first);
  922. this.eventBus.dispatch("updateviewarea", {
  923. source: this,
  924. location: this._location
  925. });
  926. }
  927. containsElement(element) {
  928. return this.container.contains(element);
  929. }
  930. focus() {
  931. this.container.focus();
  932. }
  933. get _isContainerRtl() {
  934. return getComputedStyle(this.container).direction === "rtl";
  935. }
  936. get isInPresentationMode() {
  937. return this.presentationModeState === _ui_utils.PresentationModeState.FULLSCREEN;
  938. }
  939. get isChangingPresentationMode() {
  940. return this.presentationModeState === _ui_utils.PresentationModeState.CHANGING;
  941. }
  942. get isHorizontalScrollbarEnabled() {
  943. return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
  944. }
  945. get isVerticalScrollbarEnabled() {
  946. return this.isInPresentationMode ? false : this.container.scrollHeight > this.container.clientHeight;
  947. }
  948. _getVisiblePages() {
  949. const views = this._scrollMode === _ui_utils.ScrollMode.PAGE ? this.#scrollModePageState.pages : this._pages,
  950. horizontal = this._scrollMode === _ui_utils.ScrollMode.HORIZONTAL,
  951. rtl = horizontal && this._isContainerRtl;
  952. return (0, _ui_utils.getVisibleElements)({
  953. scrollEl: this.container,
  954. views,
  955. sortByVisibility: true,
  956. horizontal,
  957. rtl
  958. });
  959. }
  960. isPageVisible(pageNumber) {
  961. if (!this.pdfDocument) {
  962. return false;
  963. }
  964. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  965. console.error(`isPageVisible: "${pageNumber}" is not a valid page.`);
  966. return false;
  967. }
  968. return this._getVisiblePages().ids.has(pageNumber);
  969. }
  970. isPageCached(pageNumber) {
  971. if (!this.pdfDocument) {
  972. return false;
  973. }
  974. if (!(Number.isInteger(pageNumber) && pageNumber > 0 && pageNumber <= this.pagesCount)) {
  975. console.error(`isPageCached: "${pageNumber}" is not a valid page.`);
  976. return false;
  977. }
  978. const pageView = this._pages[pageNumber - 1];
  979. return this.#buffer.has(pageView);
  980. }
  981. cleanup() {
  982. for (const pageView of this._pages) {
  983. if (pageView.renderingState !== _ui_utils.RenderingStates.FINISHED) {
  984. pageView.reset();
  985. }
  986. }
  987. }
  988. _cancelRendering() {
  989. for (const pageView of this._pages) {
  990. pageView.cancelRendering();
  991. }
  992. }
  993. async #ensurePdfPageLoaded(pageView) {
  994. if (pageView.pdfPage) {
  995. return pageView.pdfPage;
  996. }
  997. try {
  998. const pdfPage = await this.pdfDocument.getPage(pageView.id);
  999. if (!pageView.pdfPage) {
  1000. pageView.setPdfPage(pdfPage);
  1001. }
  1002. if (!this.linkService._cachedPageNumber?.(pdfPage.ref)) {
  1003. this.linkService.cachePageRef(pageView.id, pdfPage.ref);
  1004. }
  1005. return pdfPage;
  1006. } catch (reason) {
  1007. console.error("Unable to get page for page view", reason);
  1008. return null;
  1009. }
  1010. }
  1011. #getScrollAhead(visible) {
  1012. if (visible.first?.id === 1) {
  1013. return true;
  1014. } else if (visible.last?.id === this.pagesCount) {
  1015. return false;
  1016. }
  1017. switch (this._scrollMode) {
  1018. case _ui_utils.ScrollMode.PAGE:
  1019. return this.#scrollModePageState.scrollDown;
  1020. case _ui_utils.ScrollMode.HORIZONTAL:
  1021. return this.scroll.right;
  1022. }
  1023. return this.scroll.down;
  1024. }
  1025. #toggleLoadingIconSpinner(visibleIds) {
  1026. for (const id of visibleIds) {
  1027. const pageView = this._pages[id - 1];
  1028. pageView?.toggleLoadingIconSpinner(true);
  1029. }
  1030. for (const pageView of this.#buffer) {
  1031. if (visibleIds.has(pageView.id)) {
  1032. continue;
  1033. }
  1034. pageView.toggleLoadingIconSpinner(false);
  1035. }
  1036. }
  1037. forceRendering(currentlyVisiblePages) {
  1038. const visiblePages = currentlyVisiblePages || this._getVisiblePages();
  1039. const scrollAhead = this.#getScrollAhead(visiblePages);
  1040. const preRenderExtra = this._spreadMode !== _ui_utils.SpreadMode.NONE && this._scrollMode !== _ui_utils.ScrollMode.HORIZONTAL;
  1041. const pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, scrollAhead, preRenderExtra);
  1042. this.#toggleLoadingIconSpinner(visiblePages.ids);
  1043. if (pageView) {
  1044. this.#ensurePdfPageLoaded(pageView).then(() => {
  1045. this.renderingQueue.renderView(pageView);
  1046. });
  1047. return true;
  1048. }
  1049. return false;
  1050. }
  1051. createTextLayerBuilder({
  1052. textLayerDiv,
  1053. pageIndex,
  1054. viewport,
  1055. eventBus,
  1056. highlighter,
  1057. accessibilityManager = null
  1058. }) {
  1059. return new _text_layer_builder.TextLayerBuilder({
  1060. textLayerDiv,
  1061. eventBus,
  1062. pageIndex,
  1063. viewport,
  1064. highlighter,
  1065. accessibilityManager
  1066. });
  1067. }
  1068. createTextHighlighter({
  1069. pageIndex,
  1070. eventBus
  1071. }) {
  1072. return new _text_highlighter.TextHighlighter({
  1073. eventBus,
  1074. pageIndex,
  1075. findController: this.isInPresentationMode ? null : this.findController
  1076. });
  1077. }
  1078. createAnnotationLayerBuilder({
  1079. pageDiv,
  1080. pdfPage,
  1081. annotationStorage = this.pdfDocument?.annotationStorage,
  1082. imageResourcesPath = "",
  1083. renderForms = true,
  1084. l10n = _l10n_utils.NullL10n,
  1085. enableScripting = this.enableScripting,
  1086. hasJSActionsPromise = this.pdfDocument?.hasJSActions(),
  1087. mouseState = this._scriptingManager?.mouseState,
  1088. fieldObjectsPromise = this.pdfDocument?.getFieldObjects(),
  1089. annotationCanvasMap = null,
  1090. accessibilityManager = null
  1091. }) {
  1092. return new _annotation_layer_builder.AnnotationLayerBuilder({
  1093. pageDiv,
  1094. pdfPage,
  1095. annotationStorage,
  1096. imageResourcesPath,
  1097. renderForms,
  1098. linkService: this.linkService,
  1099. downloadManager: this.downloadManager,
  1100. l10n,
  1101. enableScripting,
  1102. hasJSActionsPromise,
  1103. mouseState,
  1104. fieldObjectsPromise,
  1105. annotationCanvasMap,
  1106. accessibilityManager
  1107. });
  1108. }
  1109. createAnnotationEditorLayerBuilder({
  1110. uiManager = this.#annotationEditorUIManager,
  1111. pageDiv,
  1112. pdfPage,
  1113. accessibilityManager = null,
  1114. l10n,
  1115. annotationStorage = this.pdfDocument?.annotationStorage
  1116. }) {
  1117. return new _annotation_editor_layer_builder.AnnotationEditorLayerBuilder({
  1118. uiManager,
  1119. pageDiv,
  1120. pdfPage,
  1121. annotationStorage,
  1122. accessibilityManager,
  1123. l10n
  1124. });
  1125. }
  1126. createXfaLayerBuilder({
  1127. pageDiv,
  1128. pdfPage,
  1129. annotationStorage = this.pdfDocument?.annotationStorage
  1130. }) {
  1131. return new _xfa_layer_builder.XfaLayerBuilder({
  1132. pageDiv,
  1133. pdfPage,
  1134. annotationStorage,
  1135. linkService: this.linkService
  1136. });
  1137. }
  1138. createStructTreeLayerBuilder({
  1139. pdfPage
  1140. }) {
  1141. return new _struct_tree_layer_builder.StructTreeLayerBuilder({
  1142. pdfPage
  1143. });
  1144. }
  1145. get hasEqualPageSizes() {
  1146. const firstPageView = this._pages[0];
  1147. for (let i = 1, ii = this._pages.length; i < ii; ++i) {
  1148. const pageView = this._pages[i];
  1149. if (pageView.width !== firstPageView.width || pageView.height !== firstPageView.height) {
  1150. return false;
  1151. }
  1152. }
  1153. return true;
  1154. }
  1155. getPagesOverview() {
  1156. return this._pages.map(pageView => {
  1157. const viewport = pageView.pdfPage.getViewport({
  1158. scale: 1
  1159. });
  1160. if (!this.enablePrintAutoRotate || (0, _ui_utils.isPortraitOrientation)(viewport)) {
  1161. return {
  1162. width: viewport.width,
  1163. height: viewport.height,
  1164. rotation: viewport.rotation
  1165. };
  1166. }
  1167. return {
  1168. width: viewport.height,
  1169. height: viewport.width,
  1170. rotation: (viewport.rotation - 90) % 360
  1171. };
  1172. });
  1173. }
  1174. get optionalContentConfigPromise() {
  1175. if (!this.pdfDocument) {
  1176. return Promise.resolve(null);
  1177. }
  1178. if (!this._optionalContentConfigPromise) {
  1179. console.error("optionalContentConfigPromise: Not initialized yet.");
  1180. return this.pdfDocument.getOptionalContentConfig();
  1181. }
  1182. return this._optionalContentConfigPromise;
  1183. }
  1184. set optionalContentConfigPromise(promise) {
  1185. if (!(promise instanceof Promise)) {
  1186. throw new Error(`Invalid optionalContentConfigPromise: ${promise}`);
  1187. }
  1188. if (!this.pdfDocument) {
  1189. return;
  1190. }
  1191. if (!this._optionalContentConfigPromise) {
  1192. return;
  1193. }
  1194. this._optionalContentConfigPromise = promise;
  1195. const updateArgs = {
  1196. optionalContentConfigPromise: promise
  1197. };
  1198. for (const pageView of this._pages) {
  1199. pageView.update(updateArgs);
  1200. }
  1201. this.update();
  1202. this.eventBus.dispatch("optionalcontentconfigchanged", {
  1203. source: this,
  1204. promise
  1205. });
  1206. }
  1207. get scrollMode() {
  1208. return this._scrollMode;
  1209. }
  1210. set scrollMode(mode) {
  1211. if (this._scrollMode === mode) {
  1212. return;
  1213. }
  1214. if (!(0, _ui_utils.isValidScrollMode)(mode)) {
  1215. throw new Error(`Invalid scroll mode: ${mode}`);
  1216. }
  1217. if (this.pagesCount > PagesCountLimit.FORCE_SCROLL_MODE_PAGE) {
  1218. return;
  1219. }
  1220. this._previousScrollMode = this._scrollMode;
  1221. this._scrollMode = mode;
  1222. this.eventBus.dispatch("scrollmodechanged", {
  1223. source: this,
  1224. mode
  1225. });
  1226. this._updateScrollMode(this._currentPageNumber);
  1227. }
  1228. _updateScrollMode(pageNumber = null) {
  1229. const scrollMode = this._scrollMode,
  1230. viewer = this.viewer;
  1231. viewer.classList.toggle("scrollHorizontal", scrollMode === _ui_utils.ScrollMode.HORIZONTAL);
  1232. viewer.classList.toggle("scrollWrapped", scrollMode === _ui_utils.ScrollMode.WRAPPED);
  1233. if (!this.pdfDocument || !pageNumber) {
  1234. return;
  1235. }
  1236. if (scrollMode === _ui_utils.ScrollMode.PAGE) {
  1237. this.#ensurePageViewVisible();
  1238. } else if (this._previousScrollMode === _ui_utils.ScrollMode.PAGE) {
  1239. this._updateSpreadMode();
  1240. }
  1241. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  1242. this._setScale(this._currentScaleValue, true);
  1243. }
  1244. this._setCurrentPageNumber(pageNumber, true);
  1245. this.update();
  1246. }
  1247. get spreadMode() {
  1248. return this._spreadMode;
  1249. }
  1250. set spreadMode(mode) {
  1251. if (this._spreadMode === mode) {
  1252. return;
  1253. }
  1254. if (!(0, _ui_utils.isValidSpreadMode)(mode)) {
  1255. throw new Error(`Invalid spread mode: ${mode}`);
  1256. }
  1257. this._spreadMode = mode;
  1258. this.eventBus.dispatch("spreadmodechanged", {
  1259. source: this,
  1260. mode
  1261. });
  1262. this._updateSpreadMode(this._currentPageNumber);
  1263. }
  1264. _updateSpreadMode(pageNumber = null) {
  1265. if (!this.pdfDocument) {
  1266. return;
  1267. }
  1268. const viewer = this.viewer,
  1269. pages = this._pages;
  1270. if (this._scrollMode === _ui_utils.ScrollMode.PAGE) {
  1271. this.#ensurePageViewVisible();
  1272. } else {
  1273. viewer.textContent = "";
  1274. if (this._spreadMode === _ui_utils.SpreadMode.NONE) {
  1275. for (const pageView of this._pages) {
  1276. viewer.append(pageView.div);
  1277. }
  1278. } else {
  1279. const parity = this._spreadMode - 1;
  1280. let spread = null;
  1281. for (let i = 0, ii = pages.length; i < ii; ++i) {
  1282. if (spread === null) {
  1283. spread = document.createElement("div");
  1284. spread.className = "spread";
  1285. viewer.append(spread);
  1286. } else if (i % 2 === parity) {
  1287. spread = spread.cloneNode(false);
  1288. viewer.append(spread);
  1289. }
  1290. spread.append(pages[i].div);
  1291. }
  1292. }
  1293. }
  1294. if (!pageNumber) {
  1295. return;
  1296. }
  1297. if (this._currentScaleValue && isNaN(this._currentScaleValue)) {
  1298. this._setScale(this._currentScaleValue, true);
  1299. }
  1300. this._setCurrentPageNumber(pageNumber, true);
  1301. this.update();
  1302. }
  1303. _getPageAdvance(currentPageNumber, previous = false) {
  1304. switch (this._scrollMode) {
  1305. case _ui_utils.ScrollMode.WRAPPED:
  1306. {
  1307. const {
  1308. views
  1309. } = this._getVisiblePages(),
  1310. pageLayout = new Map();
  1311. for (const {
  1312. id,
  1313. y,
  1314. percent,
  1315. widthPercent
  1316. } of views) {
  1317. if (percent === 0 || widthPercent < 100) {
  1318. continue;
  1319. }
  1320. let yArray = pageLayout.get(y);
  1321. if (!yArray) {
  1322. pageLayout.set(y, yArray ||= []);
  1323. }
  1324. yArray.push(id);
  1325. }
  1326. for (const yArray of pageLayout.values()) {
  1327. const currentIndex = yArray.indexOf(currentPageNumber);
  1328. if (currentIndex === -1) {
  1329. continue;
  1330. }
  1331. const numPages = yArray.length;
  1332. if (numPages === 1) {
  1333. break;
  1334. }
  1335. if (previous) {
  1336. for (let i = currentIndex - 1, ii = 0; i >= ii; i--) {
  1337. const currentId = yArray[i],
  1338. expectedId = yArray[i + 1] - 1;
  1339. if (currentId < expectedId) {
  1340. return currentPageNumber - expectedId;
  1341. }
  1342. }
  1343. } else {
  1344. for (let i = currentIndex + 1, ii = numPages; i < ii; i++) {
  1345. const currentId = yArray[i],
  1346. expectedId = yArray[i - 1] + 1;
  1347. if (currentId > expectedId) {
  1348. return expectedId - currentPageNumber;
  1349. }
  1350. }
  1351. }
  1352. if (previous) {
  1353. const firstId = yArray[0];
  1354. if (firstId < currentPageNumber) {
  1355. return currentPageNumber - firstId + 1;
  1356. }
  1357. } else {
  1358. const lastId = yArray[numPages - 1];
  1359. if (lastId > currentPageNumber) {
  1360. return lastId - currentPageNumber + 1;
  1361. }
  1362. }
  1363. break;
  1364. }
  1365. break;
  1366. }
  1367. case _ui_utils.ScrollMode.HORIZONTAL:
  1368. {
  1369. break;
  1370. }
  1371. case _ui_utils.ScrollMode.PAGE:
  1372. case _ui_utils.ScrollMode.VERTICAL:
  1373. {
  1374. if (this._spreadMode === _ui_utils.SpreadMode.NONE) {
  1375. break;
  1376. }
  1377. const parity = this._spreadMode - 1;
  1378. if (previous && currentPageNumber % 2 !== parity) {
  1379. break;
  1380. } else if (!previous && currentPageNumber % 2 === parity) {
  1381. break;
  1382. }
  1383. const {
  1384. views
  1385. } = this._getVisiblePages(),
  1386. expectedId = previous ? currentPageNumber - 1 : currentPageNumber + 1;
  1387. for (const {
  1388. id,
  1389. percent,
  1390. widthPercent
  1391. } of views) {
  1392. if (id !== expectedId) {
  1393. continue;
  1394. }
  1395. if (percent > 0 && widthPercent === 100) {
  1396. return 2;
  1397. }
  1398. break;
  1399. }
  1400. break;
  1401. }
  1402. }
  1403. return 1;
  1404. }
  1405. nextPage() {
  1406. const currentPageNumber = this._currentPageNumber,
  1407. pagesCount = this.pagesCount;
  1408. if (currentPageNumber >= pagesCount) {
  1409. return false;
  1410. }
  1411. const advance = this._getPageAdvance(currentPageNumber, false) || 1;
  1412. this.currentPageNumber = Math.min(currentPageNumber + advance, pagesCount);
  1413. return true;
  1414. }
  1415. previousPage() {
  1416. const currentPageNumber = this._currentPageNumber;
  1417. if (currentPageNumber <= 1) {
  1418. return false;
  1419. }
  1420. const advance = this._getPageAdvance(currentPageNumber, true) || 1;
  1421. this.currentPageNumber = Math.max(currentPageNumber - advance, 1);
  1422. return true;
  1423. }
  1424. increaseScale(steps = 1) {
  1425. let newScale = this._currentScale;
  1426. do {
  1427. newScale = (newScale * _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2);
  1428. newScale = Math.ceil(newScale * 10) / 10;
  1429. newScale = Math.min(_ui_utils.MAX_SCALE, newScale);
  1430. } while (--steps > 0 && newScale < _ui_utils.MAX_SCALE);
  1431. this.currentScaleValue = newScale;
  1432. }
  1433. decreaseScale(steps = 1) {
  1434. let newScale = this._currentScale;
  1435. do {
  1436. newScale = (newScale / _ui_utils.DEFAULT_SCALE_DELTA).toFixed(2);
  1437. newScale = Math.floor(newScale * 10) / 10;
  1438. newScale = Math.max(_ui_utils.MIN_SCALE, newScale);
  1439. } while (--steps > 0 && newScale > _ui_utils.MIN_SCALE);
  1440. this.currentScaleValue = newScale;
  1441. }
  1442. updateContainerHeightCss() {
  1443. const height = this.container.clientHeight;
  1444. if (height !== this.#previousContainerHeight) {
  1445. this.#previousContainerHeight = height;
  1446. _ui_utils.docStyle.setProperty("--viewer-container-height", `${height}px`);
  1447. }
  1448. }
  1449. get annotationEditorMode() {
  1450. return this.#annotationEditorUIManager ? this.#annotationEditorMode : _pdf.AnnotationEditorType.DISABLE;
  1451. }
  1452. set annotationEditorMode(mode) {
  1453. if (!this.#annotationEditorUIManager) {
  1454. throw new Error(`The AnnotationEditor is not enabled.`);
  1455. }
  1456. if (this.#annotationEditorMode === mode) {
  1457. return;
  1458. }
  1459. if (!isValidAnnotationEditorMode(mode)) {
  1460. throw new Error(`Invalid AnnotationEditor mode: ${mode}`);
  1461. }
  1462. if (!this.pdfDocument) {
  1463. return;
  1464. }
  1465. this.#annotationEditorMode = mode;
  1466. this.eventBus.dispatch("annotationeditormodechanged", {
  1467. source: this,
  1468. mode
  1469. });
  1470. this.#annotationEditorUIManager.updateMode(mode);
  1471. }
  1472. set annotationEditorParams({
  1473. type,
  1474. value
  1475. }) {
  1476. if (!this.#annotationEditorUIManager) {
  1477. throw new Error(`The AnnotationEditor is not enabled.`);
  1478. }
  1479. this.#annotationEditorUIManager.updateParams(type, value);
  1480. }
  1481. refresh() {
  1482. if (!this.pdfDocument) {
  1483. return;
  1484. }
  1485. const updateArgs = {};
  1486. for (const pageView of this._pages) {
  1487. pageView.update(updateArgs);
  1488. }
  1489. this.update();
  1490. }
  1491. }
  1492. exports.PDFViewer = PDFViewer;