【问题标题】:Extract fontname, size, style from pdf with iText使用 iText 从 pdf 中提取字体名称、大小、样式
【发布时间】:2021-06-25 16:00:03
【问题描述】:

我正在尝试使用 iText 7.1.14 根据字体、字体大小和字体样式从各种 pdf 文件中提取文本。

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 size = renderInfo.GetFontSize();

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

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

在某些文件中,“大小”的值始终为“1”,尽管 Adob​​e Acrobat 显示正确的字体大小,即 this example file 中的 25 和 11。

是否有机会使用 iText 获得正确的大小?

【问题讨论】:

    标签: c# .net-5 itext7


    【解决方案1】:

    造成这个问题的原因是当前变换矩阵和文本矩阵对绘制文本的变换被忽略了。

    TextRenderInfo 返回的字体大小是绘制文本时当前图形状态的字体大小值。该值还不包括当前文本和变换矩阵对绘制文本的变换。 因此,我们必须通过这些矩阵转换一个与字体大小值一样长的垂直向量,并从结果中确定有效大小。

    TextRenderInfo.GetTextMatrix() 值实际上包含了文本矩阵和当前变换矩阵的乘积,所以我们只需要使用那个值。

    class FontSizeSimpleTextExtractionStrategyImproved : 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();
                Color color = renderInfo.GetFillColor();
    
                float size = renderInfo.GetFontSize();
                Vector sizeHighVector = new Vector(0, size, 0);
                Matrix matrix = renderInfo.GetTextMatrix();
                float sizeAdjusted = sizeHighVector.Cross(matrix).Length();
    
                if (fontName != null)
                {
                    _textField.SetValue(renderInfo, "#Data|" + fontName + "|" + sizeAdjusted.ToString() + "|" + ColorToString(color) + "|Data#" + renderInfo.GetText());
                }
            }
            base.EventOccurred(data, type);
        }
    }
    

    (ExtractWithFontSize 助手类)

    【讨论】:

    • 没想到转换,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2014-04-15
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多