Search code examples
jspdf

jsPDF Error - Font does not exist in vFS (VueJs)


I might got a bug in my code but I'm not sure yet. I am trying to create a pdf in my Vue app with a custom font. I downloaded the font and converted it to base64 with the /fontconverter/fontconverter.html provided in the github repo. I created a new folder called 'fonts'. In the folder I included both the .ttf file of the custom font and the .js file from the fontconverter. Next, I created a method called downloadPdf(), that looks like this:

const doc = new jsPDF()
doc.setFontSize(28);

doc.text(20, 30, 'This is the default font.')

doc.setFont('courier')
doc.setFontType('normal')
doc.text(20, 60, 'This is courier normal.')

//This does not seem to solve the problem. 
//Also, this method is already included at the bottem of the 'Roboto-Regular-normal.js' file
doc.addFileToVFS("./fonts/Roboto-Regular.ttf", './fonts/Roboto-Regular-normal.js');
doc.addFont("./fonts/Roboto-Regular.ttf", "Roboto", "normal");
doc.setFont("Roboto");
doc.text("Reinier van der Galien", 20, 90);

console.log(doc.getFontList());
doc.save("customFonts.pdf");

This will create the pdf, WITH the custom font, so that works. However, in the console it still gives me the following error:

jsPDF PubSub Error No unicode cmap for font Error: No unicode cmap for font

And:

jsPDF PubSub Error Cannot read property 'widths' of undefined

The addFileToVFS method does not seem to be working. Any help is appreciated.


Solution

  • Here is my solution, probably not ideal, but it is working.

    First importing files with font. File contains only constant with font string and export of that constant.

    import Roboto from '@/assets/fonts/Roboto-Regular-normal.js'
    import RobotoBold from '@/assets/fonts/Roboto-Bold-bold.js'
    

    Then add it to jsPDF doc.

    let doc = new jsPDF()
    doc.addFileToVFS('Roboto-Regular.ttf', Roboto)
    doc.addFileToVFS('Roboto-Bold.ttf', RobotoBold)
    doc.addFont('Roboto-Regular.ttf', 'Roboto', 'normal')
    doc.addFont('Roboto-Bold.ttf', 'Roboto', 'bold')
    doc.setFont('Roboto')
    

    EDIT: I get font string from fontconvertor. From the exported file, I took only that string, everything else I removed.