Search code examples
reactjsfontsjspdf

jsPDF - Importing fonts in React.js / ES6 style


I am trying to add a font in jsPDF in my React project. I converted the font to base64 and to a .js script using the provided generator at: https://rawgit.com/MrRio/jsPDF/master/fontconverter/fontconverter.html

I import the font script as:

import '../../assets/fonts/js/Muli-normal';

where Muli-normal is the converted Muli-normal.js file from Muli.ttf using the generator. I set the font with

doc.setFont('Muli')

but I get the error

  Line 10:5:  'jsPDF' is not defined  no-undef

The script is as follows:

// ../../assets/fonts/js/Muli-normal.js

(function (jsPDFAPI) {
var font = 'AAEAAAASAQAABAAgRkZUTW2ZUGwAAAE..
...
...
...ASAQAAB';
var callAddFont = function () {
this.addFileToVFS('Muli-normal.ttf', font);
this.addFont('Muli-normal.ttf', 'Muli', 'normal');
};
jsPDFAPI.events.push(['addFonts', callAddFont])
})(jsPDF.API);

Solution

  • As the script does not recognize the jsPDF, one needs to import it using

    import jsPDF from 'jspdf'
    

    so the script becomes:

    // Muli-normal.js
    
    import jsPDF from 'jspdf'
    
    (function (jsPDFAPI) {
    var font = 'AAEAAAASAQAABAAgRkZUTW2ZUGwAAAE..
    ...
    ...
    ...ASAQAAB';
    var callAddFont = function () {
    this.addFileToVFS('Muli-normal.ttf', font);
    this.addFont('Muli-normal.ttf', 'Muli', 'normal');
    };
    jsPDFAPI.events.push(['addFonts', callAddFont])
    })(jsPDF.API);
    

    I still can't exactly figure out how the Muli-normal.js script is structured. (an IIFE module?). I figured to work it and answering my question but any explanations on this is welcome.

    Hope this helps someone