You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic/iOS环境下pdfMake动态加载字体失败问题求助

Ionic/Angular pdfMake iOS字体加载错误解决办法

问题重现

在Ionic/Angular项目中使用pdfMake生成PDF,Android端运行正常,但iOS端动态加载字体时抛出错误:

⚡️  [error] - ERROR Error: Uncaught (in promise): File 'capacitor://localhost/assets/fonts/pdf/FreeSerif.ttf' not found in virtual file system

解决方案

方案一:改用相对路径

iOS下Capacitor对绝对URL的资源读取逻辑和Android不同,直接使用相对路径可避免虚拟文件系统找不到文件的问题:
修改字体路径配置,移除window.location.origin:

generatePDF(pdfInstant: any, content: any) {
  pdfInstant.fonts = {
    common: {
       normal: 'assets/fonts/pdf/FreeSerif.ttf',
       bold: 'assets/fonts/pdf/FreeSerif.ttf',
       italics: 'assets/fonts/pdf/FreeSerif.ttf',
       bolditalics: 'assets/fonts/pdf/FreeSerif.ttf',
     },
   };

   content['defaultStyle'] = {
     font: 'common'
   };
   pdfInstant.createPdf(content).getBase64((r: any) => {
      this.utilService.sharePDF(new Date().getTime() / 1000 + '.pdf', r);
   });
}

注意:确认字体文件存放在src/assets/fonts/pdf/目录下,且angular.json的assets数组包含src/assets(默认已配置,可检查确认)。

方案二:嵌入Base64格式字体(最可靠)

将字体转换为Base64字符串直接嵌入,彻底绕开本地文件路径问题,兼容iOS和Android:

  1. 将FreeSerif.ttf转换为Base64字符串(可使用本地工具或离线转换方式);
  2. 在项目中创建字体配置文件(如src/app/utils/font-config.ts),存储Base64字符串:
export const FONT_FREE_SERIF = 'data:font/truetype;base64,此处替换为你的字体Base64内容';
  1. 修改生成PDF的代码:
import { FONT_FREE_SERIF } from './utils/font-config';

generatePDF(pdfInstant: any, content: any) {
  pdfInstant.fonts = {
    common: {
       normal: FONT_FREE_SERIF,
       bold: FONT_FREE_SERIF,
       italics: FONT_FREE_SERIF,
       bolditalics: FONT_FREE_SERIF,
     },
   };

   content['defaultStyle'] = {
     font: 'common'
   };
   pdfInstant.createPdf(content).getBase64((r: any) => {
      this.utilService.sharePDF(new Date().getTime() / 1000 + '.pdf', r);
   });
}

方案三:检查Capacitor资源配置(可选)

若坚持使用文件路径,需确保Capacitor能正确访问资源:

  • 确认iOS项目的Info.plist配置了本地文件访问权限(Ionic默认已配置,若自定义过配置需检查);
  • 运行npx cap sync ios同步资源到iOS项目,确保字体文件已被正确打包到APP中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:22:32