pdf_print_service.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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('./ui_utils');
  21. var _overlay_manager = require('./overlay_manager');
  22. var _pdfjs = require('./pdfjs');
  23. var _app = require('./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 layout() {
  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 destroy() {
  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 renderPages() {
  96. var _this = this;
  97. var pageCount = this.pagesOverview.length;
  98. var renderNextPage = function renderNextPage(resolve, reject) {
  99. _this.throwIfInactive();
  100. if (++_this.currentPage >= pageCount) {
  101. renderProgress(pageCount, pageCount);
  102. resolve();
  103. return;
  104. }
  105. var index = _this.currentPage;
  106. renderProgress(index, pageCount);
  107. renderPage(_this, _this.pdfDocument, index + 1, _this.pagesOverview[index]).then(_this.useRenderedPage.bind(_this)).then(function () {
  108. renderNextPage(resolve, reject);
  109. }, reject);
  110. };
  111. return new Promise(renderNextPage);
  112. },
  113. useRenderedPage: function useRenderedPage(printItem) {
  114. this.throwIfInactive();
  115. var img = document.createElement('img');
  116. img.style.width = printItem.width;
  117. img.style.height = printItem.height;
  118. var scratchCanvas = this.scratchCanvas;
  119. if ('toBlob' in scratchCanvas && !_pdfjs.PDFJS.disableCreateObjectURL) {
  120. scratchCanvas.toBlob(function (blob) {
  121. img.src = URL.createObjectURL(blob);
  122. });
  123. } else {
  124. img.src = scratchCanvas.toDataURL();
  125. }
  126. var wrapper = document.createElement('div');
  127. wrapper.appendChild(img);
  128. this.printContainer.appendChild(wrapper);
  129. return new Promise(function (resolve, reject) {
  130. img.onload = resolve;
  131. img.onerror = reject;
  132. });
  133. },
  134. performPrint: function performPrint() {
  135. var _this2 = this;
  136. this.throwIfInactive();
  137. return new Promise(function (resolve) {
  138. setTimeout(function () {
  139. if (!_this2.active) {
  140. resolve();
  141. return;
  142. }
  143. print.call(window);
  144. setTimeout(resolve, 20);
  145. }, 0);
  146. });
  147. },
  148. get active() {
  149. return this === activeService;
  150. },
  151. throwIfInactive: function throwIfInactive() {
  152. if (!this.active) {
  153. throw new Error('This print request was cancelled or completed.');
  154. }
  155. }
  156. };
  157. var print = window.print;
  158. window.print = function print() {
  159. if (activeService) {
  160. console.warn('Ignored window.print() because of a pending print job.');
  161. return;
  162. }
  163. ensureOverlay().then(function () {
  164. if (activeService) {
  165. _overlay_manager.OverlayManager.open('printServiceOverlay');
  166. }
  167. });
  168. try {
  169. dispatchEvent('beforeprint');
  170. } finally {
  171. if (!activeService) {
  172. console.error('Expected print service to be initialized.');
  173. if (_overlay_manager.OverlayManager.active === 'printServiceOverlay') {
  174. _overlay_manager.OverlayManager.close('printServiceOverlay');
  175. }
  176. return;
  177. }
  178. var activeServiceOnEntry = activeService;
  179. activeService.renderPages().then(function () {
  180. return activeServiceOnEntry.performPrint();
  181. }).catch(function () {}).then(function () {
  182. if (activeServiceOnEntry.active) {
  183. abort();
  184. }
  185. });
  186. }
  187. };
  188. function dispatchEvent(eventType) {
  189. var event = document.createEvent('CustomEvent');
  190. event.initCustomEvent(eventType, false, false, 'custom');
  191. window.dispatchEvent(event);
  192. }
  193. function abort() {
  194. if (activeService) {
  195. activeService.destroy();
  196. dispatchEvent('afterprint');
  197. }
  198. }
  199. function renderProgress(index, total) {
  200. var progressContainer = document.getElementById('printServiceOverlay');
  201. var progress = Math.round(100 * index / total);
  202. var progressBar = progressContainer.querySelector('progress');
  203. var progressPerc = progressContainer.querySelector('.relative-progress');
  204. progressBar.value = progress;
  205. progressPerc.textContent = _ui_utils.mozL10n.get('print_progress_percent', { progress: progress }, progress + '%');
  206. }
  207. var hasAttachEvent = !!document.attachEvent;
  208. window.addEventListener('keydown', function (event) {
  209. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  210. window.print();
  211. if (hasAttachEvent) {
  212. return;
  213. }
  214. event.preventDefault();
  215. if (event.stopImmediatePropagation) {
  216. event.stopImmediatePropagation();
  217. } else {
  218. event.stopPropagation();
  219. }
  220. return;
  221. }
  222. }, true);
  223. if (hasAttachEvent) {
  224. document.attachEvent('onkeydown', function (event) {
  225. event = event || window.event;
  226. if (event.keyCode === 80 && event.ctrlKey) {
  227. event.keyCode = 0;
  228. return false;
  229. }
  230. });
  231. }
  232. if ('onbeforeprint' in window) {
  233. var stopPropagationIfNeeded = function stopPropagationIfNeeded(event) {
  234. if (event.detail !== 'custom' && event.stopImmediatePropagation) {
  235. event.stopImmediatePropagation();
  236. }
  237. };
  238. window.addEventListener('beforeprint', stopPropagationIfNeeded);
  239. window.addEventListener('afterprint', stopPropagationIfNeeded);
  240. }
  241. var overlayPromise;
  242. function ensureOverlay() {
  243. if (!overlayPromise) {
  244. overlayPromise = _overlay_manager.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: function createPrintService(pdfDocument, pagesOverview, printContainer) {
  252. if (activeService) {
  253. throw new Error('The print service is created and active.');
  254. }
  255. activeService = new PDFPrintService(pdfDocument, pagesOverview, printContainer);
  256. return activeService;
  257. }
  258. };
  259. exports.PDFPrintService = PDFPrintService;