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

在.NET中使用iText.Kernel库:如何将Windows字体转为PdfFont?

如何将Windows字体(从TextBlock获取)转换为iText.Kernel.Font.PdfFont?

刚好之前做过类似的需求,在.NET环境下用iText处理Windows字体转PdfFont其实核心是拿到字体文件的路径,再用iText的工厂类加载就行,给你一步步拆解:

1. 从TextBlock提取字体文件路径

不管你用的是WPF还是WinForms的文本控件,首先得从控件的字体对象里找到对应的本地字体文件路径——因为iText需要直接读取字体文件来生成PdfFont。

针对WPF的TextBlock(FontFamily对象)

WPF的TextBlock.FontFamily返回的是System.Windows.Media.FontFamily,我们需要遍历它的源来找到实际的字体文件:

// 从你的TextBlock获取FontFamily
var targetFontFamily = yourTextBlock.FontFamily;
string fontFilePath = null;

foreach (var source in targetFontFamily.Source)
{
    // 先检查是不是直接指向本地文件
    if (File.Exists(source))
    {
        fontFilePath = source;
        break;
    }
    // 如果是系统字体名,去Windows字体目录找
    else
    {
        // 尝试常见的字体后缀:ttf/ttc
        string[] possibleExtensions = { ".ttf", ".ttc" };
        foreach (var ext in possibleExtensions)
        {
            string systemFontPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
                source + ext
            );
            if (File.Exists(systemFontPath))
            {
                fontFilePath = systemFontPath;
                break;
            }
        }
        if (fontFilePath != null) break;
    }
}

针对WinForms的文本控件(Font对象)

如果是WinForms里的类似控件(比如Label),拿到System.Drawing.Font后,可以这样找路径:

var winFont = yourLabel.Font;
string fontFilePath = null;
string[] possibleExtensions = { ".ttf", ".ttc" };

foreach (var ext in possibleExtensions)
{
    fontFilePath = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
        winFont.FontFamily.Name + ext
    );
    if (File.Exists(fontFilePath)) break;
}

2. 用iText加载字体生成PdfFont

拿到字体文件路径后,直接用PdfFontFactory.LoadFont方法就能生成需要的PdfFont了,这里有几个关键参数要注意:

if (!string.IsNullOrEmpty(fontFilePath))
{
    // 加载字体,推荐用IDENTITY_H编码支持全字符(包括中文、特殊符号等)
    // PREFER_EMBEDDED会把字体嵌入PDF,避免其他设备无此字体时显示异常
    PdfFont pdfFont = PdfFontFactory.LoadFont(
        fontFilePath,
        PdfEncodings.IDENTITY_H,
        PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED
    );

    // 给Paragraph设置字体
    Paragraph yourParagraph = new Paragraph("这是测试文本")
        .SetFont(pdfFont)
        .SetFontSize(14);
}

一些注意事项

  • 字体集合文件(.ttc):如果是.ttc格式的字体包(比如宋体simsun.ttc),可以在LoadFont里加一个索引参数指定要加载的字体,比如PdfFontFactory.LoadFont(fontFilePath, 0, ...),0代表集合里的第一个字体。
  • 权限问题:确保程序有读取Windows字体目录的权限,一般桌面程序默认都有,但服务端程序可能需要额外配置。
  • 编码选择:如果只需要英文,用PdfEncodings.WINANSI也可以,但要支持非ASCII字符,IDENTITY_H是最稳妥的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:27:21