jsPDF Library not exporting Cyrillic letters

56 views Asked by At

I am trying to export data into PDF from a React project using JS. (I tried other libraries as well) so I am using jsPDF to create the pdf and it works fine until I try to export something in Cyrillic.

async function exportDataToPDF() {
    const doc = new jsPDF();

    // Load the font file as a binary string
    const fontUrl = "../../../assets/fonts/Roboto-Regular.ttf";
    const fontData = await fetch(fontUrl).then(res => res.arrayBuffer());
    const fontArray = new Uint8Array(fontData);
    const fontString = String.fromCharCode.apply(null, Array.from(fontArray));

    // Add the font to the virtual file system
    doc.addFileToVFS("Roboto-Regular.ttf", fontString);

    // Add the font to the document
    doc.addFont("Roboto-Regular.ttf", "Roboto", "normal");

    // Set the font
    doc.setFont("Roboto");

    // Set font size and add text
    doc.setFontSize(16);
    doc.text('In english', 10, 10);
    doc.text('На български', 10, 20);

    // Save the PDF
    doc.save('Планирано производство.pdf');
}

I tried importing the font this way, but it won't find it. It finds other files in the assets folder.

import RobotoRegular from "../../../assets/fonts/Roboto-Regular.ttf"; 

Then I tried to add the path in the function as shown in the code and it did read it, the font changed to Cyrillic, but it still won't read Cyrillic letters.

const fontUrl = "../../../assets/fonts/Roboto-Regular.ttf";
1

There are 1 answers

0
Kristiyan On

I found a way to fix it using a base64 converted font. I converted the code and put it in a font folder that I exported. In my component, I imported it and set it as a font. I hope you find it helpful as there aren't many simple solutions on the internet!

Links:

jsPDF documentation on loading fonts.

jsPDF online tool to convert .ttf to base64

Here is the updated code:

async function exportDataToPDF() {
    const doc = new jsPDF();

    // *** Font Embedding ***
    doc.addFileToVFS('Roboto-Regular.ttf', robotoFontBase64);
    doc.addFont('Roboto-Regular.ttf', 'Roboto', 'normal'); 
    doc.setFont('Roboto');

    // *** Text Output ***
    doc.setFontSize(16);
    doc.text('In english', 10, 10);
    doc.text('На български', 10, 20);

    // Save the PDF
    doc.save('Планирано производство.pdf');
}