galkahana / HummusJS

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

Create multipage pdf from template (by looping) #441

Open simon-dk opened 5 years ago

simon-dk commented 5 years ago

Hi, Have been starring hopelessly for hours now, so hope somebody can help me out.

I'm trying to accomplish a simple thing:

I have tried all kinds of different variations but am unsure if I need to use merge pdf, a formxobject or something else. Hope to get a helping hand here, not sure if i'm even close to producing the desired result!

var hummus = require('hummus');

var pdfWriter = hummus.createWriter(__dirname + 'output.pdf',{version:hummus.ePDFVersion14});
var formX = pdfWriter.createFormXObjectsFromPDF('template.pdf', hummus.ePDFPageBoxMediaBox);

const names = ["John Doe", "Jane Doe", "Jack Doe", "Dorry Doe"];

pdfWriter.startPageContentContext(page);

for (i=0; i < names.length; ++i) {
    pdfWriter.createPage(0,0,595,842);
    pdfWriter.writeText(names[i], 30, 30);
    pdfWriter.mergePDFPageToFormXObject(formX);
    pdfWriter.writePage(page);
}

pdfWriter.end();
simon-dk commented 5 years ago

So, small progress. I made some adjustments and have a somewhat working code now, only one caveat: Each iteration makes an overlay, so page 1 looks fine page 2 = page 1 + 2 page 3 = page 1 + 2 +3 What am I doing wrong here?

var hummus = require('hummus');

var pdfWriter = require('hummus').createWriter(__dirname + '/output/PDFEmbedTest.PDF');
var formIDs = pdfWriter.createFormXObjectsFromPDF(__dirname + '/template/input.PDF',hummus.ePDFPageBoxMediaBox);

var font = pdfWriter.getFontForFile('./fonts/Roboto-Regular.ttf');
var textOptions = {font:font,size:14,colorspace:'gray',color:0x00};

var page = pdfWriter.createPage(0,0,595,842);

for (i=0; i < 5; ++i) {
    pdfWriter.startPageContentContext(page)
    .doXObject(page.getResourcesDictionary().addFormXObjectMapping(formIDs[0]))
    .writeText('Test message on page  ' + i, 75, 750, textOptions)
    pdfWriter.writePage(page);
}

pdfWriter.end();