Reputation: 41
How to add custom font in Jspdf with react? I tried every possible solution but nothing is working.I am stuck here.
Upvotes: 2
Views: 5466
Reputation: 47
convert your font.ttf file to js file using a this site : https://peckconsulting.s3.amazonaws.com/fontconverter/fontconverter.html
then take the font name and type, export the the callAddFont function and call it where you want .
//this in the js file we generated from
//peckconsulting.s3.amazonaws
var font ".....
.....
.....";
var callAddFont = function () {
this.addFileToVFS("Calibri Bold-normal.ttf",
font);
this.addFont("Calibri Bold-normal.ttf","Calibri
Bold", "normal");
};
export { callAddFont };
// your component
import { callAddFont } from "./fonts/Calibri
Bold-normal";
.....
.....
jsPDF.API.events.push(["addFonts",
callAddFont]);
var doc = new jsPDF("l", "mm", [220, 250]);
doc.setFont("Calibri Bold", "normal");
doc.text("example")
Upvotes: 5
Reputation: 620
Frankly working with fonts in jsPDF is a real pain in the back. In most cases I personally prefer to use rasterizehtml or html2pdf in complex with jsPDF. However, if you have no choice, I recommend watching this example
function createPDF() {
const doc = new jsPDF({
unit: "pt",
orientation: "p",
lineHeight: 1.2
});
doc.addFont("Arimo-Regular.ttf", "Arimo", "normal");
doc.addFont("Arimo-Bold.ttf", "Arimo", "bold");
doc.setFont("Arimo");
doc.setFontType("normal");
doc.setFontSize(28);
doc.text("Hello, World!", 100, 100);
doc.setFontType("bold");
doc.text("Hello, BOLD World!", 100, 150);
doc.save("customFonts.pdf");
}
The code is clear but it's doesn't matter... Pay attention on Pen's Settings:
So the answer is using jspdf-customfonts and its tool makeFont
node makeFonts.js
- to create a new dist/default_vfs.js
Upvotes: 1