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

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: '<div style="font-size:5mm;">Your footer text</div>',
    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).


small hint: easy-pdf-merge an pdf-merge have some "system-tools-dependencies" I prefer pdf-lib, a plain js tool where you can use Buffers and Typescript support

My Typescript:

import {PDFDocument} from 'pdf-lib'
...

const options: PDFOptions = {
    format: 'A4',
    displayHeaderFooter: true,
    footerTemplate: footerTemplate,
    margin: {
        top: '20mm',
        bottom: '20mm',
    },
}
const page1: Buffer = await page.pdf({
    ...options,
    headerTemplate: '<div><!-- no header hack --></div>',
    pageRanges: '1',
})
const page2: Buffer = await page.pdf({
    ...options,
    headerTemplate: headerTemplate,
    pageRanges: '2-',
})

const pdfDoc = await PDFDocument.create()

const coverDoc = await PDFDocument.load(page1)
const [coverPage] = await pdfDoc.copyPages(coverDoc, [0])
pdfDoc.addPage(coverPage)

const mainDoc = await PDFDocument.load(page2)
for (let i = 0; i < mainDoc.getPageCount(); i++) {
    const [aMainPage] = await pdfDoc.copyPages(mainDoc, [i])
    pdfDoc.addPage(aMainPage)
}

const pdfBytes = await pdfDoc.save()

// Buffer for https response in my case
return Buffer.from(pdfBytes)
...