pdf_print_service.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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.PDFPrintService = PDFPrintService;
  27. var _pdf = require("../pdf");
  28. var _app = require("./app.js");
  29. var _app_options = require("./app_options.js");
  30. var _print_utils = require("./print_utils.js");
  31. let activeService = null;
  32. let overlayManager = null;
  33. function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size, printResolution, optionalContentConfigPromise) {
  34. const scratchCanvas = activeService.scratchCanvas;
  35. const PRINT_UNITS = printResolution / _pdf.PixelsPerInch.PDF;
  36. scratchCanvas.width = Math.floor(size.width * PRINT_UNITS);
  37. scratchCanvas.height = Math.floor(size.height * PRINT_UNITS);
  38. const ctx = scratchCanvas.getContext("2d");
  39. ctx.save();
  40. ctx.fillStyle = "rgb(255, 255, 255)";
  41. ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height);
  42. ctx.restore();
  43. return pdfDocument.getPage(pageNumber).then(function (pdfPage) {
  44. const renderContext = {
  45. canvasContext: ctx,
  46. transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0],
  47. viewport: pdfPage.getViewport({
  48. scale: 1,
  49. rotation: size.rotation
  50. }),
  51. intent: "print",
  52. annotationMode: _pdf.AnnotationMode.ENABLE_STORAGE,
  53. optionalContentConfigPromise
  54. };
  55. return pdfPage.render(renderContext).promise;
  56. });
  57. }
  58. function PDFPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise = null, l10n) {
  59. this.pdfDocument = pdfDocument;
  60. this.pagesOverview = pagesOverview;
  61. this.printContainer = printContainer;
  62. this._printResolution = printResolution || 150;
  63. this._optionalContentConfigPromise = optionalContentConfigPromise || pdfDocument.getOptionalContentConfig();
  64. this.l10n = l10n;
  65. this.currentPage = -1;
  66. this.scratchCanvas = document.createElement("canvas");
  67. }
  68. PDFPrintService.prototype = {
  69. layout() {
  70. this.throwIfInactive();
  71. const body = document.querySelector("body");
  72. body.setAttribute("data-pdfjsprinting", true);
  73. const hasEqualPageSizes = this.pagesOverview.every(function (size) {
  74. return size.width === this.pagesOverview[0].width && size.height === this.pagesOverview[0].height;
  75. }, this);
  76. if (!hasEqualPageSizes) {
  77. console.warn("Not all pages have the same size. The printed " + "result may be incorrect!");
  78. }
  79. this.pageStyleSheet = document.createElement("style");
  80. const pageSize = this.pagesOverview[0];
  81. this.pageStyleSheet.textContent = "@page { size: " + pageSize.width + "pt " + pageSize.height + "pt;}";
  82. body.appendChild(this.pageStyleSheet);
  83. },
  84. destroy() {
  85. if (activeService !== this) {
  86. return;
  87. }
  88. this.printContainer.textContent = "";
  89. const body = document.querySelector("body");
  90. body.removeAttribute("data-pdfjsprinting");
  91. if (this.pageStyleSheet) {
  92. this.pageStyleSheet.remove();
  93. this.pageStyleSheet = null;
  94. }
  95. this.scratchCanvas.width = this.scratchCanvas.height = 0;
  96. this.scratchCanvas = null;
  97. activeService = null;
  98. ensureOverlay().then(function () {
  99. if (overlayManager.active !== "printServiceOverlay") {
  100. return;
  101. }
  102. overlayManager.close("printServiceOverlay");
  103. });
  104. },
  105. renderPages() {
  106. if (this.pdfDocument.isPureXfa) {
  107. (0, _print_utils.getXfaHtmlForPrinting)(this.printContainer, this.pdfDocument);
  108. return Promise.resolve();
  109. }
  110. const pageCount = this.pagesOverview.length;
  111. const renderNextPage = (resolve, reject) => {
  112. this.throwIfInactive();
  113. if (++this.currentPage >= pageCount) {
  114. renderProgress(pageCount, pageCount, this.l10n);
  115. resolve();
  116. return;
  117. }
  118. const index = this.currentPage;
  119. renderProgress(index, pageCount, this.l10n);
  120. renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index], this._printResolution, this._optionalContentConfigPromise).then(this.useRenderedPage.bind(this)).then(function () {
  121. renderNextPage(resolve, reject);
  122. }, reject);
  123. };
  124. return new Promise(renderNextPage);
  125. },
  126. useRenderedPage() {
  127. this.throwIfInactive();
  128. const img = document.createElement("img");
  129. const scratchCanvas = this.scratchCanvas;
  130. if ("toBlob" in scratchCanvas && !_app_options.compatibilityParams.disableCreateObjectURL) {
  131. scratchCanvas.toBlob(function (blob) {
  132. img.src = URL.createObjectURL(blob);
  133. });
  134. } else {
  135. img.src = scratchCanvas.toDataURL();
  136. }
  137. const wrapper = document.createElement("div");
  138. wrapper.className = "printedPage";
  139. wrapper.appendChild(img);
  140. this.printContainer.appendChild(wrapper);
  141. return new Promise(function (resolve, reject) {
  142. img.onload = resolve;
  143. img.onerror = reject;
  144. });
  145. },
  146. performPrint() {
  147. this.throwIfInactive();
  148. return new Promise(resolve => {
  149. setTimeout(() => {
  150. if (!this.active) {
  151. resolve();
  152. return;
  153. }
  154. print.call(window);
  155. setTimeout(resolve, 20);
  156. }, 0);
  157. });
  158. },
  159. get active() {
  160. return this === activeService;
  161. },
  162. throwIfInactive() {
  163. if (!this.active) {
  164. throw new Error("This print request was cancelled or completed.");
  165. }
  166. }
  167. };
  168. const print = window.print;
  169. window.print = function () {
  170. if (activeService) {
  171. console.warn("Ignored window.print() because of a pending print job.");
  172. return;
  173. }
  174. ensureOverlay().then(function () {
  175. if (activeService) {
  176. overlayManager.open("printServiceOverlay");
  177. }
  178. });
  179. try {
  180. dispatchEvent("beforeprint");
  181. } finally {
  182. if (!activeService) {
  183. console.error("Expected print service to be initialized.");
  184. ensureOverlay().then(function () {
  185. if (overlayManager.active === "printServiceOverlay") {
  186. overlayManager.close("printServiceOverlay");
  187. }
  188. });
  189. return;
  190. }
  191. const activeServiceOnEntry = activeService;
  192. activeService.renderPages().then(function () {
  193. return activeServiceOnEntry.performPrint();
  194. }).catch(function () {}).then(function () {
  195. if (activeServiceOnEntry.active) {
  196. abort();
  197. }
  198. });
  199. }
  200. };
  201. function dispatchEvent(eventType) {
  202. const event = document.createEvent("CustomEvent");
  203. event.initCustomEvent(eventType, false, false, "custom");
  204. window.dispatchEvent(event);
  205. }
  206. function abort() {
  207. if (activeService) {
  208. activeService.destroy();
  209. dispatchEvent("afterprint");
  210. }
  211. }
  212. function renderProgress(index, total, l10n) {
  213. const progressContainer = document.getElementById("printServiceOverlay");
  214. const progress = Math.round(100 * index / total);
  215. const progressBar = progressContainer.querySelector("progress");
  216. const progressPerc = progressContainer.querySelector(".relative-progress");
  217. progressBar.value = progress;
  218. l10n.get("print_progress_percent", {
  219. progress
  220. }).then(msg => {
  221. progressPerc.textContent = msg;
  222. });
  223. }
  224. window.addEventListener("keydown", function (event) {
  225. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  226. window.print();
  227. event.preventDefault();
  228. if (event.stopImmediatePropagation) {
  229. event.stopImmediatePropagation();
  230. } else {
  231. event.stopPropagation();
  232. }
  233. }
  234. }, true);
  235. if ("onbeforeprint" in window) {
  236. const stopPropagationIfNeeded = function (event) {
  237. if (event.detail !== "custom" && event.stopImmediatePropagation) {
  238. event.stopImmediatePropagation();
  239. }
  240. };
  241. window.addEventListener("beforeprint", stopPropagationIfNeeded);
  242. window.addEventListener("afterprint", stopPropagationIfNeeded);
  243. }
  244. let overlayPromise;
  245. function ensureOverlay() {
  246. if (!overlayPromise) {
  247. overlayManager = _app.PDFViewerApplication.overlayManager;
  248. if (!overlayManager) {
  249. throw new Error("The overlay manager has not yet been initialized.");
  250. }
  251. overlayPromise = overlayManager.register("printServiceOverlay", document.getElementById("printServiceOverlay"), abort, true);
  252. document.getElementById("printCancel").onclick = abort;
  253. }
  254. return overlayPromise;
  255. }
  256. _app.PDFPrintServiceFactory.instance = {
  257. supportsPrinting: true,
  258. createPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise, l10n) {
  259. if (activeService) {
  260. throw new Error("The print service is created and active.");
  261. }
  262. activeService = new PDFPrintService(pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise, l10n);
  263. return activeService;
  264. }
  265. };