Pdf Generation with Playwright

11/28/2021, Sun
Categories: #JavaScript
Tags: #NodeJs

Alternative to Puppeteer for PDF Generation

While puppeteer is a popular option used for testing as well as pdf generation for webpages, playwright is also another option that can perform these tasks and more.

To simplify the configuration of pdf generation with playwright, the '@raminjafary/sura' module will be used as an example to show how to generate a pdf from an url. This module will require you to use ESM.

import { generateFile } from '@raminjafary/sura';

(async () => {
    await generateFile({
        type: 'pdf',
        htmlPath: 'https://github.com/raminjafary/sura',
        pageLoad: {
            waitUntil: 'networkidle',
        },
        pdf: {
            path: '/path/to/file.pdf',
            format: 'A4',
            printBackground: true,
        },
    })
})();

This module will only generate html files from a server url, and it is also capable of generating screenshots from pages.

If you do have control over the html page contents, then it is helpful to add in the following css to the html elements for which you do not want to clip off between a page break as to avoid the 'cutting' of the element when the element can not fit completely on the bottom of the page.

.my-element-which-should-not-break{
  break-inside: avoid;
}