pdf_print_service.js 8.3 KB

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