Skip to content

Using Paged.js

Browser support for advanced HTML-to-PDF layout is still limited. For example, adapting headers to the page content or controlling page breaks precisely can be difficult. Standards such as CSS Paged Media Module Level 3 were designed to help, but browser support is still incomplete.

Paged.js helps fill that gap. It is a polyfill that brings part of this paged-media behavior to the browser and can make complex PDF layouts much easier to manage.

Getting the script

Doppio could theoretically inject Paged.js automatically before printing, but that could break some pages. It is safer to add it explicitly in your own HTML document.

To add the polyfill, place this script tag inside the head of your HTML document:

html
<script src="https://unpkg.com/pagedjs/dist/paged.polyfill.js"></script>

This script executes as soon as the document is loaded in the browser. To make sure it has time to run before printing, add the following option to your request body:

json
{
    "page": {
        "pdf": {
            "printBackground": true
        },
        "goto": {
            "url": "https://your-url.com",
            "options": {
                "waitUntil": ["load"],
                ...
            },
        },
        ...
    }
}

Working with async content

If your page fetches additional content after the initial document load, you may need to delay Paged.js until everything is ready. To do that, add a script that disables automatic execution on load.

html
<head>
    ...
    <script>
        window.PagedConfig = {
            auto: false, // disable automatic script execution on document load
        };
    </script>
    <script src="https://unpkg.com/pagedjs/dist/paged.polyfill.js"></script>
    ...
</head>

WARNING

Be sure to add this script before the Paged.js script tag, or add defer to the Paged.js script tag. Otherwise, Paged.js may start before you disable its automatic execution.

Then, once all your content has loaded, execute Paged.js:

js
window.PagedPolyfill.preview();

INFO

This is also explained in the Paged.js npm README. That documentation also covers additional options that may be useful for your project.

Finally, add networkidle0 to waitUntil so the render waits for the page content before printing.

json
{
    "page": {
        "pdf": {
            "printBackground": true
        },
        "goto": {
            "url": "https://your-url.com",
            "options": {
                "waitUntil": ["load", "networkidle0"],
                ...
            },
        },
        ...
    }
}

Other Paged.js articles on Doppio

Paged.js - Installation with React

Paged.js - Installation with Vue 3

Few tips with Paged.js

Using Paged.js - Installation

All rights reserved