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

498 Views Asked by At

i'm trying to make a js project that fills pdf forms. Well it works only with english characters. How can I make it to use UTF-8?

This is my code:

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);

1

There are 1 best solutions below

0
On

you can load it like that after declaring pdfDoc directly :

// 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();