puppeteer: PDF margins doesn't seem to be respected

I’m trying to create an A4 PDF with multiple page.

But I’m still having margins even with margins set to 0…


(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url, {waitUntil: 'networkidle'});
    await page.pdf({path: filepath, format: 'A4', landscape: true, printBackground: true, margin: {top: 0, left: 0, right: 0, bottom: 0}});
    browser.close();
})();

Any ideas?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 15 (1 by maintainers)

Commits related to this issue

Most upvoted comments

I got my margins respected (they had to fight hard) by using

@page
{
  size: A4 landscape;
  margin: 0;
}

So dunno if it’s a bug or not. 🤔

preferCSSPageSize appears to have been added in 1.7.0. Interestingly, the default is false, which is what I want.

However, I tried it with 1.8.0 and even when specifically passing preferCSSPageSize: false, the CSS @page size and margin still takes precedence.

It seems that preferCSSPageSize doesn’t actually do anything at the moment? I tried everything I could think of and I couldn’t find any difference between preferCSSPageSize: false and preferCSSPageSize: true. Is this feature broken?

I have observed the same. If you set the page size to be tiny in CSS, Puppeteer generates a PDF with the default page size. I have preferCSSPageSize: true in my options.

It does seem to obey margins, but not using separate margins for the first page. For example this removes the bottom margin on all pages:

@page {
  margin-bottom: 50%;
}

@page :first {
  margin-bottom: 0;
}

The Chrome print preview appears to respect the :first rule.

Working, but headers and footers are included, I’ll go deeper to work with current CSS LIBS.

await page.addStyleTag({
  content: `
    @page {
      margin: 1in;
    }
    body {
      margin: 0;
    }
  `,
});

The state of this today with puppeteer 9.1.1 is still that margin argument is not respected, and you must modify the CSS to indicate the margins needed.

Have you tried the preferCSSPageSize ? This allows you to specify the margin’s for page in the CSS and it will take priority:

@page {
  size: A4 portait;
  margin: 0;
}

@HugoHeneault your page code helped solve my case, thank you for fighting against margins on behalf of us.

In my case it was:

@page { size: A4 portrait; margin: 0; }

For me margin option works well on windows and linux debian too. Puppeteer version 13.3.2.