How to print a PDF with JavaScript using PDF.js (three methods)

Table of contents

    How to print a PDF with JavaScript using PDF.js (three methods)
    Outgrowing PDF.js?

    See how Nutrient Web SDK compares on rendering fidelity, annotations, forms, and support.

    TL;DR

    JavaScript can open a print dialog, but what gets printed depends on the integration. window.print() prints the current webpage. Printing through PDF.js means rendering the required pages and applying print styles first. Printing the original PDF means handing it to the browser’s PDF viewer or to a library such as Print.js(opens in a new tab). Silent printing isn’t available from ordinary browser JavaScript, and print behavior differs across browsers.

    Choose a PDF printing method

    Use the output requirements to choose an approach:

    MethodWhat gets printedMain tradeoff
    PDF.js canvases and window.print()Rendered page images in the host HTML layoutThe application controls pagination, but output is rasterized and uses memory for every rendered page
    Browser PDF viewerThe original PDF through the browser’s viewerNo canvas conversion in the application. Programmatic printing depends on browser support
    Print.js in PDF modeThe original PDF loaded into a printing frameAdds a convenience API on top of the browser’s PDF printing

    Applications that host the complete PDF.js viewer can start with its print button. The custom example below is for applications that use the PDF.js display API without the complete viewer.

    Method 1: Render every PDF page before printing

    This example prepares a short PDF for A4 portrait output. It disables printing until every page finishes rendering and displays a failure message if loading or rendering fails. It keeps all pages in memory, so it isn’t suitable unchanged for hundreds of pages or oversized drawings.

    Install PDF.js

    Create a local project and install the version used below:

    Terminal window
    mkdir pdfjs-print
    cd pdfjs-print
    npm init -y
    npm install pdfjs-dist@6.3.289

    Save a short PDF as example.pdf beside index.html and print.js. Our sample PDF is suitable for an initial test. Keep the worker and runtime resources from the same package version. For rendering basics, see the PDF.js viewer tutorial.

    Add the page and print styles

    Save this as index.html. The print stylesheet hides the controls and puts each canvas on its own sheet. The original PDF link remains available onscreen:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Print a PDF with PDF.js</title>
    <style>
    body { margin: 1rem; font-family: sans-serif; }
    canvas { display: block; max-width: 100%; height: auto; margin: 1rem auto; }
    @page { size: A4 portrait; margin: 10mm; }
    @media print {
    body { margin: 0; }
    .toolbar { display: none; }
    .pdf-page { break-after: page; break-inside: avoid; }
    .pdf-page:last-child { break-after: auto; }
    canvas {
    width: auto;
    height: auto;
    max-width: 190mm;
    max-height: 277mm;
    margin: 0 auto;
    }
    }
    </style>
    </head>
    <body>
    <div class="toolbar">
    <button id="print-button" disabled>Print rendered PDF</button>
    <p id="status" role="status">Preparing pages…</p>
    <a href="example.pdf" target="_blank" rel="noopener">Open original PDF</a>
    </div>
    <main id="pages" aria-label="PDF page previews"></main>
    <script type="module" src="print.js"></script>
    </body>
    </html>

    Wait for rendering before enabling print

    Save this as print.js. Each page has its own canvas, and rendering is sequential. The intent: "print" option requests print-quality rendering but doesn’t open a print dialog:

    import {
    getDocument,
    GlobalWorkerOptions,
    } from "./node_modules/pdfjs-dist/build/pdf.mjs";
    const assets = new URL("./node_modules/pdfjs-dist/", import.meta.url);
    GlobalWorkerOptions.workerSrc = new URL("build/pdf.worker.mjs", assets).href;
    const pages = document.getElementById("pages");
    const status = document.getElementById("status");
    const printButton = document.getElementById("print-button");
    printButton.addEventListener("click", () => window.print());
    const loadingTask = getDocument({
    url: "example.pdf",
    cMapUrl: new URL("cmaps/", assets).href,
    standardFontDataUrl: new URL("standard_fonts/", assets).href,
    wasmUrl: new URL("wasm/", assets).href,
    });
    try {
    const pdf = await loadingTask.promise;
    for (let number = 1; number <= pdf.numPages; number += 1) {
    status.textContent = `Preparing page ${number} of ${pdf.numPages}…`;
    const page = await pdf.getPage(number);
    const viewport = page.getViewport({ scale: 150 / 72 });
    const wrapper = document.createElement("section");
    wrapper.className = "pdf-page";
    const canvas = document.createElement("canvas");
    canvas.setAttribute("aria-label", `Page ${number}`);
    canvas.width = Math.ceil(viewport.width);
    canvas.height = Math.ceil(viewport.height);
    wrapper.append(canvas);
    pages.append(wrapper);
    await page.render({
    canvasContext: canvas.getContext("2d"),
    viewport,
    intent: "print",
    }).promise;
    page.cleanup();
    }
    status.textContent = `${pdf.numPages} pages ready to print.`;
    printButton.disabled = false;
    } catch (error) {
    console.error(error);
    pages.replaceChildren();
    status.textContent = "Could not prepare the PDF. Use the original PDF link.";
    } finally {
    await loadingTask.destroy();
    }

    Serve the directory and open http://localhost:8080:

    Terminal window
    npx serve . -l 8080

    The example renders at 150 dots per inch (DPI). Increasing this value improves bitmap resolution but increases memory use. The printed output is rasterized page images, so it loses selectable text, vector objects, tags, and form fields from the original PDF.

    The A4 stylesheet fits pages to the printable area. Mixed page sizes, landscape drawings, and exact physical dimensions call for the original PDF or a dedicated printing workflow. Test representative files to confirm that annotations and form values print as expected.

    Method 2: Print the original PDF with the browser viewer

    A direct link enables the user to open the PDF and use the viewer’s print command. Keep this link even when an embedded print button exists.

    For a same-origin PDF, printing from a visible iframe is also possible. Save the following as a separate HTML file next to example.pdf:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Print the original PDF</title>
    </head>
    <body>
    <button id="print-original" disabled>Print original PDF</button>
    <p id="status" role="status">Loading viewer…</p>
    <p><a href="example.pdf" target="_blank" rel="noopener">Open PDF in a new tab</a></p>
    <iframe id="pdf-frame" title="PDF preview" style="width: 100%; height: 70vh;"></iframe>
    <script>
    const frame = document.getElementById("pdf-frame");
    const button = document.getElementById("print-original");
    const status = document.getElementById("status");
    frame.addEventListener("load", () => {
    button.disabled = false;
    status.textContent = "If printing is unavailable, open the PDF in a new tab.";
    });
    button.addEventListener("click", () => {
    try {
    frame.contentWindow.focus();
    frame.contentWindow.print();
    } catch (error) {
    console.error(error);
    status.textContent = "Use the PDF link and print from the browser viewer.";
    }
    });
    frame.src = "example.pdf";
    </script>
    </body>
    </html>

    An iframe load event doesn’t confirm that the PDF viewer is ready or that the request succeeded. Some browsers ignore or restrict calls into their PDF viewer, and cross-origin frames block script access entirely. Treat the button as a convenience for supported browsers.

    This approach avoids rasterizing the PDF in the application. The browser’s print dialog controls page range, scale, and margins.

    Method 3: Print the original PDF with Print.js

    Print.js(opens in a new tab) can load a same-origin PDF and prepare its print frame. type: "pdf" prints the original file. type: "html" prints HTML content and doesn’t apply to PDF files.

    Install the library:

    Terminal window
    npm install print-js@1.6.0

    Save this as another HTML file in the same project and serve it over HTTP:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Print.js PDF example</title>
    <link rel="stylesheet" href="node_modules/print-js/dist/print.css" />
    </head>
    <body>
    <button id="print-pdf">Print PDF</button>
    <p id="status" role="status"></p>
    <a href="example.pdf" target="_blank" rel="noopener">Open original PDF</a>
    <script src="node_modules/print-js/dist/print.js"></script>
    <script>
    document.getElementById("print-pdf").addEventListener("click", () => {
    printJS({
    printable: "example.pdf",
    type: "pdf",
    showModal: true,
    onError: (error) => {
    console.error(error);
    document.getElementById("status").textContent =
    "Printing failed. Open the original PDF instead.";
    },
    });
    });
    </script>
    </body>
    </html>

    Check the library’s browser support against the target browsers. Print.js relies on the native PDF viewer, and PDF mode applies no HTML styling to the file’s contents. Keep the direct link for failures and unsupported environments.

    The video shows the original single-page version of these workflows:

    Troubleshoot missing pages and blank output

    • Only one page prints — Rendering getPage(1) only prepares the first page. Render every required page or print the original file.
    • Blank canvas — Wait for page.render(...).promise before enabling printing.
    • Extra blank sheets — Check print margins, page dimensions, and page breaks, including the final page.
    • Cross-origin errors — PDF.js requests need cross-origin resource sharing (CORS) permission. Script access to an iframe has separate same-origin restrictions.
    • Memory pressure — Reduce resolution, limit document size, or use the complete viewer’s print workflow rather than keeping every page canvas.
    • No dialog — Trigger printing from a user action and offer the original PDF as a fallback.

    Printing with Nutrient Web SDK

    Nutrient Web SDK provides a print UI and a programmatic print API. Its two printing modes differ in output. Document object model (DOM) mode prints rendered bitmaps. Export-PDF mode prints a generated PDF and, in some browsers, opens it in a separate tab instead.

    Evaluate forms, annotations, document size, and target browsers with the intended mode. The Nutrient vs. PDF.js comparison covers the differences beyond printing, and when to move on from PDF.js covers the upgrade decision. Start with the demo or free trial to evaluate an SDK integration.

    FAQ

    Does `window.print()` print the original PDF?

    No. It prints the current document. If that document contains PDF.js canvases, it prints those rendered images and the applicable HTML layout.

    How do I print every page with PDF.js?

    Use the complete viewer’s print command, or render every required page and wait for all render tasks before printing. A single canvas showing the current page won’t automatically print the rest.

    Can I print without showing a dialog?

    Ordinary browser JavaScript opens a user-controlled print flow. Silent printing requires a separately managed environment, such as an explicitly configured kiosk or native application.

    Does Print.js preserve the original PDF?

    PDF mode loads the original file into its printing workflow. HTML mode prints rendered HTML instead.

    Why keep an open-PDF link beside the print button?

    Embedded PDF and programmatic print support vary. A direct link gives users another way to open the document and use their viewer’s print controls.

    Hulya Masharipov

    Hulya Masharipov

    Technical Writer

    Hulya is a frontend web developer and technical writer who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

    Explore related topics

    Try for free Add a complete PDF viewer to your app