Chrome headless rendering completely wrong to pdf

3.8k views Asked by At

I am trying to print a page with several nvd3 charts to pdf using puppeteer. When using the printing function via the Chrome browser I obtain the following decent output (don't mind the blue borders):

Correct output

When I try to visit the same page using chrome headless via puppeteer, I get this output instead, spanning over 3 pages:

Wrong output

This is the code that I am using:

const puppeteer = require('puppeteer');

(async() => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.setCookie({
        name: 'cookie-a',
        value: '...',
        domain: 'example.com'
    });
    await page.setCookie({
        name: 'cookie-b',
        value: '...',
        domain: 'example.com'
    });

    await page.goto('http://example.com/search/?bookmark=bot-overview', {waitUntil: 'networkidle'});

    setTimeout(async function () {
        await page.pdf({ path: 'page.pdf', format: 'A4', landscape: true });
        browser.close();
    }, 10000);
})();

I also tried to fix height and width to pixel values, cm and mm, but it doesn't affect the output. Notice that the entire page is styled through pages and bootstrap with their print media stylesheet. I also added several css rules for the printing media (among which the blue borders). One of these rules forces the whole page to be 297mmx210mm big, i.e. the exact size of an A4 page.

1

There are 1 answers

2
Lars van den Bosch On BEST ANSWER

I was facing issues like yours. After a while I was able to fix some of them:

    const puppeteer = require('puppeteer');
    const devices = require('puppeteer/DeviceDescriptors');

    (async () => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        const url = 'https://example.com';

        await page.emulateMedia('screen'); //<--
        await page.goto(url, {waitUntil: 'networkidle'});

        await page.screenshot({path: 'full_img.png', fullPage: true});
        await page.pdf({
          path: 'the_file.pdf', 
          format: 'A4', 
          printBackground: true, //<---
          displayHeaderFooter: true, //<---
          scale: 1,
          landscape: false,
          pageRanges: ""
      });
    })();