pdf_print_service.js 8.9 KB

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