How to print PDFs in the browser with PDF.js (three easy methods)

How to print PDFs in the browser with PDF.js (three easy methods)
TL;DR

Learn how to print PDFs directly from your JavaScript web application using PDF.js. This tutorial introduces three practical approaches.

MethodUse casePrint qualitySetupControl
window.print()Basic in-browser printing of canvasModerateMinimalLow
Print.jsPrint a styled canvas or HTML elementModerateModerateHigh
iframeNative PDF printing from file sourceHighModerateMedium
  • Use window.print() if you want a fast and easy solution.
  • Use Print.js(opens in a new tab) if you need more control over layout and styles.
  • Use an iframe for the most accurate print output from the original PDF file.

If you’re building a web application with in-browser PDF viewing and printing features, PDF.js(opens in a new tab) is one of the most reliable client-side libraries available. This tutorial will demonstrate how to render and print PDF documents using PDF.js and explore three different techniques to handle the printing process:

Each method has unique advantages and tradeoffs depending on your project requirements.

Prerequisites

You’ll need:

  • A basic HTML/JS environment

  • A sample PDF file (example.pdf)

  • A modern browser that supports JavaScript modules

Create two files in your project directory:

  • index.html — Contains the layout and loads PDF.js
  • print.js — Contains the logic for loading and printing the PDF

Render a PDF with PDF.js

You can install PDF.js via npm or use a CDN. Here’s the CDN method for simplicity:

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.6.82/pdf.min.mjs"></script>

Create a basic HTML structure:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Print PDF Example</title>
<style>
#pdf-canvas {
border: 1px solid #ccc;
display: block;
margin: 1rem auto;
}
@media print {
.toolbar {
display: none;
}
}
</style>
</head>
<body>
<div class="toolbar">
<button id="print-button">Print PDF</button>
</div>
<canvas id="pdf-canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.6.82/pdf.min.mjs"></script>
<script type="module" src="print.js"></script>
</body>
</html>

Render a PDF on canvas:

const url = "example.pdf"; // Replace with the path to your PDF file.
import {
GlobalWorkerOptions,
getDocument,
} from "https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.min.mjs";
GlobalWorkerOptions.workerSrc =
"https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.mjs";
const loadingTask = getDocument(url);
loadingTask.promise.then((pdf) => {
pdf.getPage(1).then((page) => {
const scale = 1.5;
const viewport = page.getViewport({ scale });
const canvas = document.getElementById("pdf-canvas");
const context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({ canvasContext: context, viewport: viewport });
});
});

This code uses PDF.js to load the first page of a PDF file and render it onto a <canvas> element in the browser. It sets the canvas size based on the PDF page dimensions and draws the page using the render() method.

To learn more about how to render PDFs with PDF.js, check out our PDF.js tutorial.

Method 1: Print PDFs with window.print()

Once your PDF is rendered, add this print handler:

document.getElementById("print-button").addEventListener("click", () => {
window.print();
});

The window.print() method triggers the browser’s print dialog, and whatever is visible on the screen — in this case, your rendered PDF page in the canvas — will be sent to the printer.

How it works

  1. PDF.js is loaded via a CDN using native ES module syntax.
  2. The PDF file (example.pdf) is rendered to a <canvas> element.
  3. A print button triggers the window.print() method, printing the contents of the page.
  4. To keep the UI clean, the @media print CSS rule hides the toolbar during printing.

Benefits

  • Lightweight — Requires only a browser and two files — no frameworks or bundlers.
  • Standards-based — Uses native JavaScript modules and web APIs.
  • Simple integration — Ideal for applications that need to preview or print a single PDF page quickly.

Limitations

  • Canvas-based output — Printing from canvas may not preserve the full fidelity of vector PDFs (e.g. selectable text or embedded fonts).
  • Single page only — The example renders and prints only the first page. Extending this to support multipage printing requires additional logic.
  • No print preview — This implementation uses the default browser print dialog without customization.

Method 2: Print the original PDF file via hidden iframe (best quality)

For higher fidelity and full-document printing, consider printing the actual PDF file using a hidden iframe. This uses the browser’s native PDF rendering engine.

Create another button in your HTML:

<button id="iframe-print-button">Print original PDF</button>

Add the following JavaScript to handle printing via an iframe:

document.getElementById("iframe-print-button").addEventListener("click", () => {
const iframe = document.createElement("iframe");
iframe.style.position = "fixed";
iframe.style.right = "100%";
iframe.style.bottom = "100%";
iframe.src = "example.pdf"; // Your PDF path
iframe.onload = () => {
iframe.contentWindow.focus();
iframe.contentWindow.print();
};
document.body.appendChild(iframe);
});

This method preserves vector graphics, fonts, and page structure with better print accuracy.

Benefits

  • High print fidelity — The browser’s built-in PDF viewer handles rendering, ensuring accurate fonts, vector graphics, and layout.
  • Full-document support — Unlike canvas-based rendering, this method prints all pages of the PDF by default.
  • No preprocessing required — You don’t need to render the PDF with JavaScript — just provide a URL to the file.

