【发布时间】:2021-12-19 06:54:18
【问题描述】:
我在另一篇文章中看到了PDFescape,并尝试了编辑表单字段名称。运行我的 prog 并确实填写了表单字段,但我的模板文件中的其余内容丢失了。
我尝试了Fill Form 示例文件,但它找不到表单字段名称,所以我还将它加载到 PDFescape 并从那里保存,然后模板的其余部分丢失但表单字段已填充的相同结果.
我认为 PDFescape 可能是问题,所以我购买了 Adobe 试用版以便能够编辑表单字段名称,但又一次,pdf-lib 找不到它们(错误:PDFDocument 没有名称为“的表单字段” prodCode") 即使肯定是这样保存的 -
我到底哪里错了?!供您参考的代码 -
const { PDFDocument } = require('pdf-lib');
const fs = require('fs');
(async () => {
const pdfUTF8 = fs.readFileSync('./test.pdf','utf8')
var formPdfBytes = new TextEncoder("utf-8").encode(pdfUTF8);
// Load a PDF with form fields
const pdfDoc = await PDFDocument.load(formPdfBytes)
// Get the form containing all the fields
const form = pdfDoc.getForm()
// Get all fields in the PDF by their names
const productCodeField = form.getTextField('prodCode')
const certNumberField = form.getTextField('certNumber')
productCodeField.setText('Product code here')
certNumberField.setText('Cert number here')
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save()
const data = fs.writeFileSync('./done.pdf', new Buffer.from(pdfBytes))
})().catch(e => {
console.log(e)
});
【问题讨论】:
标签: node.js