微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 iText 从 pdf 中提取字体名称、大小、样式

如何解决使用 iText 从 pdf 中提取字体名称、大小、样式

我正在尝试使用 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);
    }
}

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

是否有机会使用 iText 获得正确的尺寸?

解决方法

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

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 辅助类)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。