如何在 PDF-Lib JavaScript 上使用 UTF-8

How can I use UTF-8 on PDF-Lib JavaScript

提问人:Nick S 提问时间:8/7/2023 更新时间:8/7/2023 访问量:208

问:

我正在尝试制作一个填充 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);

JavaScript 编码 UTF-8 PDF-lib .js

评论


答:

0赞 Mohamed Mostafa 8/7/2023 #1

您可以直接声明 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();