Search code examples
javascriptnode.jspdfpuppeteerhtml-to-pdf

Why Puppeteer PDF generation not working on Windows?


I have this NodeJs app, trying to generate a PDF from HTML. It works on Mac, but not on Windows (times out). Here's the code.

const puppeteer = require('puppeteer');
const fs = require('fs');

const init = async () => {
    try {
        const browser = await puppeteer.launch({headless: true});
        const page = await browser.newPage();

        await page.setContent('<h1>Hello World</h1>');
        await page.emulateMediaType('screen');
        await page.pdf({
            path: 'hello-world.pdf',
            format: 'A4',
            printBackground: true,
            timeout: 0
        });

        console.log('PDF Generated');
        await browser.close();
        process.exit()

    } catch (error) {
        console.log(error)
    }
};

init()

after calling page.pdf method, it waits so long and times out. ProtocolError: Page.printToPDF timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.

But on my M1 MacBook Pro, it works like a charm.

Tried this on a Windows 11 VM (Parallels) and a couple of Windows 11 laptops. But No luck.

What am I doing wrong here? Do I need to add something else?

Thanks!

Node: v20.15.0

Puppeteer: ^22.12.1


Solution

  • After a few hours I was able to find the issue.

    After launching the browser with browser logging await puppeteer.launch({headless: true, dumpio:true}); it logged this:

    [16848:6956:0703/000025.226:ERROR:sandbox_win.cc(913)] Sandbox cannot access executable. Check filesystem permissions are valid. See [URL]: Access is denied. (0x5)
    
    DevTools listening on ws://[URL][16848:7356:0703/000025.488:ERROR:network_service_instance_impl.cc(600)] Network service crashed, restarting service.
    [16848:6956:0703/000026.330:ERROR:sandbox_win.cc(913)] Sandbox cannot access executable. Check filesystem permissions are valid. See [URL]: Access is denied. (0x5)
    

    so I was able to find adding args: ['--no-sandbox', '--disable-setuid-sandbox'] is a workaround but not recommended https://stackoverflow.com/a/53975412/9814969

    const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); worked!

    Seems to be that this is a common issue on Linux based systems but I was trying it on Windows. Therefore adding this as an answer