use pdf-lib to fill in pdf template:
export const fillForm = async (pdfDoc: any, fieldNames: string[], fieldValues: string[]) => {
const form = pdfDoc.context.lookup(pdfDoc.catalog.get(PDFName.of('AcroForm')))
if (!form) {
throw new Error('PDF does not contain a form')
}
form.set(PDFName.of('NeedAppearances'), PDFBool.True)
const fieldRefs = form.context.lookup(form.get(PDFName.of('Fields')))
if (!fieldRefs) {
throw new Error('PDF form does not contain any fields')
}
const fields = fieldRefs.array.map((ref: any) => form.context.lookup(ref))
fields.forEach((field: any) => {
const name = field.get(PDFName.of('T'))
console.log('pdf form fieldName:', name, name.value)
if (name) {
const idx = fieldNames.indexOf(name.value)
const newValue = idx >= 0 ? fieldValues[idx] : ''
if (newValue) {
field.set(PDFName.of('V'), PDFString.of(newValue))
field.set(PDFName.of('Ff'), PDFNumber.of(1))
}
}
})
}
another good code:
https://github.com/YOU54F/serverless-pdf-filler/blob/serverless/src/utils/template.ts
Comments
Post a Comment