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

5

8

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.

Priestess answered 3/3, 2017 at 6:0 Comment(1)
for any of these solutions to work for my specific use case - the first page always put the footer at the top right of the page. I used doc.text('', 0, 0) before the for loop and it solved my problem. after that, all of the solutions worked that looped across the range of pages. in my case, pageAdded hooks didnt work because I never Add a page.Erechtheum
F
16

You can do this :

doc.text('This is a footer', 20, doc.page.height - 50, {
    lineBreak: false
  });
Fontainebleau answered 11/9, 2017 at 10:37 Comment(0)
S
17

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;
})
Sartre answered 6/8, 2018 at 16:3 Comment(2)
Worth Noting: PDFkit won't let you write in the margins. That's why this answer unsets the bottom margin, writes, and then resets the bottom margin.Ledbetter
This was the deal breaker for me doc.page.margins.bottom = 0. I needed to remove the margin and then add my custom footer design to itSaltarello
F
16

You can do this :

doc.text('This is a footer', 20, doc.page.height - 50, {
    lineBreak: false
  });
Fontainebleau answered 11/9, 2017 at 10:37 Comment(0)
L
8

Adding content to every page using doc.on('pageAdded'... hook has the nasty side effect of hijacking your position (doc.x/doc.y) while filling in a page. Additionally, you have to set the autoFirstPage: false flag in order to inject your hook prior to first page creation.

I find using bufferPages mode and then making global edit to the pages at the end much more graceful/logical.

const doc = new PDFDocument({
  bufferPages: true
});

doc.text("Hello World")
doc.addPage();
doc.text("Hello World2")
doc.addPage();
doc.text("Hello World3")

//Global Edits to All Pages (Header/Footer, etc)
let pages = doc.bufferedPageRange();
for (let i = 0; i < pages.count; i++) {
  doc.switchToPage(i);
    
  //Header: Add page number
  let oldTopMargin = doc.page.margins.top;
  doc.page.margins.top = 0 //Dumb: Have to remove top margin in order to write into it
  doc
    .text(
      `Page: ${i + 1} of ${pages.count}`,
      0,
      (oldTopMargin/2), // Centered vertically in top margin
      { align: 'center' }
    );
  doc.page.margins.top = oldTopMargin; // ReProtect top margin

  //Footer: Add page number
  let oldBottomMargin = doc.page.margins.bottom;
  doc.page.margins.bottom = 0 //Dumb: Have to remove bottom margin in order to write into it
  doc
    .text(
      `Page: ${i + 1} of ${pages.count}`,
      0,
      doc.page.height - (oldBottomMargin/2), // Centered vertically in bottom margin
      { align: 'center' }
    );
  doc.page.margins.bottom = oldBottomMargin; // ReProtect bottom margin
}

doc.end();
Ledbetter answered 29/1, 2020 at 4:1 Comment(0)
C
3

about this library, I suggest to read the PDF documentation, it is a lot must complete that the online HTML doc.

Warning : To be able to write outside the main content area, you have to set height and width on text's function params.

so as seen pdf doc you can do :

const doc = new PDFDocument({bufferPages: true})

//addPage X times

const range = doc.bufferedPageRange();

for( let i = range.start; i <  (range.start + range.count); i++) {

  doc.switchToPage(i);
  doc.text(`Page ${i + 1} of ${range.count}`, 
            200, 
            doc.page.height - 40, 
            { height : 25, width : 100});
}
Curtain answered 23/10, 2017 at 12:36 Comment(2)
I'm getting TypeError: doc.bufferedPageRange is not a function. Using https://github.com/devongovett/pdfkit/releases/download/v0.6.2/pdfkit.jsMoreover
this was the best answer, thanks!Foppery
C
2

this works for me

    const doc = new PDFDocument({bufferPages: true})
    const range = doc.bufferedPageRange();

    for (let i = range.start; i <= (doc._pageBufferStart + 
    doc._pageBuffer.length - 1); i++) {

    doc.switchToPage(i);

        doc.font('Times-Roman').fontSize(8).text('Footer', 90, 
    doc.page.height - 40, {
    lineBreak: false
  });

}
Cruse answered 29/5, 2018 at 9:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.