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

iText 8 pdfHTML:SVG元素添加替代文本的正确语法是什么?

解决iText 8 + pdfHTML转换带SVG的HTML到PDF/UA时替代文本不生效的问题

你的SVG写法和iText的无障碍支持规则不匹配,导致替代文本没被正确解析。iText处理SVG的无障碍文本时,优先识别SVG内部的<title>(主替代文本)和<desc>(补充描述),同时必须正确配置PDF/UA转换参数。

正确的SVG HTML写法

移除SVG上无效的alt属性(SVG标准不支持该属性,iText不会识别),确保<title>是SVG的第一个子元素,同时保留role="img"让屏幕阅读器识别为图像角色:

<p>Remember to keep it simple for PDF/UA compliance.</p>
<svg role="img" width="100" height="100" aria-labelledby="svg-title">
    <title id="svg-title">A red circle</title>
    <!-- 可选:添加desc提供更详细描述 -->
    <desc>A solid red circle centered in a 100x100 viewport</desc>
    <circle cx="50" cy="50" r="40" fill="red"></circle>
</svg>
  • <title>会被iText识别为SVG的主替代文本,映射到PDF的Alt文本字段
  • <desc>可选,用于补充详细描述,屏幕阅读器会读取该内容
  • aria-labelledby关联<title>的id,确保辅助技术正确关联文本

iText转换的关键配置

必须开启PDF/UA模式,否则无障碍标签和替代文本不会被写入PDF。示例Java代码:

import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfUAConfiguration;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class AccessibleSvgPdfConverter {
    public static void main(String[] args) throws Exception {
        String inputHtml = "path/to/your/input.html";
        String outputPdf = "path/to/your/output.pdf";

        // 配置PDF/UA参数
        PdfUAConfiguration uaConfig = new PdfUAConfiguration();
        uaConfig.setTagged(true);
        uaConfig.setLanguage("en"); // PDF/UA要求设置文档语言
        uaConfig.setTitle("Accessible PDF with SVG Element");

        // 初始化PDF写入器和文档
        PdfWriter writer = new PdfWriter(new FileOutputStream(outputPdf), uaConfig);
        PdfDocument pdfDoc = new PdfDocument(writer);
        pdfDoc.setTagged();
        pdfDoc.getCatalog().setLang(new com.itextpdf.kernel.pdf.PdfString("en"));

        // 执行HTML转PDF
        HtmlConverter.convertToPdf(new FileInputStream(inputHtml), pdfDoc);

        // 关闭资源
        pdfDoc.close();
        writer.close();
    }
}

核心注意事项

  1. PDF/UA模式必须开启:setTagged(true)、设置文档语言是PDF/UA合规的必要条件,也是iText生成无障碍标签的前提
  2. SVG的无障碍文本依赖<title>和<desc>,而非HTML的alt属性
  3. <title>必须是SVG的第一个子元素,否则iText可能无法正确识别

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:22:10