You need to enable JavaScript to run this app. 使用iText7提取PDF字体名称、大小、样式时字号取值异常如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用iText7提取PDF字体名称、大小、样式时字号取值异常如何解决

你调用TextRenderInfo.GetFontSize()获取的是PDF内容流中定义的原始字号参数,部分PDF生成工具会将原始字号设置为1,再通过文本变换矩阵的缩放系数控制实际显示的字号,这就是你获取到的值恒为1、和Adobe Acrobat显示结果不一致的原因。

要获取和Acrobat一致的实际显示字号,需要结合文本渲染时的变换矩阵计算缩放后的大小,修正后的自定义提取策略代码如下:

public class FontSizeSimpleTextExtractionStrategy : SimpleTextExtractionStrategy
{
    FieldInfo _textField = typeof(TextRenderInfo).GetField("text", BindingFlags.NonPublic | BindingFlags.Instance);
    public override void EventOccurred(IEventData data, EventType type)
    {
        if (type.Equals(EventType.RENDER_TEXT))
        {
            TextRenderInfo renderInfo = (TextRenderInfo)data;
            string fontName = renderInfo.GetFont()?.GetFontProgram()?.GetFontNames()?.GetFontName();
            iText.Kernel.Colors.Color color = renderInfo.GetFillColor();
            // 原始字号参数
            float originalSize = renderInfo.GetFontSize();
            // 获取文本矩阵Y轴缩放系数,计算实际显示字号
            Matrix textMatrix = renderInfo.GetTextMatrix();
            float actualFontSize = originalSize * textMatrix.Get(Matrix.I22);
            // 浮点精度处理,保留1位小数即可
            actualFontSize = (float)Math.Round(actualFontSize, 1);

            if (fontName != null)
            {
                _textField.SetValue(renderInfo, "#Data|" + fontName + "|" + actualFontSize.ToString() + "|" + ColorToString(color) + "|Data#" + renderInfo.GetText());
            }

        }
        base.EventOccurred(data, type);
    }
}

如果需要适配存在旋转、非均匀缩放的特殊PDF,也可以通过文本基线长度计算实际字号,替换上述字号计算逻辑即可:

LineSegment baseline = renderInfo.GetBaseline();
float actualFontSize = baseline.GetLength() / renderInfo.GetText().Length;

以上两种方式都可以正确获取到你提到的测试文件中25、11的字号结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 06:24:01