How to add Header and footer content to pdfkit for node.js

Akhil Gopan picture Akhil Gopan · Mar 3, 2017 · Viewed 10.9k times · Source

I would like to generate a pdf using node js (express). I need to add header and footer to every page with page numbers. Any help would be appreciated.

Thanks.

Answer

Adding a Footer on all pages

doc.addPage()

let bottom = doc.page.margins.bottom;
doc.page.margins.bottom = 0;
doc.text('Page 1', 0.5 * (doc.page.width - 100), doc.page.height - 50,
{
width: 100,
align: 'center',
lineBreak: false,
})

// Reset text writer position

doc.text('', 50, 50)
doc.page.margins.bottom = bottom;

let pageNumber = 1;

doc.on('pageAdded', () => {
    pageNumber++
    let bottom = doc.page.margins.bottom;
    doc.page.margins.bottom = 0;

    doc.text(
        'Pág. ' + pageNumber, 
        0.5 * (doc.page.width - 100),
        doc.page.height - 50,
        {
            width: 100,
            align: 'center',
            lineBreak: false,
        })

    // Reset text writer position
    doc.text('', 50, 50);
    doc.page.margins.bottom = bottom;
})