pdf_viewer.js 47 KB

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