Im trying to create a multi-page document from templates on my file system, but I'm getting strange behaviour of the same page title across all pages in the document instead. Any ideas what I'm doing wrong here?
Something I don't quite get, is the way we add pages. Why do we need to reference newDoc in the example below, when we do await newDoc.copyPages(page, [0])? Instead of just newDoc.addPage(page)?
Would it be that the form field named Title is being overwritten because both pages have the same field name during the copying of data streams?
Note: I've been made aware that StackOverflow doesnt have a tag for pdf-lib.js.org, not to be confused with other pdf libraries.
const payload = {
rows: [{
id: 1,
title: 'Foo',
},{
id: 2,
title: 'Bar'
},
formData: {
hello: 'World',
lorum: 'Ipsum'
}
]
}
const makePdf = async (payload) => {
const newDoc = await PDFDocument.create()
newDoc.getForm().acroForm.dict.set(PDFName.of('NeedAppearances'), PDFBool.True)
for (const row of payload.rows) {
await addPage(row, payload.formData, newDoc)
}
return newDoc
}
const addPage = async (dataRow, formData, newDoc) => {
const rowId = dataRow.id
let templateName
switch(true) {
case (rowId === 1):
templateName = 'foo'
break
case (rowId === 2):
templateName = 'bar'
break
}
const templatePath = path.join(__dirname, `../templates/pdfs_/${templateName}.pdf`)
const template = await fs.readFileSync(templatePath)
const page = await PDFDocument.load(template)
const form = page.getForm()
form.acroForm.dict.set(PDFName.of('NeedAppearances'), PDFBool.True)
switch(templateName) {
case 'foo':
foo(form, formData)
break
case 'bar':
bar(form, formData)
}
// dataRow.title logs correct strings ie: 'Foo' & 'Bar'
form.getField('Title').setText(dataRow.title)
const [firstPage] = await newDoc.copyPages(page, [0])
return await newDoc.addPage(firstPage)
}
const bar = (form, formData) => {
form.getField('Lorum').setText(formData.lorum)
}
const foo = (form, payload) => {
form.getField('Hello').setText(formData.hello)
}
return makePdf(payload)
// Produces 2 page pdf with the same title
// [[ title: Foo, Hello: World ], [title: Foo, Lorum: Ipsum ]]
I don't have your template file so I'm not sure excatly what you are trying to achieve.
The copyPage is indeed required.
You should save the PDFDocument before you change it again.
I tried to rewrite your code, I ignored the PDFName and PDFBool line but I'm sure you can get the idea.
const {PDFDocument} = require('./engine/node_modules/pdf-lib');
const fs = require('fs');
const payload = {
rows: [
{ id: 1, title: 'Foo', },
{ id: 2, title: 'Bar', },
],
formData: { hello: 'World', lorum: 'Ipsum', }
}
class PdfSample {
async loadTemplate(templatePath) {
const templateFile = fs.readFileSync(templatePath);
const templateDoc = this.templateDoc = await PDFDocument.load(templateFile);
this.templateForm = templateDoc.getForm();
}
async initDoc() {
this.resultDoc = await PDFDocument.create();
}
fillTextField(fieldName, value) {
const field = this.templateForm.getField(fieldName);
field.setText(value);
}
get formFieldsNames() {
return this.templateForm.getFields().map(field => field.getName());
}
async addDocPage() {
const newPageBytes = await this.templateDoc.save();
const newPage = await PDFDocument.load(newPageBytes);
const [pageToAdd] = await this.resultDoc.copyPages(newPage, [0]);
return this.resultDoc.addPage(pageToAdd);
}
async saveResult(outputPath) {
const pdfBytes = await this.resultDoc.save();
fs.writeFileSync(outputPath, pdfBytes);
}
}
const pdfSample = new PdfSample();
(async () => {
await pdfSample.initDoc();
await pdfSample.loadTemplate('./pdfs_/OoPdfFormExample.pdf');
console.log(pdfSample.formFieldsNames);
for (const row of payload.rows) {
pdfSample.fillTextField('Given Name Text Box', row.title);
pdfSample.fillTextField('Family Name Text Box', payload.formData.hello);
pdfSample.fillTextField('House nr Text Box', payload.formData.lorum);
await pdfSample.addDocPage(pdfSample.templateDoc);
}
await pdfSample.saveResult('./pdfs_/result.pdf');
})();
The sample form is from this site
You are trying to create a document with two form fields named Title, one on each page. This does not work, both are the same field and show the same value.
Rather then "copy" existing fields from a template, you must use something like
var newField = form.createTextField('Title' + dataRow.id);
newField.addToPage(firstPage, {x: ..., y: ...});
newField.setText(...);