2
0

pdf_page_view.js 19 KB

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