How to print a PDF from the browser
Categories:
Printing PDFs Directly from the Browser: A Comprehensive Guide

Learn various methods to trigger PDF printing from web applications, including JavaScript techniques and server-side considerations.
Printing documents directly from a web browser is a common requirement for many applications, especially when dealing with reports, invoices, or official documents. While browsers inherently offer print functionality, programmatically triggering a PDF print or generating a PDF for printing can be a bit more nuanced. This article explores different approaches to achieve this, focusing on client-side JavaScript techniques and touching upon server-side generation for more complex scenarios.
Client-Side Printing with window.print()
The simplest and most direct way to initiate a print dialog from the browser is by using the window.print()
method. This method opens the browser's native print dialog, allowing the user to select a printer, choose print settings, and print the current web page. While straightforward, it prints the entire visible content of the page, which might not always be desirable if you only want to print a specific section or a pre-generated PDF.
function printCurrentPage() {
window.print();
}
// Example usage with a button click
// document.getElementById('printButton').addEventListener('click', printCurrentPage);
Basic usage of window.print()
to trigger the browser's print dialog.
@media print
) to style your page specifically for printing, hiding unnecessary elements (like navigation bars) and optimizing layout for paper.Printing Specific HTML Content
If you only need to print a specific part of your web page, window.print()
alone isn't sufficient. A common workaround involves dynamically creating an iframe, populating it with the desired HTML content, and then calling print()
on the iframe's window. This isolates the content you want to print from the rest of the page.
sequenceDiagram participant User participant Browser participant WebApp User->>WebApp: Clicks 'Print Section' button WebApp->>Browser: Creates hidden iframe WebApp->>Browser: Populates iframe with target HTML WebApp->>Browser: Calls `iframe.contentWindow.print()` Browser->>User: Displays print dialog for iframe content User->>Browser: Confirms print Browser->>WebApp: Destroys iframe (optional)
Sequence diagram for printing specific HTML content using an iframe.
function printDiv(divId) {
const printContents = document.getElementById(divId).innerHTML;
const originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
// A more robust approach using an iframe:
function printElement(elementId) {
const element = document.getElementById(elementId);
if (!element) {
console.error('Element not found:', elementId);
return;
}
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
const iframeDoc = iframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write('<html><head><title>Print</title>');
// Copy styles from the main document
Array.from(document.querySelectorAll('link[rel="stylesheet"], style')).forEach(node => {
iframeDoc.write(node.outerHTML);
});
iframeDoc.write('</head><body>');
iframeDoc.write(element.outerHTML);
iframeDoc.write('</body></html>');
iframeDoc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
// Optional: Remove iframe after printing or after a delay
setTimeout(() => {
document.body.removeChild(iframe);
}, 1000);
}
JavaScript functions to print a specific HTML element, first by replacing body content (less ideal) and then using an iframe (recommended).
Printing Pre-Generated PDFs
When you have a PDF file (either generated on the client-side or fetched from a server) that you want the user to print, there are a few strategies. The most common is to open the PDF in a new tab, allowing the browser's built-in PDF viewer to handle it, which usually includes a print button. For more direct printing, you might need to rely on browser-specific behaviors or server-side solutions.

Different pathways for handling PDF printing from a web application.
1. Open PDF in New Tab
The simplest method is to open the PDF URL in a new browser tab. Most modern browsers have built-in PDF viewers that allow users to view and print the document directly. This gives the user full control over the printing process.
2. Trigger Download and Print
For PDFs generated dynamically (e.g., using client-side libraries like jsPDF), you can offer a download button. Once downloaded, the user can open the PDF with their system's default PDF viewer and print it. This is less direct but ensures the user has a local copy.
3. Server-Side PDF Generation and Printing
For complex PDFs or scenarios requiring direct printing without user interaction (e.g., printing shipping labels in a warehouse), server-side generation combined with specific printer APIs or services might be necessary. This often involves sending the PDF data to a server that can then communicate with a network printer. This is outside the scope of purely client-side browser printing.
// Method 1: Open PDF in a new tab
function openPdfForPrinting(pdfUrl) {
window.open(pdfUrl, '_blank');
}
// Method 2: Trigger download (if PDF is a Blob or File object)
function downloadPdf(pdfBlob, filename = 'document.pdf') {
const url = URL.createObjectURL(pdfBlob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Example with jsPDF (client-side PDF generation)
/*
import { jsPDF } from 'jspdf';
function generateAndPrintPdf() {
const doc = new jsPDF();
doc.text('Hello world!', 10, 10);
const pdfBlob = doc.output('blob');
// Option A: Open in new tab (requires converting blob to data URL or object URL)
const pdfUrl = URL.createObjectURL(pdfBlob);
openPdfForPrinting(pdfUrl);
// Option B: Trigger download
// downloadPdf(pdfBlob, 'my_generated_document.pdf');
}
*/
JavaScript examples for opening a PDF in a new tab or triggering a download.