pdf_print_service.js 9.3 KB

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