jsPDF - Importing fonts in React.js / ES6 style

故事扮演 提交于 2020-02-02 19:12:46

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/59950312/jspdf-importing-fonts-in-react-js-es6-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!