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

将HTML转换为PDF/A时报错:所有字体必须嵌入,Times-Bold未嵌入

解决HTML转PDF/A时“Times-Bold未嵌入”的字体问题

Got it, let's fix that "Times-Bold not embedded" error when converting HTML to PDF/A. The core issue here is that PDF/A mandates all fonts used in the document are embedded, and your current setup isn't handling the Times-Bold font properly. Here's how to resolve this with iText:

方案1:手动指定并嵌入字体文件

如果你有Times-Bold(以及配套的Times常规字体)的.ttf文件,可以显式将它们添加到字体提供者并启用嵌入:

public const String INTENT = "sRGB Color Space Profile.icm";
static void Main(string[] args) {
    String HTML = "<h1>Test</h1><p>Hello World</p>";
    PdfWriter writer = new PdfWriter("hello.pdf");
    PdfADocument pdf = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3A, 
        new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", 
        new FileStream(INTENT, FileMode.Open)));
    pdf.SetTagged();

    // 1. 创建字体提供者并添加需要嵌入的字体
    FontProvider fontProvider = new FontProvider();
    // 替换为你的Times-Bold字体文件路径,第三个参数true表示强制嵌入
    fontProvider.AddFont(@"C:\fonts\Times-Bold.ttf", PdfEncodings.IDENTITY_H, true);
    // 同时添加常规Times字体,避免普通文本的字体问题
    fontProvider.AddFont(@"C:\fonts\Times-Roman.ttf", PdfEncodings.IDENTITY_H, true);

    // 2. 将字体提供者绑定到转换属性
    ConverterProperties properties = new ConverterProperties();
    properties.SetFontProvider(fontProvider);

    // 3. 执行HTML转换
    HtmlConverter.ConvertToDocument(HTML, pdf, properties);

    pdf.Close();
}

方案2:使用系统字体并强制嵌入

如果不想额外打包字体文件,可以直接调用系统中已安装的Times字体,通过SystemFontProvider配置自动嵌入:

public const String INTENT = "sRGB Color Space Profile.icm";
static void Main(string[] args) {
    String HTML = "<h1>Test</h1><p>Hello World</p>";
    PdfWriter writer = new PdfWriter("hello.pdf");
    PdfADocument pdf = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_3A, 
        new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", 
        new FileStream(INTENT, FileMode.Open)));
    pdf.SetTagged();

    // 1. 创建系统字体提供者,参数true表示注册所有系统字体
    SystemFontProvider fontProvider = new SystemFontProvider(true);
    // 启用子集化嵌入,只嵌入文档中实际用到的字符,减小文件体积(可选但推荐)
    fontProvider.SetUseSubset(true);

    // 2. 将字体提供者绑定到转换属性
    ConverterProperties properties = new ConverterProperties();
    properties.SetFontProvider(fontProvider);

    // 3. 执行HTML转换
    HtmlConverter.ConvertToDocument(HTML, pdf, properties);

    pdf.Close();
}

关键说明

  • 你的HTML里<h1>标签会被渲染为粗体,这会触发Times-Bold字体的使用。如果不明确配置该字体的嵌入逻辑,iText默认不会为PDF/A文档嵌入它。
  • 要确保HTML中用到的所有字体变体(包括粗体、斜体)都被字体提供者覆盖,要么手动添加字体文件,要么通过系统字体提供者自动获取。
  • 子集化嵌入(SetUseSubset(true))只会打包文档中实际用到的字符,能有效控制PDF文件的大小。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:13:07