Limitations

  • Requires direct file access — The PDF must be accessible via a direct URL or relative path; it won’t work with canvas-rendered content.
  • Limited print customization — You can’t style or modify the document before printing — what you see is what you get.
  • Browser-dependent output — Print behavior and output quality may vary slightly across different browsers and platforms.

Method 3: Printing PDFs with Print.js for better control

While window.print() offers a fast way to print visible content like a canvas, it doesn’t provide fine-grained control over layout or formatting. If your use case requires more flexibility — such as custom headers, styling, or printing specific HTML elements — Print.js(opens in a new tab) is a strong alternative.

Print.js allows you to print HTML elements, PDF files, or JSON data. In this example, you’ll use it to print the PDF content rendered in a <canvas> element.

Setup

Include the Print.js CSS and JS files in your HTML:

<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/print-js/1.6.0/print.css"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/print-js/1.6.0/print.js"></script>

Place the <link> in your <head> section and the <script> at the end of the <body> (or within your module if desired).

Add another button for printing with Print.js:

<button id="printjs-button">Print with Print.js</button>

Add the following JavaScript to handle printing with Print.js:

document.getElementById("printjs-button").addEventListener("click", () => {
// Trigger Print.js after render is done.
printJS({
printable: "pdf-canvas",
type: "html",
targetStyles: ["*"],
});
});

This call instructs Print.js to print the HTML element with the pdf-canvas ID. The type: "html" setting specifies that the content is standard HTML, and targetStyles: ["*"] ensures all applied styles (e.g. canvas borders or dimensions) are preserved in the print output.

Benefits

  • Improved layout control — Customize styling via CSS.

  • Specific element targeting — Only print designated DOM nodes.

  • Preview flexibility — Easily test different formats without altering document structure.

Limitations

  • Canvas quality — Like window.print(), this method still prints rasterized content from the <canvas>, which may result in lower resolution compared to native PDF printing.

  • No native PDF rendering — If high-fidelity vector output is required, printing the original PDF via an <iframe> remains the best approach.

You can find the full working demo code for all three PDF printing methods on GitHub(opens in a new tab).

Summary: Which print PDF method is best?

MethodPrint qualityCustom stylingComplexityBest use case
window.print()Low–MediumLimitedLowPrototyping or simple apps
Print.jsMediumGoodMediumStyled HTML sections
IframeHighBrowser nativeMediumFull-quality printing

Consider using a commercial SDK for robust PDF printing

If your application requires high-fidelity, multipage PDF printing, annotations, form support, or document editing, a commercial SDK may be more appropriate.

Nutrient Web SDK provides advanced PDF viewing and printing capabilities with out-of-the-box support for React, Angular, and Vue. It supports:

  • Multipage and high-resolution printing
  • Form filling, signatures, and annotations
  • Print-ready vector rendering and embedded fonts
  • Easy integration and theming

Conclusion

This tutorial covered three effective ways to print PDFs in the browser using PDF.js:

  • window.print() for fast, minimal setup using canvas rendering
  • Print.js for styled, HTML-based printing of specific elements
  • A hidden iframe for printing the original PDF file with full fidelity

Each approach serves different needs — use window.print() for simple use cases, Print.js when layout control is important, and iframe-based printing when output quality matters most.

If you require additional PDF functionality — like multipage printing, annotations, digital signatures, or form interactions — consider a more advanced solution. Nutrient Web SDK offers a complete PDF toolkit with features like high-resolution printing, annotation, editing, and cross-framework support (React, Angular, Vue). You can start a free trial or explore our live demo to see it in action.

Choose the method that best fits your users’ expectations, and your app’s technical constraints.

FAQ

How do I add a print button to a PDF.js viewer?

Clone the project, add a print button in HTML, attach a window.print() event listener in index.js, and use CSS to hide the toolbar during printing.

What is the advantage of using window.print() for printing PDFs?

window.print() generates the PDF directly from the browser, is tool-independent, and supports modern CSS properties.

Can I use Print.js to print PDFs from PDF.js?

Yes. You can use Print.js by including its library and updating the print button’s click handler to use printJS() with the PDF element’s selector.

What are the limitations of window.print() for printing PDFs?

window.print() doesn’t support server-side file storage.

What is the best way to print a PDF file in the browser?

The best way to print a PDF file in the browser depends on your needs. For simple use, window.print() is fast. For better control, use Print.js. For highest quality, render your PDF in a hidden iframe and print from it.

Can you print PDFs from JavaScript without opening a new tab?

Yes. All three methods in this guide let you print PDFs without opening a new browser tab, including iframe-based printing, which avoids popups.

Hulya Masharipov

Hulya Masharipov

Technical Writer

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

Explore related topics

FREE TRIAL Ready to get started?