如何在React中添加Jspdf中的自定义字体?

问题描述

如何通过React在Jspdf中添加自定义字体?我尝试了所有可能的解决方案,但没有任何效果。我被困在这里

解决方法

坦白地说,使用jsPDF中的字体确实是一件难事。在大多数情况下,我个人更喜欢将rasterizehtmlhtml2pdf与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");
}

代码很清楚,但这没关系...请注意笔的设置:

enter image description here

因此答案是使用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")

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...