我正在尝试制作一个填充 pdf 表单的 js 项目。嗯,它只适用于英文字符。我怎样才能让它使用UTF-8?
这是我的代码:
const formUrl = 'form.pdf';
const formPdfBytes = await fetch(formUrl).then((res) => res.arrayBuffer());
const pdfDoc = await PDFLib.PDFDocument.load(formPdfBytes);
const form = pdfDoc.getForm();
form.getTextField('TEXT1').setText('Nick');
form.getTextField('LAST').setText('Slet');
form.getTextField('AGE').setText('1223');
form.getTextField('FIRST').setText('Nick');
form.getTextField('FAM').setText('oik');
form.getTextField('FAM1').setText('oik2');
form.getTextField('NAMES').setText('slay');
form.getTextField('NAMES1').setText('slay1');
form.getTextField('HOUR').setText('090');
form.flatten();
const pdfBytes = await pdfDoc.save();
// Download the modified PDF
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = 'modified_form.pdf';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
直接声明 pdfDoc 后即可加载它:
// Load a custom font that supports UTF-8 characters
const fontBytes = await fetch('path-to-your-font.ttf').then((res) =>
res.arrayBuffer());
const customFont = await pdfDoc.embedFont(fontBytes);
const form = pdfDoc.getForm();