Trying to hide first footer/header on PDF generated with Puppeteer

后端 未结 2 604
小蘑菇
小蘑菇 2020-12-19 08:20

Im new using nodejs functions and also puppeteer. Previously I was using wkhtmltopdf but currently its options are very poor.

So, my idea was generating a pdf from a

2条回答
  •  悲&欢浪女
    2020-12-19 08:29

    There are currently multiple bugs (see this question/answer or this one) that make it impossible to get this working.

    This is currently only possible for headers using this trick (taken from this github comment):

    await page.addStyleTag({
        content: `
            body { margin-top: 1cm; }
            @page:first { margin-top: 0; }
        `,
    });
    

    This will basically hide the margin on the first page, but will not work when using a bottom margin (as also noted here).

    Possible Solution

    The solution I recommend is to create two PDFs, one with only the first page and no margins, and another one with the remaining pages and a margin:

    await page.pdf({
        displayHeaderFooter: false,
        pageRanges: '1',
        path: 'page1.pdf',
    });
    
    await page.pdf({
        displayHeaderFooter: true,
        footerTemplate: '
    Your footer text
    ', margin: { bottom: '10mm' }, pageRanges: '2-', // start this PDF at page 2 path: 'remaining-pages.pdf', });

    Depending on how often you need to perform the task you could either manually merge the PDFs or automate it using a tool like easy-pdf-merge (I have not used this one myself).

提交回复
热议问题