问题描述
如何通过React在Jspdf中添加自定义字体?我尝试了所有可能的解决方案,但没有任何效果。我被困在这里。
解决方法
坦白地说,使用jsPDF中的字体确实是一件难事。在大多数情况下,我个人更喜欢将rasterizehtml或html2pdf与jsPDF一起使用。但是,如果您别无选择,建议您观看此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","bold");
doc.setFont("Arimo");
doc.setFontType("normal");
doc.setFontSize(28);
doc.text("Hello,World!",100,100);
doc.setFontType("bold");
doc.text("Hello,BOLD World!",150);
doc.save("customFonts.pdf");
}
代码很清楚,但这没关系...请注意笔的设置:
因此答案是使用jspdf-customfonts及其工具 makeFont
node makeFonts.js
-创建新的dist / default_vfs.js
使用此站点将您的 font.ttf 文件转换为 js 文件:https://peckconsulting.s3.amazonaws.com/fontconverter/fontconverter.html
然后取字体名称和类型, 导出 callAddFont 函数并在需要的地方调用它。
//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")