pdf_print_service.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /* Copyright 2017 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. Object.defineProperty(exports, "__esModule", {
  17. value: true
  18. });
  19. exports.PDFPrintService = undefined;
  20. var _ui_utils = require('pdfjs-web/ui_utils');
  21. var _overlay_manager = require('pdfjs-web/overlay_manager');
  22. var _pdfjs = require('pdfjs-web/pdfjs');
  23. var _app = require('pdfjs-web/app');
  24. var activeService = null;
  25. function renderPage(activeServiceOnEntry, pdfDocument, pageNumber, size) {
  26. var scratchCanvas = activeService.scratchCanvas;
  27. var PRINT_RESOLUTION = 150;
  28. var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
  29. scratchCanvas.width = Math.floor(size.width * PRINT_UNITS);
  30. scratchCanvas.height = Math.floor(size.height * PRINT_UNITS);
  31. var width = Math.floor(size.width * _ui_utils.CSS_UNITS) + 'px';
  32. var height = Math.floor(size.height * _ui_utils.CSS_UNITS) + 'px';
  33. var ctx = scratchCanvas.getContext('2d');
  34. ctx.save();
  35. ctx.fillStyle = 'rgb(255, 255, 255)';
  36. ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height);
  37. ctx.restore();
  38. return pdfDocument.getPage(pageNumber).then(function (pdfPage) {
  39. var renderContext = {
  40. canvasContext: ctx,
  41. transform: [PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0],
  42. viewport: pdfPage.getViewport(1, size.rotation),
  43. intent: 'print'
  44. };
  45. return pdfPage.render(renderContext).promise;
  46. }).then(function () {
  47. return {
  48. width: width,
  49. height: height
  50. };
  51. });
  52. }
  53. function PDFPrintService(pdfDocument, pagesOverview, printContainer) {
  54. this.pdfDocument = pdfDocument;
  55. this.pagesOverview = pagesOverview;
  56. this.printContainer = printContainer;
  57. this.currentPage = -1;
  58. this.scratchCanvas = document.createElement('canvas');
  59. }
  60. PDFPrintService.prototype = {
  61. layout: function () {
  62. this.throwIfInactive();
  63. var body = document.querySelector('body');
  64. body.setAttribute('data-pdfjsprinting', true);
  65. var hasEqualPageSizes = this.pagesOverview.every(function (size) {
  66. return size.width === this.pagesOverview[0].width && size.height === this.pagesOverview[0].height;
  67. }, this);
  68. if (!hasEqualPageSizes) {
  69. console.warn('Not all pages have the same size. The printed ' + 'result may be incorrect!');
  70. }
  71. this.pageStyleSheet = document.createElement('style');
  72. var pageSize = this.pagesOverview[0];
  73. this.pageStyleSheet.textContent = '@supports ((size:A4) and (size:1pt 1pt)) {' + '@page { size: ' + pageSize.width + 'pt ' + pageSize.height + 'pt;}' + '}';
  74. body.appendChild(this.pageStyleSheet);
  75. },
  76. destroy: function () {
  77. if (activeService !== this) {
  78. return;
  79. }
  80. this.printContainer.textContent = '';
  81. if (this.pageStyleSheet && this.pageStyleSheet.parentNode) {
  82. this.pageStyleSheet.parentNode.removeChild(this.pageStyleSheet);
  83. this.pageStyleSheet = null;
  84. }
  85. this.scratchCanvas.width = this.scratchCanvas.height = 0;
  86. this.scratchCanvas = null;
  87. activeService = null;
  88. ensureOverlay().then(function () {
  89. if (_overlay_manager.OverlayManager.active !== 'printServiceOverlay') {
  90. return;
  91. }
  92. _overlay_manager.OverlayManager.close('printServiceOverlay');
  93. });
  94. },
  95. renderPages: function () {
  96. var pageCount = this.pagesOverview.length;
  97. var renderNextPage = function (resolve, reject) {
  98. this.throwIfInactive();
  99. if (++this.currentPage >= pageCount) {
  100. renderProgress(pageCount, pageCount);
  101. resolve();
  102. return;
  103. }
  104. var index = this.currentPage;
  105. renderProgress(index, pageCount);
  106. renderPage(this, this.pdfDocument, index + 1, this.pagesOverview[index]).then(this.useRenderedPage.bind(this)).then(function () {
  107. renderNextPage(resolve, reject);
  108. }, reject);
  109. }.bind(this);
  110. return new Promise(renderNextPage);
  111. },
  112. useRenderedPage: function (printItem) {
  113. this.throwIfInactive();
  114. var img = document.createElement('img');
  115. img.style.width = printItem.width;
  116. img.style.height = printItem.height;
  117. var scratchCanvas = this.scratchCanvas;
  118. if ('toBlob' in scratchCanvas && !_pdfjs.PDFJS.disableCreateObjectURL) {
  119. scratchCanvas.toBlob(function (blob) {
  120. img.src = URL.createObjectURL(blob);
  121. });
  122. } else {
  123. img.src = scratchCanvas.toDataURL();
  124. }
  125. var wrapper = document.createElement('div');
  126. wrapper.appendChild(img);
  127. this.printContainer.appendChild(wrapper);
  128. return new Promise(function (resolve, reject) {
  129. img.onload = resolve;
  130. img.onerror = reject;
  131. });
  132. },
  133. performPrint: function () {
  134. this.throwIfInactive();
  135. return new Promise(function (resolve) {
  136. setTimeout(function () {
  137. if (!this.active) {
  138. resolve();
  139. return;
  140. }
  141. print.call(window);
  142. setTimeout(resolve, 20);
  143. }.bind(this), 0);
  144. }.bind(this));
  145. },
  146. get active() {
  147. return this === activeService;
  148. },
  149. throwIfInactive: function () {
  150. if (!this.active) {
  151. throw new Error('This print request was cancelled or completed.');
  152. }
  153. }
  154. };
  155. var print = window.print;
  156. window.print = function print() {
  157. if (activeService) {
  158. console.warn('Ignored window.print() because of a pending print job.');
  159. return;
  160. }
  161. ensureOverlay().then(function () {
  162. if (activeService) {
  163. _overlay_manager.OverlayManager.open('printServiceOverlay');
  164. }
  165. });
  166. try {
  167. dispatchEvent('beforeprint');
  168. } finally {
  169. if (!activeService) {
  170. console.error('Expected print service to be initialized.');
  171. if (_overlay_manager.OverlayManager.active === 'printServiceOverlay') {
  172. _overlay_manager.OverlayManager.close('printServiceOverlay');
  173. }
  174. return;
  175. }
  176. var activeServiceOnEntry = activeService;
  177. activeService.renderPages().then(function () {
  178. return activeServiceOnEntry.performPrint();
  179. }).catch(function () {}).then(function () {
  180. if (activeServiceOnEntry.active) {
  181. abort();
  182. }
  183. });
  184. }
  185. };
  186. function dispatchEvent(eventType) {
  187. var event = document.createEvent('CustomEvent');
  188. event.initCustomEvent(eventType, false, false, 'custom');
  189. window.dispatchEvent(event);
  190. }
  191. function abort() {
  192. if (activeService) {
  193. activeService.destroy();
  194. dispatchEvent('afterprint');
  195. }
  196. }
  197. function renderProgress(index, total) {
  198. var progressContainer = document.getElementById('printServiceOverlay');
  199. var progress = Math.round(100 * index / total);
  200. var progressBar = progressContainer.querySelector('progress');
  201. var progressPerc = progressContainer.querySelector('.relative-progress');
  202. progressBar.value = progress;
  203. progressPerc.textContent = _ui_utils.mozL10n.get('print_progress_percent', { progress: progress }, progress + '%');
  204. }
  205. var hasAttachEvent = !!document.attachEvent;
  206. window.addEventListener('keydown', function (event) {
  207. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  208. window.print();
  209. if (hasAttachEvent) {
  210. return;
  211. }
  212. event.preventDefault();
  213. if (event.stopImmediatePropagation) {
  214. event.stopImmediatePropagation();
  215. } else {
  216. event.stopPropagation();
  217. }
  218. return;
  219. }
  220. }, true);
  221. if (hasAttachEvent) {
  222. document.attachEvent('onkeydown', function (event) {
  223. event = event || window.event;
  224. if (event.keyCode === 80 && event.ctrlKey) {
  225. event.keyCode = 0;
  226. return false;
  227. }
  228. });
  229. }
  230. if ('onbeforeprint' in window) {
  231. var stopPropagationIfNeeded = function (event) {
  232. if (event.detail !== 'custom' && event.stopImmediatePropagation) {
  233. event.stopImmediatePropagation();
  234. }
  235. };
  236. window.addEventListener('beforeprint', stopPropagationIfNeeded);
  237. window.addEventListener('afterprint', stopPropagationIfNeeded);
  238. }
  239. var overlayPromise;
  240. function ensureOverlay() {
  241. if (!overlayPromise) {
  242. overlayPromise = _overlay_manager.OverlayManager.register('printServiceOverlay', document.getElementById('printServiceOverlay'), abort, true);
  243. document.getElementById('printCancel').onclick = abort;
  244. }
  245. return overlayPromise;
  246. }
  247. _app.PDFPrintServiceFactory.instance = {
  248. supportsPrinting: true,
  249. createPrintService: function (pdfDocument, pagesOverview, printContainer) {
  250. if (activeService) {
  251. throw new Error('The print service is created and active.');
  252. }
  253. activeService = new PDFPrintService(pdfDocument, pagesOverview, printContainer);
  254. return activeService;
  255. }
  256. };
  257. exports.PDFPrintService = PDFPrintService;