pdf_print_service.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 _app = require('./app');
  22. var _pdfjs = require('./pdfjs');
  23. var activeService = null;
  24. var overlayManager = 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 (overlayManager.active !== 'printServiceOverlay') {
  90. return;
  91. }
  92. 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. 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. ensureOverlay().then(function () {
  174. if (overlayManager.active === 'printServiceOverlay') {
  175. overlayManager.close('printServiceOverlay');
  176. }
  177. });
  178. return;
  179. }
  180. var activeServiceOnEntry = activeService;
  181. activeService.renderPages().then(function () {
  182. return activeServiceOnEntry.performPrint();
  183. }).catch(function () {}).then(function () {
  184. if (activeServiceOnEntry.active) {
  185. abort();
  186. }
  187. });
  188. }
  189. };
  190. function dispatchEvent(eventType) {
  191. var event = document.createEvent('CustomEvent');
  192. event.initCustomEvent(eventType, false, false, 'custom');
  193. window.dispatchEvent(event);
  194. }
  195. function abort() {
  196. if (activeService) {
  197. activeService.destroy();
  198. dispatchEvent('afterprint');
  199. }
  200. }
  201. function renderProgress(index, total) {
  202. var progressContainer = document.getElementById('printServiceOverlay');
  203. var progress = Math.round(100 * index / total);
  204. var progressBar = progressContainer.querySelector('progress');
  205. var progressPerc = progressContainer.querySelector('.relative-progress');
  206. progressBar.value = progress;
  207. progressPerc.textContent = _ui_utils.mozL10n.get('print_progress_percent', { progress: progress }, progress + '%');
  208. }
  209. var hasAttachEvent = !!document.attachEvent;
  210. window.addEventListener('keydown', function (event) {
  211. if (event.keyCode === 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
  212. window.print();
  213. if (hasAttachEvent) {
  214. return;
  215. }
  216. event.preventDefault();
  217. if (event.stopImmediatePropagation) {
  218. event.stopImmediatePropagation();
  219. } else {
  220. event.stopPropagation();
  221. }
  222. return;
  223. }
  224. }, true);
  225. if (hasAttachEvent) {
  226. document.attachEvent('onkeydown', function (event) {
  227. event = event || window.event;
  228. if (event.keyCode === 80 && event.ctrlKey) {
  229. event.keyCode = 0;
  230. return false;
  231. }
  232. });
  233. }
  234. if ('onbeforeprint' in window) {
  235. var stopPropagationIfNeeded = function stopPropagationIfNeeded(event) {
  236. if (event.detail !== 'custom' && event.stopImmediatePropagation) {
  237. event.stopImmediatePropagation();
  238. }
  239. };
  240. window.addEventListener('beforeprint', stopPropagationIfNeeded);
  241. window.addEventListener('afterprint', stopPropagationIfNeeded);
  242. }
  243. var overlayPromise;
  244. function ensureOverlay() {
  245. if (!overlayPromise) {
  246. overlayManager = _app.PDFViewerApplication.overlayManager;
  247. if (!overlayManager) {
  248. throw new Error('The overlay manager has not yet been initialized.');
  249. }
  250. overlayPromise = overlayManager.register('printServiceOverlay', document.getElementById('printServiceOverlay'), abort, true);
  251. document.getElementById('printCancel').onclick = abort;
  252. }
  253. return overlayPromise;
  254. }
  255. _app.PDFPrintServiceFactory.instance = {
  256. supportsPrinting: true,
  257. createPrintService: function createPrintService(pdfDocument, pagesOverview, printContainer) {
  258. if (activeService) {
  259. throw new Error('The print service is created and active.');
  260. }
  261. activeService = new PDFPrintService(pdfDocument, pagesOverview, printContainer);
  262. return activeService;
  263. }
  264. };
  265. exports.PDFPrintService = PDFPrintService;