pdf_page_view.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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.PDFPageView = void 0;
  27. var _ui_utils = require("./ui_utils.js");
  28. var _pdf = require("../pdf");
  29. var _l10n_utils = require("./l10n_utils.js");
  30. var _pdf_rendering_queue = require("./pdf_rendering_queue.js");
  31. var _viewer_compatibility = require("./viewer_compatibility.js");
  32. const MAX_CANVAS_PIXELS = _viewer_compatibility.viewerCompatibilityParams.maxCanvasPixels || 16777216;
  33. class PDFPageView {
  34. constructor(options) {
  35. const container = options.container;
  36. const defaultViewport = options.defaultViewport;
  37. this.id = options.id;
  38. this.renderingId = "page" + this.id;
  39. this.pdfPage = null;
  40. this.pageLabel = null;
  41. this.rotation = 0;
  42. this.scale = options.scale || _ui_utils.DEFAULT_SCALE;
  43. this.viewport = defaultViewport;
  44. this.pdfPageRotate = defaultViewport.rotation;
  45. this._optionalContentConfigPromise = options.optionalContentConfigPromise || null;
  46. this.hasRestrictedScaling = false;
  47. this.textLayerMode = Number.isInteger(options.textLayerMode) ? options.textLayerMode : _ui_utils.TextLayerMode.ENABLE;
  48. this.imageResourcesPath = options.imageResourcesPath || "";
  49. this.renderInteractiveForms = options.renderInteractiveForms !== false;
  50. this.useOnlyCssZoom = options.useOnlyCssZoom || false;
  51. this.maxCanvasPixels = options.maxCanvasPixels || MAX_CANVAS_PIXELS;
  52. this.eventBus = options.eventBus;
  53. this.renderingQueue = options.renderingQueue;
  54. this.textLayerFactory = options.textLayerFactory;
  55. this.annotationLayerFactory = options.annotationLayerFactory;
  56. this.xfaLayerFactory = options.xfaLayerFactory;
  57. this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;
  58. this.enableWebGL = options.enableWebGL || false;
  59. this.l10n = options.l10n || _l10n_utils.NullL10n;
  60. this.enableScripting = options.enableScripting === true;
  61. this.paintTask = null;
  62. this.paintedViewportMap = new WeakMap();
  63. this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL;
  64. this.resume = null;
  65. this._renderError = null;
  66. this.annotationLayer = null;
  67. this.textLayer = null;
  68. this.zoomLayer = null;
  69. this.xfaLayer = null;
  70. const div = document.createElement("div");
  71. div.className = "page";
  72. div.style.width = Math.floor(this.viewport.width) + "px";
  73. div.style.height = Math.floor(this.viewport.height) + "px";
  74. div.setAttribute("data-page-number", this.id);
  75. div.setAttribute("role", "region");
  76. this.l10n.get("page_landmark", {
  77. page: this.id
  78. }).then(msg => {
  79. div.setAttribute("aria-label", msg);
  80. });
  81. this.div = div;
  82. container.appendChild(div);
  83. }
  84. setPdfPage(pdfPage) {
  85. this.pdfPage = pdfPage;
  86. this.pdfPageRotate = pdfPage.rotate;
  87. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  88. this.viewport = pdfPage.getViewport({
  89. scale: this.scale * _ui_utils.CSS_UNITS,
  90. rotation: totalRotation
  91. });
  92. this.reset();
  93. }
  94. destroy() {
  95. this.reset();
  96. if (this.pdfPage) {
  97. this.pdfPage.cleanup();
  98. }
  99. }
  100. async _renderAnnotationLayer() {
  101. let error = null;
  102. try {
  103. await this.annotationLayer.render(this.viewport, "display");
  104. } catch (ex) {
  105. error = ex;
  106. } finally {
  107. this.eventBus.dispatch("annotationlayerrendered", {
  108. source: this,
  109. pageNumber: this.id,
  110. error
  111. });
  112. }
  113. }
  114. async _renderXfaLayer() {
  115. let error = null;
  116. try {
  117. await this.xfaLayer.render(this.viewport, "display");
  118. } catch (ex) {
  119. error = ex;
  120. } finally {
  121. this.eventBus.dispatch("xfalayerrendered", {
  122. source: this,
  123. pageNumber: this.id,
  124. error
  125. });
  126. }
  127. }
  128. _resetZoomLayer(removeFromDOM = false) {
  129. if (!this.zoomLayer) {
  130. return;
  131. }
  132. const zoomLayerCanvas = this.zoomLayer.firstChild;
  133. this.paintedViewportMap.delete(zoomLayerCanvas);
  134. zoomLayerCanvas.width = 0;
  135. zoomLayerCanvas.height = 0;
  136. if (removeFromDOM) {
  137. this.zoomLayer.remove();
  138. }
  139. this.zoomLayer = null;
  140. }
  141. reset(keepZoomLayer = false, keepAnnotations = false) {
  142. this.cancelRendering(keepAnnotations);
  143. this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL;
  144. const div = this.div;
  145. div.style.width = Math.floor(this.viewport.width) + "px";
  146. div.style.height = Math.floor(this.viewport.height) + "px";
  147. const childNodes = div.childNodes;
  148. const currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null;
  149. const currentAnnotationNode = keepAnnotations && this.annotationLayer?.div || null;
  150. const currentXfaLayerNode = this.xfaLayer?.div || null;
  151. for (let i = childNodes.length - 1; i >= 0; i--) {
  152. const node = childNodes[i];
  153. if (currentZoomLayerNode === node || currentAnnotationNode === node || currentXfaLayerNode === node) {
  154. continue;
  155. }
  156. div.removeChild(node);
  157. }
  158. div.removeAttribute("data-loaded");
  159. if (currentAnnotationNode) {
  160. this.annotationLayer.hide();
  161. } else if (this.annotationLayer) {
  162. this.annotationLayer.cancel();
  163. this.annotationLayer = null;
  164. }
  165. if (!currentZoomLayerNode) {
  166. if (this.canvas) {
  167. this.paintedViewportMap.delete(this.canvas);
  168. this.canvas.width = 0;
  169. this.canvas.height = 0;
  170. delete this.canvas;
  171. }
  172. this._resetZoomLayer();
  173. }
  174. if (this.svg) {
  175. this.paintedViewportMap.delete(this.svg);
  176. delete this.svg;
  177. }
  178. this.loadingIconDiv = document.createElement("div");
  179. this.loadingIconDiv.className = "loadingIcon";
  180. this.loadingIconDiv.setAttribute("role", "img");
  181. this.l10n.get("loading").then(msg => {
  182. this.loadingIconDiv?.setAttribute("aria-label", msg);
  183. });
  184. div.appendChild(this.loadingIconDiv);
  185. }
  186. update(scale, rotation, optionalContentConfigPromise = null) {
  187. this.scale = scale || this.scale;
  188. if (typeof rotation !== "undefined") {
  189. this.rotation = rotation;
  190. }
  191. if (optionalContentConfigPromise instanceof Promise) {
  192. this._optionalContentConfigPromise = optionalContentConfigPromise;
  193. }
  194. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  195. this.viewport = this.viewport.clone({
  196. scale: this.scale * _ui_utils.CSS_UNITS,
  197. rotation: totalRotation
  198. });
  199. if (this.svg) {
  200. this.cssTransform(this.svg, true);
  201. this.eventBus.dispatch("pagerendered", {
  202. source: this,
  203. pageNumber: this.id,
  204. cssTransform: true,
  205. timestamp: performance.now(),
  206. error: this._renderError
  207. });
  208. return;
  209. }
  210. let isScalingRestricted = false;
  211. if (this.canvas && this.maxCanvasPixels > 0) {
  212. const outputScale = this.outputScale;
  213. if ((Math.floor(this.viewport.width) * outputScale.sx | 0) * (Math.floor(this.viewport.height) * outputScale.sy | 0) > this.maxCanvasPixels) {
  214. isScalingRestricted = true;
  215. }
  216. }
  217. if (this.canvas) {
  218. if (this.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) {
  219. this.cssTransform(this.canvas, true);
  220. this.eventBus.dispatch("pagerendered", {
  221. source: this,
  222. pageNumber: this.id,
  223. cssTransform: true,
  224. timestamp: performance.now(),
  225. error: this._renderError
  226. });
  227. return;
  228. }
  229. if (!this.zoomLayer && !this.canvas.hidden) {
  230. this.zoomLayer = this.canvas.parentNode;
  231. this.zoomLayer.style.position = "absolute";
  232. }
  233. }
  234. if (this.zoomLayer) {
  235. this.cssTransform(this.zoomLayer.firstChild);
  236. }
  237. this.reset(true, true);
  238. }
  239. cancelRendering(keepAnnotations = false) {
  240. if (this.paintTask) {
  241. this.paintTask.cancel();
  242. this.paintTask = null;
  243. }
  244. this.resume = null;
  245. if (this.textLayer) {
  246. this.textLayer.cancel();
  247. this.textLayer = null;
  248. }
  249. if (!keepAnnotations && this.annotationLayer) {
  250. this.annotationLayer.cancel();
  251. this.annotationLayer = null;
  252. }
  253. }
  254. cssTransform(target, redrawAnnotations = false) {
  255. const width = this.viewport.width;
  256. const height = this.viewport.height;
  257. const div = this.div;
  258. target.style.width = target.parentNode.style.width = div.style.width = Math.floor(width) + "px";
  259. target.style.height = target.parentNode.style.height = div.style.height = Math.floor(height) + "px";
  260. const relativeRotation = this.viewport.rotation - this.paintedViewportMap.get(target).rotation;
  261. const absRotation = Math.abs(relativeRotation);
  262. let scaleX = 1,
  263. scaleY = 1;
  264. if (absRotation === 90 || absRotation === 270) {
  265. scaleX = height / width;
  266. scaleY = width / height;
  267. }
  268. target.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX}, ${scaleY})`;
  269. if (this.textLayer) {
  270. const textLayerViewport = this.textLayer.viewport;
  271. const textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation;
  272. const textAbsRotation = Math.abs(textRelativeRotation);
  273. let scale = width / textLayerViewport.width;
  274. if (textAbsRotation === 90 || textAbsRotation === 270) {
  275. scale = width / textLayerViewport.height;
  276. }
  277. const textLayerDiv = this.textLayer.textLayerDiv;
  278. let transX, transY;
  279. switch (textAbsRotation) {
  280. case 0:
  281. transX = transY = 0;
  282. break;
  283. case 90:
  284. transX = 0;
  285. transY = "-" + textLayerDiv.style.height;
  286. break;
  287. case 180:
  288. transX = "-" + textLayerDiv.style.width;
  289. transY = "-" + textLayerDiv.style.height;
  290. break;
  291. case 270:
  292. transX = "-" + textLayerDiv.style.width;
  293. transY = 0;
  294. break;
  295. default:
  296. console.error("Bad rotation value.");
  297. break;
  298. }
  299. textLayerDiv.style.transform = `rotate(${textAbsRotation}deg) ` + `scale(${scale}) ` + `translate(${transX}, ${transY})`;
  300. textLayerDiv.style.transformOrigin = "0% 0%";
  301. }
  302. if (redrawAnnotations && this.annotationLayer) {
  303. this._renderAnnotationLayer();
  304. }
  305. if (this.xfaLayer) {
  306. this._renderXfaLayer();
  307. }
  308. }
  309. get width() {
  310. return this.viewport.width;
  311. }
  312. get height() {
  313. return this.viewport.height;
  314. }
  315. getPagePoint(x, y) {
  316. return this.viewport.convertToPdfPoint(x, y);
  317. }
  318. draw() {
  319. if (this.renderingState !== _pdf_rendering_queue.RenderingStates.INITIAL) {
  320. console.error("Must be in new state before drawing");
  321. this.reset();
  322. }
  323. const {
  324. div,
  325. pdfPage
  326. } = this;
  327. if (!pdfPage) {
  328. this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED;
  329. if (this.loadingIconDiv) {
  330. div.removeChild(this.loadingIconDiv);
  331. delete this.loadingIconDiv;
  332. }
  333. return Promise.reject(new Error("pdfPage is not loaded"));
  334. }
  335. this.renderingState = _pdf_rendering_queue.RenderingStates.RUNNING;
  336. const canvasWrapper = document.createElement("div");
  337. canvasWrapper.style.width = div.style.width;
  338. canvasWrapper.style.height = div.style.height;
  339. canvasWrapper.classList.add("canvasWrapper");
  340. if (this.annotationLayer?.div) {
  341. div.insertBefore(canvasWrapper, this.annotationLayer.div);
  342. } else {
  343. div.appendChild(canvasWrapper);
  344. }
  345. let textLayer = null;
  346. if (this.textLayerMode !== _ui_utils.TextLayerMode.DISABLE && this.textLayerFactory) {
  347. const textLayerDiv = document.createElement("div");
  348. textLayerDiv.className = "textLayer";
  349. textLayerDiv.style.width = canvasWrapper.style.width;
  350. textLayerDiv.style.height = canvasWrapper.style.height;
  351. if (this.annotationLayer?.div) {
  352. div.insertBefore(textLayerDiv, this.annotationLayer.div);
  353. } else {
  354. div.appendChild(textLayerDiv);
  355. }
  356. textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.textLayerMode === _ui_utils.TextLayerMode.ENABLE_ENHANCE, this.eventBus);
  357. }
  358. this.textLayer = textLayer;
  359. let renderContinueCallback = null;
  360. if (this.renderingQueue) {
  361. renderContinueCallback = cont => {
  362. if (!this.renderingQueue.isHighestPriority(this)) {
  363. this.renderingState = _pdf_rendering_queue.RenderingStates.PAUSED;
  364. this.resume = () => {
  365. this.renderingState = _pdf_rendering_queue.RenderingStates.RUNNING;
  366. cont();
  367. };
  368. return;
  369. }
  370. cont();
  371. };
  372. }
  373. const finishPaintTask = async (error = null) => {
  374. if (paintTask === this.paintTask) {
  375. this.paintTask = null;
  376. }
  377. if (error instanceof _pdf.RenderingCancelledException) {
  378. this._renderError = null;
  379. return;
  380. }
  381. this._renderError = error;
  382. this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED;
  383. if (this.loadingIconDiv) {
  384. div.removeChild(this.loadingIconDiv);
  385. delete this.loadingIconDiv;
  386. }
  387. this._resetZoomLayer(true);
  388. this.eventBus.dispatch("pagerendered", {
  389. source: this,
  390. pageNumber: this.id,
  391. cssTransform: false,
  392. timestamp: performance.now(),
  393. error: this._renderError
  394. });
  395. if (error) {
  396. throw error;
  397. }
  398. };
  399. const paintTask = this.renderer === _ui_utils.RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper);
  400. paintTask.onRenderContinue = renderContinueCallback;
  401. this.paintTask = paintTask;
  402. const resultPromise = paintTask.promise.then(function () {
  403. return finishPaintTask(null).then(function () {
  404. if (textLayer) {
  405. const readableStream = pdfPage.streamTextContent({
  406. normalizeWhitespace: true
  407. });
  408. textLayer.setTextContentStream(readableStream);
  409. textLayer.render();
  410. }
  411. });
  412. }, function (reason) {
  413. return finishPaintTask(reason);
  414. });
  415. if (this.annotationLayerFactory) {
  416. if (!this.annotationLayer) {
  417. this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, pdfPage, null, this.imageResourcesPath, this.renderInteractiveForms, this.l10n, this.enableScripting, null, null);
  418. }
  419. this._renderAnnotationLayer();
  420. }
  421. if (this.xfaLayerFactory) {
  422. if (!this.xfaLayer) {
  423. this.xfaLayer = this.xfaLayerFactory.createXfaLayerBuilder(div, pdfPage);
  424. }
  425. this._renderXfaLayer();
  426. }
  427. div.setAttribute("data-loaded", true);
  428. this.eventBus.dispatch("pagerender", {
  429. source: this,
  430. pageNumber: this.id
  431. });
  432. return resultPromise;
  433. }
  434. paintOnCanvas(canvasWrapper) {
  435. const renderCapability = (0, _pdf.createPromiseCapability)();
  436. const result = {
  437. promise: renderCapability.promise,
  438. onRenderContinue(cont) {
  439. cont();
  440. },
  441. cancel() {
  442. renderTask.cancel();
  443. }
  444. };
  445. const viewport = this.viewport;
  446. const canvas = document.createElement("canvas");
  447. canvas.hidden = true;
  448. let isCanvasHidden = true;
  449. const showCanvas = function () {
  450. if (isCanvasHidden) {
  451. canvas.hidden = false;
  452. isCanvasHidden = false;
  453. }
  454. };
  455. canvasWrapper.appendChild(canvas);
  456. this.canvas = canvas;
  457. canvas.mozOpaque = true;
  458. const ctx = canvas.getContext("2d", {
  459. alpha: false
  460. });
  461. const outputScale = (0, _ui_utils.getOutputScale)(ctx);
  462. this.outputScale = outputScale;
  463. if (this.useOnlyCssZoom) {
  464. const actualSizeViewport = viewport.clone({
  465. scale: _ui_utils.CSS_UNITS
  466. });
  467. outputScale.sx *= actualSizeViewport.width / viewport.width;
  468. outputScale.sy *= actualSizeViewport.height / viewport.height;
  469. outputScale.scaled = true;
  470. }
  471. if (this.maxCanvasPixels > 0) {
  472. const pixelsInViewport = viewport.width * viewport.height;
  473. const maxScale = Math.sqrt(this.maxCanvasPixels / pixelsInViewport);
  474. if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
  475. outputScale.sx = maxScale;
  476. outputScale.sy = maxScale;
  477. outputScale.scaled = true;
  478. this.hasRestrictedScaling = true;
  479. } else {
  480. this.hasRestrictedScaling = false;
  481. }
  482. }
  483. const sfx = (0, _ui_utils.approximateFraction)(outputScale.sx);
  484. const sfy = (0, _ui_utils.approximateFraction)(outputScale.sy);
  485. canvas.width = (0, _ui_utils.roundToDivide)(viewport.width * outputScale.sx, sfx[0]);
  486. canvas.height = (0, _ui_utils.roundToDivide)(viewport.height * outputScale.sy, sfy[0]);
  487. canvas.style.width = (0, _ui_utils.roundToDivide)(viewport.width, sfx[1]) + "px";
  488. canvas.style.height = (0, _ui_utils.roundToDivide)(viewport.height, sfy[1]) + "px";
  489. this.paintedViewportMap.set(canvas, viewport);
  490. const transform = !outputScale.scaled ? null : [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
  491. const renderContext = {
  492. canvasContext: ctx,
  493. transform,
  494. viewport: this.viewport,
  495. enableWebGL: this.enableWebGL,
  496. renderInteractiveForms: this.renderInteractiveForms,
  497. optionalContentConfigPromise: this._optionalContentConfigPromise
  498. };
  499. const renderTask = this.pdfPage.render(renderContext);
  500. renderTask.onContinue = function (cont) {
  501. showCanvas();
  502. if (result.onRenderContinue) {
  503. result.onRenderContinue(cont);
  504. } else {
  505. cont();
  506. }
  507. };
  508. renderTask.promise.then(function () {
  509. showCanvas();
  510. renderCapability.resolve(undefined);
  511. }, function (error) {
  512. showCanvas();
  513. renderCapability.reject(error);
  514. });
  515. return result;
  516. }
  517. paintOnSvg(wrapper) {
  518. let cancelled = false;
  519. const ensureNotCancelled = () => {
  520. if (cancelled) {
  521. throw new _pdf.RenderingCancelledException(`Rendering cancelled, page ${this.id}`, "svg");
  522. }
  523. };
  524. const pdfPage = this.pdfPage;
  525. const actualSizeViewport = this.viewport.clone({
  526. scale: _ui_utils.CSS_UNITS
  527. });
  528. const promise = pdfPage.getOperatorList().then(opList => {
  529. ensureNotCancelled();
  530. const svgGfx = new _pdf.SVGGraphics(pdfPage.commonObjs, pdfPage.objs, _viewer_compatibility.viewerCompatibilityParams.disableCreateObjectURL);
  531. return svgGfx.getSVG(opList, actualSizeViewport).then(svg => {
  532. ensureNotCancelled();
  533. this.svg = svg;
  534. this.paintedViewportMap.set(svg, actualSizeViewport);
  535. svg.style.width = wrapper.style.width;
  536. svg.style.height = wrapper.style.height;
  537. this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED;
  538. wrapper.appendChild(svg);
  539. });
  540. });
  541. return {
  542. promise,
  543. onRenderContinue(cont) {
  544. cont();
  545. },
  546. cancel() {
  547. cancelled = true;
  548. }
  549. };
  550. }
  551. setPageLabel(label) {
  552. this.pageLabel = typeof label === "string" ? label : null;
  553. if (this.pageLabel !== null) {
  554. this.div.setAttribute("data-page-label", this.pageLabel);
  555. } else {
  556. this.div.removeAttribute("data-page-label");
  557. }
  558. }
  559. }
  560. exports.PDFPageView = PDFPageView;