pdf_print_service.js 8.9 KB

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