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._optionalContentConfigPromise = options.optionalContentConfigPromise || null;
  45. this.hasRestrictedScaling = false;
  46. this.textLayerMode = Number.isInteger(options.textLayerMode) ? options.textLayerMode : _ui_utils.TextLayerMode.ENABLE;
  47. this.imageResourcesPath = options.imageResourcesPath || "";
  48. this.renderInteractiveForms = typeof options.renderInteractiveForms === "boolean" ? options.renderInteractiveForms : true;
  49. this.useOnlyCssZoom = options.useOnlyCssZoom || false;
  50. this.maxCanvasPixels = options.maxCanvasPixels || MAX_CANVAS_PIXELS;
  51. this.eventBus = options.eventBus;
  52. this.renderingQueue = options.renderingQueue;
  53. this.textLayerFactory = options.textLayerFactory;
  54. this.annotationLayerFactory = options.annotationLayerFactory;
  55. this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;
  56. this.enableWebGL = options.enableWebGL || false;
  57. this.l10n = options.l10n || _ui_utils.NullL10n;
  58. this.enableScripting = options.enableScripting || false;
  59. this.paintTask = null;
  60. this.paintedViewportMap = new WeakMap();
  61. this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL;
  62. this.resume = null;
  63. this._renderError = 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.reset();
  84. }
  85. destroy() {
  86. this.reset();
  87. if (this.pdfPage) {
  88. this.pdfPage.cleanup();
  89. }
  90. }
  91. async _renderAnnotationLayer() {
  92. let error = null;
  93. try {
  94. await this.annotationLayer.render(this.viewport, "display");
  95. } catch (ex) {
  96. error = ex;
  97. } finally {
  98. this.eventBus.dispatch("annotationlayerrendered", {
  99. source: this,
  100. pageNumber: this.id,
  101. error
  102. });
  103. }
  104. }
  105. _resetZoomLayer(removeFromDOM = false) {
  106. if (!this.zoomLayer) {
  107. return;
  108. }
  109. const zoomLayerCanvas = this.zoomLayer.firstChild;
  110. this.paintedViewportMap.delete(zoomLayerCanvas);
  111. zoomLayerCanvas.width = 0;
  112. zoomLayerCanvas.height = 0;
  113. if (removeFromDOM) {
  114. this.zoomLayer.remove();
  115. }
  116. this.zoomLayer = null;
  117. }
  118. reset(keepZoomLayer = false, keepAnnotations = false) {
  119. this.cancelRendering(keepAnnotations);
  120. this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL;
  121. const div = this.div;
  122. div.style.width = Math.floor(this.viewport.width) + "px";
  123. div.style.height = Math.floor(this.viewport.height) + "px";
  124. const childNodes = div.childNodes;
  125. const currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null;
  126. const currentAnnotationNode = keepAnnotations && this.annotationLayer && this.annotationLayer.div || null;
  127. for (let i = childNodes.length - 1; i >= 0; i--) {
  128. const node = childNodes[i];
  129. if (currentZoomLayerNode === node || currentAnnotationNode === node) {
  130. continue;
  131. }
  132. div.removeChild(node);
  133. }
  134. div.removeAttribute("data-loaded");
  135. if (currentAnnotationNode) {
  136. this.annotationLayer.hide();
  137. } else if (this.annotationLayer) {
  138. this.annotationLayer.cancel();
  139. this.annotationLayer = null;
  140. }
  141. if (!currentZoomLayerNode) {
  142. if (this.canvas) {
  143. this.paintedViewportMap.delete(this.canvas);
  144. this.canvas.width = 0;
  145. this.canvas.height = 0;
  146. delete this.canvas;
  147. }
  148. this._resetZoomLayer();
  149. }
  150. if (this.svg) {
  151. this.paintedViewportMap.delete(this.svg);
  152. delete this.svg;
  153. }
  154. this.loadingIconDiv = document.createElement("div");
  155. this.loadingIconDiv.className = "loadingIcon";
  156. div.appendChild(this.loadingIconDiv);
  157. }
  158. update(scale, rotation, optionalContentConfigPromise = null) {
  159. this.scale = scale || this.scale;
  160. if (typeof rotation !== "undefined") {
  161. this.rotation = rotation;
  162. }
  163. if (optionalContentConfigPromise instanceof Promise) {
  164. this._optionalContentConfigPromise = optionalContentConfigPromise;
  165. }
  166. const totalRotation = (this.rotation + this.pdfPageRotate) % 360;
  167. this.viewport = this.viewport.clone({
  168. scale: this.scale * _ui_utils.CSS_UNITS,
  169. rotation: totalRotation
  170. });
  171. if (this.svg) {
  172. this.cssTransform(this.svg, true);
  173. this.eventBus.dispatch("pagerendered", {
  174. source: this,
  175. pageNumber: this.id,
  176. cssTransform: true,
  177. timestamp: performance.now(),
  178. error: this._renderError
  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. error: this._renderError
  198. });
  199. return;
  200. }
  201. if (!this.zoomLayer && !this.canvas.hasAttribute("hidden")) {
  202. this.zoomLayer = this.canvas.parentNode;
  203. this.zoomLayer.style.position = "absolute";
  204. }
  205. }
  206. if (this.zoomLayer) {
  207. this.cssTransform(this.zoomLayer.firstChild);
  208. }
  209. this.reset(true, true);
  210. }
  211. cancelRendering(keepAnnotations = false) {
  212. if (this.paintTask) {
  213. this.paintTask.cancel();
  214. this.paintTask = null;
  215. }
  216. this.resume = null;
  217. if (this.textLayer) {
  218. this.textLayer.cancel();
  219. this.textLayer = null;
  220. }
  221. if (!keepAnnotations && this.annotationLayer) {
  222. this.annotationLayer.cancel();
  223. this.annotationLayer = null;
  224. }
  225. }
  226. cssTransform(target, redrawAnnotations = false) {
  227. const width = this.viewport.width;
  228. const height = this.viewport.height;
  229. const div = this.div;
  230. target.style.width = target.parentNode.style.width = div.style.width = Math.floor(width) + "px";
  231. target.style.height = target.parentNode.style.height = div.style.height = Math.floor(height) + "px";
  232. const relativeRotation = this.viewport.rotation - this.paintedViewportMap.get(target).rotation;
  233. const absRotation = Math.abs(relativeRotation);
  234. let scaleX = 1,
  235. scaleY = 1;
  236. if (absRotation === 90 || absRotation === 270) {
  237. scaleX = height / width;
  238. scaleY = width / height;
  239. }
  240. target.style.transform = `rotate(${relativeRotation}deg) scale(${scaleX}, ${scaleY})`;
  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}) ` + `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 = null) => {
  343. if (paintTask === this.paintTask) {
  344. this.paintTask = null;
  345. }
  346. if (error instanceof _pdf.RenderingCancelledException) {
  347. this._renderError = null;
  348. return;
  349. }
  350. this._renderError = error;
  351. this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED;
  352. if (this.loadingIconDiv) {
  353. div.removeChild(this.loadingIconDiv);
  354. delete this.loadingIconDiv;
  355. }
  356. this._resetZoomLayer(true);
  357. this.eventBus.dispatch("pagerendered", {
  358. source: this,
  359. pageNumber: this.id,
  360. cssTransform: false,
  361. timestamp: performance.now(),
  362. error: this._renderError
  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, null, this.imageResourcesPath, this.renderInteractiveForms, this.l10n, this.enableScripting, null, null);
  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;