UNPKG

pdfjs-vue-print

Version:

Example Vue 3 project using pdf.js to build a simple custom PDF.js viewer and print service.

445 lines (369 loc) 11.7 kB
/* Copyright 2016 Mozilla Foundation * Copyright 2022 Drew Letcher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; import { PixelsPerInch } from "pdfjs-dist"; import { PDFPrintServiceFactory } from "./print_service_factory.js"; var _activeService = null; var _dialog = null; // override the factory function PDFPrintServiceFactory.instance = { supportsPrinting: true, createPrintService( pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise, l10n) { if (_activeService) { throw new Error("The print service is created and active."); } _activeService = new PDFPrintService({ pdfDocument, pagesOverview, printContainer, printResolution, optionalContentConfigPromise, l10n }); return _activeService; }, }; export default class PDFPrintService { constructor(options) { this.pdfDocument = options.pdfDocument; this.pagesOverview = options.pagesOverview; this.printContainer = options.printContainer; this._printResolution = options.printResolution || 150; this._optionalContentConfigPromise = options.optionalContentConfigPromise || this.pdfDocument.getOptionalContentConfig(); this.l10n = options.l10n; this.currentPage = -1; // The temporary canvas where renderPage paints one page image at a time. this.scratchCanvas = document.createElement("canvas"); } /** * layout */ layout() { this.throwIfInactive(); const body = document.querySelector("body"); body.setAttribute("data-pdfjsprinting", true); const hasEqualPageSizes = this.pagesOverview.every( (size) => { return ( size.width === this.pagesOverview[ 0 ].width && size.height === this.pagesOverview[ 0 ].height ); }, this); if (!hasEqualPageSizes) { console.warn( "Not all pages have the same size. The printed " + "result may be incorrect!" ); } // Insert a @page + size rule to make sure that the page size is correctly // set. Note that we assume that all pages have the same size, because // variable-size pages are not supported yet (e.g. in Chrome & Firefox). // TODO(robwu): Use named pages when size calculation bugs get resolved // (e.g. https://crbug.com/355116) AND when support for named pages is // added (http://www.w3.org/TR/css3-page/#using-named-pages). // In browsers where @page + size is not supported (such as Firefox, // https://bugzil.la/851441), the next stylesheet will be ignored and the // user has to select the correct paper size in the UI if wanted. this.pageStyleSheet = document.createElement("style"); const pageSize = this.pagesOverview[ 0 ]; this.pageStyleSheet.textContent = "@page { size: " + pageSize.width + "pt " + pageSize.height + "pt;}"; body.append(this.pageStyleSheet); } /** * * @returns */ async destroy() { if (_activeService !== this) { // |_activeService| cannot be replaced without calling destroy() first, // so if it differs then an external consumer has a stale reference to us. return; } this.printContainer.textContent = ""; const body = document.querySelector("body"); body.removeAttribute("data-pdfjsprinting"); if (this.pageStyleSheet) { this.pageStyleSheet.remove(); this.pageStyleSheet = null; } this.scratchCanvas.width = this.scratchCanvas.height = 0; this.scratchCanvas = null; _activeService = null; closeDialog(); } /** * * @returns */ async renderPages() { console.log("renderPages"); if (this.pdfDocument.isPureXfa) { console.log("isPureXfa"); //getXfaHtmlForPrinting(this.printContainer, this.pdfDocument); return; } const pageCount = this.pagesOverview.length; const renderNextPage = async () => { this.throwIfInactive(); if (++this.currentPage >= pageCount) { console.log("renderPages done") renderProgress(pageCount, pageCount, this.l10n); return; } const index = this.currentPage; renderProgress(index, pageCount, this.l10n); await renderPage( this, this.pdfDocument, /* pageNumber = */ index + 1, this.pagesOverview[ index ], this._printResolution, this._optionalContentConfigPromise ); await this.useRenderedPage(); await renderNextPage(); }; await renderNextPage(); closeDialog(); } /** * * @returns */ useRenderedPage() { this.throwIfInactive(); const img = document.createElement("img"); const scratchCanvas = this.scratchCanvas; if ("toBlob" in scratchCanvas) { scratchCanvas.toBlob(function (blob) { img.src = URL.createObjectURL(blob); }); } else { img.src = scratchCanvas.toDataURL(); } const wrapper = document.createElement("div"); wrapper.className = "printedPage"; wrapper.append(img); this.printContainer.append(wrapper); return new Promise(function (resolve, reject) { img.onload = resolve; img.onerror = reject; }); } /** * * @returns */ performPrint() { console.log("performPrint"); this.throwIfInactive(); return new Promise(resolve => { // Push window.print in the macrotask queue to avoid being affected by // the deprecation of running print() code in a microtask, see // https://github.com/mozilla/pdf.js/issues/7547. setTimeout(() => { if (!this.active) { resolve(); return; } console.log("_print.call(window)"); _print.call(window); // Delay promise resolution in case print() was not synchronous. setTimeout(resolve, 20); // Tidy-up. }, 0); }); } get active() { return this === _activeService; } throwIfInactive() { if (!this.active) { throw new Error("This print request was cancelled or completed."); } } }; //////// module level functions //////// ///// rendering // Renders the page to the canvas of the given print service, // and returns a promise for the results async function renderPage( _activeService, pdfDocument, pageNumber, size, printResolution, optionalContentConfigPromise ) { const scratchCanvas = _activeService.scratchCanvas; // The size of the canvas in pixels for printing. const PRINT_UNITS = printResolution / PixelsPerInch.PDF; scratchCanvas.width = Math.floor(size.width * PRINT_UNITS); scratchCanvas.height = Math.floor(size.height * PRINT_UNITS); const ctx = scratchCanvas.getContext("2d"); ctx.save(); ctx.fillStyle = "rgb(255, 255, 255)"; ctx.fillRect(0, 0, scratchCanvas.width, scratchCanvas.height); ctx.restore(); let pdfPage = await pdfDocument.getPage(pageNumber); const renderContext = { canvasContext: ctx, transform: [ PRINT_UNITS, 0, 0, PRINT_UNITS, 0, 0 ], viewport: pdfPage.getViewport({ scale: 1, rotation: size.rotation }), intent: "print", optionalContentConfigPromise }; return pdfPage.render(renderContext).promise; } async function renderProgress(index, total, l10n) { const progress = Math.round((100 * index) / total); let msg = progress + "%"; if (l10n) msg = await l10n.get("print_progress_percent", { progress }); openDialog(); const progressBar = _dialog.querySelector("progress"); progressBar.value = progress; const progressPerc = _dialog.querySelector(".relative-progress"); progressPerc.textContent = " " + msg; } function dispatchEvent(eventType) { console.log("dispatchEvent " + eventType); const event = document.createEvent("CustomEvent"); event.initCustomEvent(eventType, false, false, "custom"); window.dispatchEvent(event); } function abort() { console.log("abort"); if (_activeService) { _activeService.destroy(); dispatchEvent("afterprint"); } } ////// event listeners var _print = null; var _stopPropagationIfNeeded = null; // override the normal window.print function function install() { console.log("PrintService install") if (_print) { console.warn("print routine already installed") return; } // save window.print function _print = window.print; window.print = async () => { if (_activeService) { console.warn("Ignored window.print() because of a pending print job."); return; } if (_activeService) { openDialog(); } try { dispatchEvent("beforeprint"); if (!_activeService) { console.error("Expected print service to be initialized."); closeDialog(); return; // eslint-disable-line no-unsafe-finally } await _activeService.renderPages(); await _activeService.performPrint(); dispatchEvent("afterprint"); } catch (err) { console.error(err.message); // Ignore any error messages. } finally { // aborts acts on the "active" print request, so we need to check // whether the print request (_activeService) is still active. // Without the check, an unrelated print request (created after aborting // this print request while the pages were being generated) would be // aborted. if (_activeService && _activeService.active) { console.log("calling abort"); abort(); } } } window.addEventListener( "keydown", onCtrlP, true ); if ("onbeforeprint" in window) { // Do not propagate before/afterprint events when they are not triggered // from within this polyfill. (FF / Chrome 63+). _stopPropagationIfNeeded = (event) => { if (event.detail !== "custom") { event.stopImmediatePropagation(); } }; window.addEventListener("beforeprint", _stopPropagationIfNeeded); window.addEventListener("afterprint", _stopPropagationIfNeeded); } } function remove() { console.log("PrintService.remove") if (!print) { console.warn("print routine not installed") return; } window.print = _print; _print = null; window.removeEventListener( "keydown", onCtrlP, true ); if (_stopPropagationIfNeeded) { window.removeEventListener("beforeprint", _stopPropagationIfNeeded); window.removeEventListener("afterprint", _stopPropagationIfNeeded); _stopPropagationIfNeeded = null; } } function onCtrlP(event) { // Intercept Cmd/Ctrl + P in all browsers. // Also intercept Cmd/Ctrl + Shift + P in Chrome and Opera if ( event.keyCode === /* P= */ 80 && (event.ctrlKey || event.metaKey) && !event.altKey && (!event.shiftKey || window.chrome || window.opera) ) { window.print(); event.preventDefault(); event.stopImmediatePropagation(); } } function openDialog() { if (_dialog) return; _dialog = document.getElementById("printServiceDialog"); _dialog.addEventListener("close", abort); _dialog.showModal(); } function closeDialog() { if (!_dialog) return; _dialog.close(); _dialog.removeEventListener("close", abort); _dialog = null; } export { PDFPrintService, install, remove };