NodeJS with Puppeteer: how to set the margins of each pages (or scale all of them to fit the magins)?
Asked Answered
S

2

7

I tried to just use below setting but turn out the header and footer positions will be changed. Please advise.

await page.pdf({
    path: FILENAME,
    format: 'A4',
    margin: {
        top: "0px",
        right: "0px",
        bottom: "0px",
        left: "0px"
    },
    printBackground: true // required for photos otherwise blank
});
Southeast answered 17/10, 2019 at 5:6 Comment(0)
C
5

try preferCSSPageSize: true in page.pdf options. This allows you to specify the margin's for page in the CSS and it will take priority. **place CSS **

<style>
    @page 
{ 
    size: A4 portrait;
    margin:0; 
}
</style>
Clarita answered 29/1, 2020 at 7:17 Comment(0)
G
0

To add a margin to the puppeteer pdf, the normal props did not work for me. I had to add the below style directly to my website.

<style>
        {`@media print {
            @page {
                size: A4 portrait;
                margin-top: 0.6in;
                margin-right: 0.4in;
            }
            //If you want to style specific page
            @page :first {
                margin-top: 0.4in;
            }         
        }`}
</style>

Also, enable the preferCSSPageSize to be true

const pdfBuffer = await page.pdf({
        preferCSSPageSize: true,
    });
Gyniatrics answered 3/7, 2024 at 10:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.