pdf_print_service.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2018 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");
  28. var _app = require("./app");
  29. var _pdf = require("../pdf");
  30. var activeService = null;
  31. var overlayManager = null;
  32. function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
  33. var scratchCanvas = activeService.scratchCanvas;
  34. var PRINT_RESOLUTION = 150;
  35. var 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. var width = Math.floor(size.width * _ui_utils.CSS_UNITS) + 'px';
  39. var height = Math.floor(size.height * _ui_utils.CSS_UNITS) + 'px';
  40. var 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. var 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: width,
  59. height: 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 = pdfDocument.loadingParams['disableCreateObjectURL'];
  69. this.currentPage = -1;
  70. this.scratchCanvas = document.createElement('canvas');
  71. }
  72. PDFPrintService.prototype = {
  73. layout: function layout() {
  74. this.throwIfInactive();
  75. var body = document.querySelector('body');
  76. body.setAttribute('data-pdfjsprinting', true);
  77. var 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. var 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: function destroy() {
  89. if (activeService !== this) {
  90. return;
  91. }
  92. this.printContainer.textContent = '';
  93. if (this.pageStyleSheet) {
  94. this.pageStyleSheet.remove();
  95. this.pageStyleSheet = null;
  96. }
  97. this.scratchCanvas.width = this.scratchCanvas.height = 0;
  98. this.scratchCanvas = null;
  99. activeService = null;
  100. ensureOverlay().then(function () {
  101. if (overlayManager.active !== 'printServiceOverlay') {
  102. return;
  103. }
  104. overlayManager.close('printServiceOverlay');
  105. });
  106. },
  107. renderPages: function renderPages() {
  108. var _this = this;
  109. var pageCount = this.pagesOverview.length;
  110. var renderNextPage = function renderNextPage(resolve, reject) {
  111. _this.throwIfInactive();
  112. if (++_this.currentPage >= pageCount) {
  113. renderProgress(pageCount, pageCount, _this.l10n);
  114. resolve();
  115. return;
  116. }
  117. var index = _this.currentPage;
  118. renderProgress(index, pageCount, _this.l10n);
  119. renderPage(_this, _this.pdfDocument, index + 1, _this.pagesOverview[index]).then(_this.useRenderedPage.bind(_this)).then(function () {
  120. renderNextPage(resolve, reject);
  121. }, reject);
  122. };
  123. return new Promise(renderNextPage);
  124. },
  125. useRenderedPage: function useRenderedPage(printItem) {
  126. this.throwIfInactive();
  127. var img = document.createElement('img');
  128. img.style.width = printItem.width;
  129. img.style.height = printItem.height;
  130. var scratchCanvas = this.scratchCanvas;
  131. if ('toBlob' in scratchCanvas && !this.disableCreateObjectURL) {
  132. scratchCanvas.toBlob(function (blob) {
  133. img.src = _pdf.URL.createObjectURL(blob);
  134. });
  135. } else {
  136. img.src = scratchCanvas.toDataURL();
  137. }
  138. var wrapper = document.createElement('div');
  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: function performPrint() {
  147. var _this2 = this;
  148. this.throwIfInactive();
  149. return new Promise(function (resolve) {
  150. setTimeout(function () {
  151. if (!_this2.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: function throwIfInactive() {
  164. if (!this.active) {
  165. throw new Error('This print request was cancelled or completed.');
  166. }
  167. }
  168. };
  169. var print = window.print;
  170. window.print = function print() {
  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. var 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. var 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. var progressContainer = document.getElementById('printServiceOverlay');
  215. var progress = Math.round(100 * index / total);
  216. var progressBar = progressContainer.querySelector('progress');
  217. var progressPerc = progressContainer.querySelector('.relative-progress');
  218. progressBar.value = progress;
  219. l10n.get('print_progress_percent', {
  220. progress: progress
  221. }, progress + '%').then(function (msg) {
  222. progressPerc.textContent = msg;
  223. });
  224. }
  225. var hasAttachEvent = !!document.attachEvent;
  226. window.addEventListener('keydown', function (event) {
  227. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  228. window.print();
  229. if (hasAttachEvent) {
  230. return;
  231. }
  232. event.preventDefault();
  233. if (event.stopImmediatePropagation) {
  234. event.stopImmediatePropagation();
  235. } else {
  236. event.stopPropagation();
  237. }
  238. return;
  239. }
  240. }, true);
  241. if (hasAttachEvent) {
  242. document.attachEvent('onkeydown', function (event) {
  243. event = event || window.event;
  244. if (event.keyCode === 80 && event.ctrlKey) {
  245. event.keyCode = 0;
  246. return false;
  247. }
  248. });
  249. }
  250. if ('onbeforeprint' in window) {
  251. var stopPropagationIfNeeded = function stopPropagationIfNeeded(event) {
  252. if (event.detail !== 'custom' && event.stopImmediatePropagation) {
  253. event.stopImmediatePropagation();
  254. }
  255. };
  256. window.addEventListener('beforeprint', stopPropagationIfNeeded);
  257. window.addEventListener('afterprint', stopPropagationIfNeeded);
  258. }
  259. var overlayPromise;
  260. function ensureOverlay() {
  261. if (!overlayPromise) {
  262. overlayManager = _app.PDFViewerApplication.overlayManager;
  263. if (!overlayManager) {
  264. throw new Error('The overlay manager has not yet been initialized.');
  265. }
  266. overlayPromise = overlayManager.register('printServiceOverlay', document.getElementById('printServiceOverlay'), abort, true);
  267. document.getElementById('printCancel').onclick = abort;
  268. }
  269. return overlayPromise;
  270. }
  271. _app.PDFPrintServiceFactory.instance = {
  272. supportsPrinting: true,
  273. createPrintService: function createPrintService(pdfDocument, pagesOverview, printContainer, l10n) {
  274. if (activeService) {
  275. throw new Error('The print service is created and active.');
  276. }
  277. activeService = new PDFPrintService(pdfDocument, pagesOverview, printContainer, l10n);
  278. return activeService;
  279. }
  280. };