You need to enable JavaScript to run this app. 如何修改jsPDF html方法生成的PDF中HTML元素的字体?
优惠活动
大模型
产品
解决方案
定价
更多

如何修改jsPDF html方法生成的PDF中HTML元素的字体?

jsPDF HTML转PDF自定义Poppins字体问题修复

问题排查点

你当前代码同时混用了两种字体添加逻辑(addFileToVFS/addFont 和 fontFaces),这是冲突根源之一;另外CSS的字体格式声明有误,路径也可能存在加载问题。

修正步骤


1. 简化JS代码,移除冗余字体添加逻辑

doc.html()方法有独立的fontFaces配置,不需要再用addFileToVFS和addFont,保留fontFaces即可:

const doc = new jsPDF({
  unit: "pt",
  // 暂时关闭该选项,避免字体被误过滤
  putOnlyUsedFonts: false,
});

const elementToConvert = document.querySelector("#id");

doc.html(elementToConvert, {
  callback: (doc) => {
    doc.save("custom-font.pdf");
  },
  fontFaces: [
    {
      family: "Poppins",
      src: [
        {
          // 若路径访问有问题,推荐转base64嵌入字体(彻底避免路径/跨域问题)
          url: "../public/assets/poppins-regular.ttf",
          format: "truetype",
        },
      ],
      weight: "normal",
    },
    {
      family: "Poppins",
      src: [
        {
          url: "../public/assets/poppins-bold.ttf",
          format: "truetype"
        },
      ],
      weight: "bold"
    },
  ],
});

2. 修正CSS字体格式声明

把format('ttf')改为标准的format('truetype'),同时统一字体族名大小写(与JS配置保持一致):

@font-face {
  font-family: "Poppins";
  src: url("../public/assets/poppins-regular.ttf") format('truetype');
  font-weight: normal;
}
@font-face {
  font-family: "Poppins";
  src: url("../public/assets/poppins-bold.ttf") format('truetype');
  font-weight: bold;
}

#id{
  font-family: "Poppins", sans-serif;
}

3. 额外注意事项

  • 验证字体路径有效性:直接在浏览器地址栏输入字体文件路径,确认能正常下载字体,不行就调整为绝对路径(比如/assets/poppins-regular.ttf)。
  • 优先用base64嵌入字体:将字体文件转成base64字符串后,在fontFaces的src中写url('data:font/truetype;base64,xxx'),彻底规避路径问题。
  • 检查字体文件完整性:如果字体文件损坏也会加载失败,可更换官方下载的Poppins字体测试。

内容的提问来源于stack exchange,提问作者laheeb350

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 10:02:27