Skip to content
Print HTML JavaScript Tips Style Guides PDF Download

HTML to PDF with CSS: Download an A4 PDF with jsPDF and html2canvas

Raheel Shan

Raheel Shan

May 2nd, 2025 · 8 min read

HTML to PDF with CSS: Download an A4 PDF with jsPDF and html2canvas

To convert HTML and CSS to a PDF in the browser, render the element to a canvas with html2canvas, then place that image on A4 pages with jsPDF and call save(). There is no backend and no print stylesheet. This post gives you the full working function, including the part most tutorials skip: splitting a long page across several A4 pages.

If you only want to print the page with the browser's print dialog, that is a different job. I covered it in Say Goodbye to Media Queries: Print Fully Styled HTML Content. This post is about a downloadable file.

Quick answer

  1. Load html2canvas and jsPDF from a CDN.
  2. Render your element with html2canvas(element, { scale: 2, useCORS: true }).
  3. Create the PDF with new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' }).
  4. Cut the canvas into page-sized slices and add each slice with addImage() and addPage().
  5. Call pdf.save('file.pdf').

Step 1: HTML and scripts

Wrap what you want in the PDF in one element. Nothing else is needed.

<div id="content-to-print">
    <!-- invoice, certificate, report... -->
</div>

<button id="download-pdf" type="button">Download PDF</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

The UMD build of jsPDF exposes window.jspdf.jsPDF. You do not need jQuery for any of this.

Step 2: Print HTML to PDF with one function

The original version of this post added the whole image once, with a hard-coded offset, so anything taller than one page was cut off. This version slices the canvas by page height.

async function downloadPdf(filename = 'document.pdf') {
    const element = document.getElementById('content-to-print');

    const canvas = await html2canvas(element, {
        scale: 2,               // pixel density, not page size
        useCORS: true,          // allow cross-origin images
        backgroundColor: '#ffffff',
        scrollX: 0,
        scrollY: 0,
    });

    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' });

    const pageWidth = pdf.internal.pageSize.getWidth();    // 210
    const pageHeight = pdf.internal.pageSize.getHeight();  // 297
    const margin = 10;

    const imgWidth = pageWidth - margin * 2;
    const usableHeight = pageHeight - margin * 2;

    // canvas pixels per millimetre once the image is scaled to imgWidth
    const pxPerMm = canvas.width / imgWidth;
    const sliceHeightPx = Math.floor(usableHeight * pxPerMm);

    let offsetY = 0;
    let page = 0;

    while (offsetY < canvas.height) {
        const sliceHeight = Math.min(sliceHeightPx, canvas.height - offsetY);

        const slice = document.createElement('canvas');
        slice.width = canvas.width;
        slice.height = sliceHeight;

        const ctx = slice.getContext('2d');
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, slice.width, slice.height);
        ctx.drawImage(canvas, 0, offsetY, canvas.width, sliceHeight, 0, 0, canvas.width, sliceHeight);

        if (page > 0) pdf.addPage();

        pdf.addImage(
            slice.toDataURL('image/jpeg', 0.92),
            'JPEG',
            margin,
            margin,
            imgWidth,
            sliceHeight / pxPerMm
        );

        offsetY += sliceHeight;
        page++;
    }

    pdf.save(filename);
}

document.getElementById('download-pdf').addEventListener('click', () => downloadPdf('sample-file.pdf'));

What changed from the first version

  • Multi-page output. The old code drew one image and stopped, so long content was lost. Slicing fixes that.
  • No white rectangle hack. The old code filled the page with pdf.rect() and used position = -7 to hide an offset. A white margin and a white slice background do the same job cleanly.
  • Unused code removed. heightLeft, the injected <style> rule and jQuery did nothing.
  • JPEG instead of PNG. A PNG at scale: 3 easily makes a PDF of several MB. JPEG at 0.92 is far smaller and looks the same for documents. Use PNG only if you need transparency or crisp line art.

jsPDF A4 size and scale explained

Many searches for "jspdf scale" mix up two different things.

  • html2canvas scale is pixel density. Higher means sharper text and a bigger file. It does not change the page size.
  • jsPDF size arguments in addImage(imageData, format, x, y, width, height) are in the unit you chose, here millimetres. This is what scales the image onto the A4 page.

A4 is 210 by 297 mm, and pdf.internal.pageSize.getWidth() and getHeight() return it for the chosen format, so you never hard-code those numbers.

jsPDF addImage as a full page background

To use an image as a full-page background, call addImage first, with no margin, and the full page size, then add your text on top:

pdf.addImage(backgroundDataUrl, 'JPEG', 0, 0, pdf.internal.pageSize.getWidth(), pdf.internal.pageSize.getHeight());
pdf.text('Certificate of completion', 105, 60, { align: 'center' });

For a single page, set margin = 0 in the function above and the content fills the sheet.

Limits you should know about

  • Text becomes pixels. The PDF is made of images. Text cannot be selected, searched or copied, and screen readers cannot read it.
  • Slices can cut through a line. The cut falls at a fixed height, so a line of text or a table row can be split across two pages. For documents with many rows, use real print CSS or a server-side renderer.
  • Canvas size limits. Browsers cap canvas size (roughly 16,000 pixels on a side, less on phones). Very long content at a high scale fails or comes out blank. Lower scale or render in sections.
  • File size. Many images and a high scale mean a heavy PDF.
  • CORS. Cross-origin images need useCORS: true and correct headers on the image server. Web fonts must be loaded before you start.

When to use something else

If you need selectable text, small files or exact page breaks, use the browser print dialog with @page { size: A4; } (see the html2canvas print post) or generate the PDF on the server. If the data comes from your Laravel app, building the document from a Blade view on the server keeps it consistent; for structuring that data cleanly see Avoid the Mess: Structuring Laravel View Data with ViewModels.

This approach is a good fit for invoices, certificates and styled reports where the look matters more than selectable text.

FAQ

How do I print an HTML page as a PDF with CSS? Use the browser print dialog with @media print and @page, then choose Save as PDF, or render the element with html2canvas and save it with jsPDF as shown above. The second keeps your screen CSS exactly.

Does html2canvas keep my CSS? It redraws the page from computed screen styles, so most CSS (fonts, spacing, backgrounds) is kept. It does not apply @media print, and a few properties are not supported.

How do I fit HTML to an A4 page in jsPDF? Take the page width from pdf.internal.pageSize.getWidth(), subtract your margins, scale the image to that width and derive the height from the canvas ratio. Slice the canvas when it is taller than one page.

Why is my PDF blurry or huge? Blurry means scale is too low, so use 2. Huge means PNG at a high scale, so switch to JPEG.

Can I make the text selectable? Not with this method. jsPDF also has an html() method that uses html2canvas internally and still produces images, so for real text use server-side generation.

Found this useful?

Support the work that goes into these posts.

Support
Comments


Comment created and will be displayed once approved.
Built with Brandidos