Skip to content

Print page to PDF

Andrea Cardaci edited this page Jun 13, 2017 · 1 revision

Print the page to PDF once the URL finished loading.

Note: prior to Chrome version 60 Page.printToPDF doesn't take any parameters.

const CDP = require('chrome-remote-interface');
const fs = require('fs');

CDP(async (client) => {
    const {Page} = client;
    try {
        await Page.enable();
        await Page.navigate({url: 'https://github.com'});
        await Page.loadEventFired();
        const {data} = await Page.printToPDF({
            landscape: true,
            printBackground: true,
            marginTop: 0,
            marginBottom: 0,
            marginLeft: 0,
            marginRight: 0
        });
        fs.writeFileSync('page.pdf', Buffer.from(data, 'base64'));
    } catch (err) {
        console.error(err);
    } finally {
        await client.close();
    }
}).on('error', (err) => {
    console.error(err);
});