galkahana / HummusJS

Node.js module for high performance creation, modification and parsing of PDF files and streams
http://www.pdfhummus.com
Other
1.14k stars 169 forks source link

Insert page number on each page #346

Closed istvanpp closed 5 years ago

istvanpp commented 5 years ago

Hi, could you please provide me an example how to add page numbers in the footer of an existing PDF document?

Isn't clear for me, which method or solutions is the best and the fastest for this process?

My code is working, but I am not sure if I am using the best solution:

var pdfInserPageNumber = hummus.createWriterToModify('AppendPagesTest.pdf', {
            modifiedFilePath:'AppendPagesTestModif.pdf' });
var getFont = pdfInserPageNumber.getFontForFile('liberationregular.ttf');
var textOptions = {font:getFont, size:14, colorspace:'gray', color:'red'};
var totalPages = hummus.createReader('AppendPagesTest.pdf').getPagesCount();

var pageNumber;
for (pageNumber = 1; pageNumber <= totalPages; pageNumber++) {
    var pageModifier = new hummus.PDFPageModifier(pdfInserPageNumber, pageNumber-1);
    pageModifier.startContext().getContext().writeText('Page ' + String(pageNumber) + ' of ' + String(totalPages), 460, 38, textOptions); 
    pageModifier.endContext().writePage();
}
pdfInserPageNumber.end();
galkahana commented 5 years ago

looks like it couldn't get any better. i mean, i normally like ++a, and not a++, but who cares :).

oh. one thing. you don't need to create another reader for the pdf file. when creating a modification writer, it creates internally a parser and provider a handle for you. so you can get pages count with:

pdfInserPageNumber.getModifiedFileParser().getPagesCount()

this should save you some time.

istvanpp commented 5 years ago

Thank you @galkahana , I have updated my code based on your observation.