使用itextsharp从Pdf文件中提取文本和文本矩形坐标

6

我正在尝试从PDF文件中获取所有单词及其位置坐标。我已经成功地使用Acrobat API在.NET上完成了这个任务。现在,我想使用免费的API(如iTextSharp)来实现同样的功能(.NET版本)。我可以使用PRTokeniser逐行获取文本,但是我不知道如何获取每行的坐标,更不用说每个单词的坐标了。


4
如果您在商业应用程序中使用iText和iTextSharp,它们并不是免费的。 - Andrew Cash
2个回答

14

我的账户太新了,无法回复Mark Storer的答案。

我无法直接使用LocationTextExtracationStrategy(我认为我可能做错了些什么)。当我使用LocationTextExtracationStrategy时,我能够获取文本,但我无法弄清楚如何获取每个字符串(或每行字符串)的坐标。

最终,我创建了LocationTextExtracationStrategy的子类,并公开了我想要的数据,因为它在内部确实具有该数据。

我还希望它在.net中可用... 所以这里是我编写的C#版本。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using iTextSharp.text.pdf.parser;

namespace PdfHelper
{
    /// <summary>
    /// Taken from http://www.java-frameworks.com/java/itext/com/itextpdf/text/pdf/parser/LocationTextExtractionStrategy.java.html
    /// </summary>
    class LocationTextExtractionStrategyEx : LocationTextExtractionStrategy
    {
        private List<TextChunk> m_locationResult = new List<TextChunk>();
        private List<TextInfo> m_TextLocationInfo = new List<TextInfo>();
        public List<TextChunk> LocationResult 
        {
            get { return m_locationResult; }
        }
        public List<TextInfo> TextLocationInfo
        {
            get { return m_TextLocationInfo; }
        }

        /// <summary>
        /// Creates a new LocationTextExtracationStrategyEx
        /// </summary>
        public LocationTextExtractionStrategyEx()
        {
        }

        /// <summary>
        /// Returns the result so far
        /// </summary>
        /// <returns>a String with the resulting text</returns>
        public override String GetResultantText()
        {
            m_locationResult.Sort();

            StringBuilder sb = new StringBuilder();
            TextChunk lastChunk = null;
            TextInfo lastTextInfo = null;
            foreach (TextChunk chunk in m_locationResult)
            {
                if (lastChunk == null)
                {
                    sb.Append(chunk.Text);
                    lastTextInfo = new TextInfo(chunk);
                    m_TextLocationInfo.Add(lastTextInfo);
                }
                else
                {
                    if (chunk.sameLine(lastChunk))
                    {
                        float dist = chunk.distanceFromEndOf(lastChunk);

                        if (dist < -chunk.CharSpaceWidth)
                        {
                            sb.Append(' ');
                            lastTextInfo.addSpace();
                        }
                        //append a space if the trailing char of the prev string wasn't a space && the 1st char of the current string isn't a space
                        else if (dist > chunk.CharSpaceWidth / 2.0f && chunk.Text[0] != ' ' && lastChunk.Text[lastChunk.Text.Length - 1] != ' ')
                        {
                            sb.Append(' ');
                            lastTextInfo.addSpace();
                        }
                        sb.Append(chunk.Text);
                        lastTextInfo.appendText(chunk);
                    }
                    else
                    {
                        sb.Append('\n');
                        sb.Append(chunk.Text);
                        lastTextInfo = new TextInfo(chunk);
                        m_TextLocationInfo.Add(lastTextInfo);
                    }
                }
                lastChunk = chunk;
            }
            return sb.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="renderInfo"></param>
        public override void RenderText(TextRenderInfo renderInfo)
        {
            LineSegment segment = renderInfo.GetBaseline();
            TextChunk location = new TextChunk(renderInfo.GetText(), segment.GetStartPoint(), segment.GetEndPoint(), renderInfo.GetSingleSpaceWidth(), renderInfo.GetAscentLine(), renderInfo.GetDescentLine());
            m_locationResult.Add(location);
        }

        public class TextChunk : IComparable, ICloneable
        {
            string m_text;
            Vector m_startLocation;
            Vector m_endLocation;
            Vector m_orientationVector;
            int m_orientationMagnitude;
            int m_distPerpendicular;
            float m_distParallelStart;
            float m_distParallelEnd;
            float m_charSpaceWidth;

            public LineSegment AscentLine;
            public LineSegment DecentLine;

            public object Clone()
            {
                TextChunk copy = new TextChunk(m_text, m_startLocation, m_endLocation, m_charSpaceWidth, AscentLine, DecentLine);
                return copy;
            }

            public string Text
            {
                get { return m_text; }
                set { m_text = value; }
            }
            public float CharSpaceWidth
            {
                get { return m_charSpaceWidth; }
                set { m_charSpaceWidth = value; }
            }
            public Vector StartLocation
            {
                get { return m_startLocation; }
                set { m_startLocation = value; }
            }
            public Vector EndLocation
            {
                get { return m_endLocation; }
                set { m_endLocation = value; }
            }

            /// <summary>
            /// Represents a chunk of text, it's orientation, and location relative to the orientation vector
            /// </summary>
            /// <param name="txt"></param>
            /// <param name="startLoc"></param>
            /// <param name="endLoc"></param>
            /// <param name="charSpaceWidth"></param>
            public TextChunk(string txt, Vector startLoc, Vector endLoc, float charSpaceWidth, LineSegment ascentLine, LineSegment decentLine)
            {
                m_text = txt;
                m_startLocation = startLoc;
                m_endLocation = endLoc;
                m_charSpaceWidth = charSpaceWidth;
                AscentLine = ascentLine;
                DecentLine = decentLine;

                m_orientationVector = m_endLocation.Subtract(m_startLocation).Normalize();
                m_orientationMagnitude = (int)(Math.Atan2(m_orientationVector[Vector.I2], m_orientationVector[Vector.I1]) * 1000);

                // see http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
                // the two vectors we are crossing are in the same plane, so the result will be purely
                // in the z-axis (out of plane) direction, so we just take the I3 component of the result
                Vector origin = new Vector(0, 0, 1);
                m_distPerpendicular = (int)(m_startLocation.Subtract(origin)).Cross(m_orientationVector)[Vector.I3];

                m_distParallelStart = m_orientationVector.Dot(m_startLocation);
                m_distParallelEnd = m_orientationVector.Dot(m_endLocation);
            }

            /// <summary>
            /// true if this location is on the the same line as the other text chunk
            /// </summary>
            /// <param name="textChunkToCompare">the location to compare to</param>
            /// <returns>true if this location is on the the same line as the other</returns>
            public bool sameLine(TextChunk textChunkToCompare)
            {
                if (m_orientationMagnitude != textChunkToCompare.m_orientationMagnitude) return false;
                if (m_distPerpendicular != textChunkToCompare.m_distPerpendicular) return false;
                return true;
            }

            /// <summary>
            /// Computes the distance between the end of 'other' and the beginning of this chunk
            /// in the direction of this chunk's orientation vector.  Note that it's a bad idea
            /// to call this for chunks that aren't on the same line and orientation, but we don't
            /// explicitly check for that condition for performance reasons.
            /// </summary>
            /// <param name="other"></param>
            /// <returns>the number of spaces between the end of 'other' and the beginning of this chunk</returns>
            public float distanceFromEndOf(TextChunk other)
            {
                float distance = m_distParallelStart - other.m_distParallelEnd;
                return distance;
            }

            /// <summary>
            /// Compares based on orientation, perpendicular distance, then parallel distance
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            public int CompareTo(object obj)
            {
                if (obj == null) throw new ArgumentException("Object is now a TextChunk");

                TextChunk rhs = obj as TextChunk;
                if (rhs != null)
                {
                    if (this == rhs) return 0;

                    int rslt;
                    rslt = m_orientationMagnitude - rhs.m_orientationMagnitude;
                    if (rslt != 0) return rslt;

                    rslt = m_distPerpendicular - rhs.m_distPerpendicular;
                    if (rslt != 0) return rslt;

                    // note: it's never safe to check floating point numbers for equality, and if two chunks
                    // are truly right on top of each other, which one comes first or second just doesn't matter
                    // so we arbitrarily choose this way.
                    rslt = m_distParallelStart < rhs.m_distParallelStart ? -1 : 1;

                    return rslt;
                }
                else
                {
                    throw new ArgumentException("Object is now a TextChunk");
                }
            }
        }

        public class TextInfo
        {
            public Vector TopLeft;
            public Vector BottomRight;
            private string m_Text;

            public string Text
            {
                get { return m_Text; }
            }

            /// <summary>
            /// Create a TextInfo.
            /// </summary>
            /// <param name="initialTextChunk"></param>
            public TextInfo(TextChunk initialTextChunk)
            {
                TopLeft = initialTextChunk.AscentLine.GetStartPoint();
                BottomRight = initialTextChunk.DecentLine.GetEndPoint();
                m_Text = initialTextChunk.Text;
            }

            /// <summary>
            /// Add more text to this TextInfo.
            /// </summary>
            /// <param name="additionalTextChunk"></param>
            public void appendText(TextChunk additionalTextChunk)
            {
                BottomRight = additionalTextChunk.DecentLine.GetEndPoint();
                m_Text += additionalTextChunk.Text;
            }

            /// <summary>
            /// Add a space to the TextInfo.  This will leave the endpoint out of sync with the text.
            /// The assumtion is that you will add more text after the space which will correct the endpoint.
            /// </summary>
            public void addSpace()
            {
                m_Text += ' ';
            }


        }
    }
}

我添加了一个TextLocationInfo属性,它会返回一个文本行列表和这些行的坐标(左上角和右下角),可以用来给你提供一个边界框。
我还发现在我的初始尝试中出现了一些奇怪的东西。看起来如果我从基线(我认为正确的做法是从ascentLine和DecentLine中提取这些点)中提取startPoint和endPoint,我得到的坐标是相同的。在我的初始尝试中,我只使用了基线。奇怪的是,我没有看到结果坐标的差异。所以要注意...我不确定我提供的坐标是否正确...我只是认为它们是/应该是正确的。

你好,你的类看起来非常有帮助。我该如何使用它根据找到的文本位置向PDF添加命名目标? - xspydr
我不确定所谓的命名目标是什么。我猜想你可以修改GetResultantText,使其在附加到m_TextLocationInfo之前也创建一个“命名目标”。或者你可以直接使用该类来解析文本和位置,然后迭代文本位置列表并为每个位置创建一个“命名目标”。 - greenhat
这个能否轻松修改以便为每个字符提供位置? - d456
我已经有一段时间没有看过这个了。我认为这不是一个简单的问题,但也许不会太糟糕。每个文本块都通过RenderText传入。不幸的是,这些块不是单个字符。但是,您可以将每个传入的块分解为单个字符,以便您拥有一堆新的文本块,每个块长度为1,并将它们添加到m_locationResult中。之后,我认为它会起作用。 - greenhat

10

您需要使用com.itextpdf.text.pdf.parser包中的类。它们跟踪当前的转换、颜色、字体等等。

不幸的是,这些类没有在新书中涵盖,所以您只能使用JavaDoc,并将其从Java转换为C#,这并不太难。

因此,您需要将LocationTextExtractionStrategy插入到PdfTextExtractor中。

这将为您提供字符串和位置如其在pdf中呈现的那样。您需要将其解释为单词(如果需要,还有段落,哎哟)。

请记住,PDF不知道文本布局。每个字符都可以单独放置。如果有人愿意(他们必须是一些塔可饼组合盘的缺少),他们可以在给定页面上绘制所有的“a”,然后所有的“b”,依此类推。

更现实的是,有人可能会画出页面上使用FontA的所有文本,然后画出所有使用FontB的文本,等等。这可以产生更有效的内容流。请记住,italicbold(以及bold italic)都是单独的字体。如果有人将一个词的一部分标记为粗体(或其他),那么该逻辑词就需要被拆分成至少两个绘图命令。

但是很多人只是按照逻辑顺序写出他们的文本到PDF中……这对于那些困在解析中的人来说非常方便,但您不能指望所有的PDF都是如此。因为您肯定会遇到一些奇怪的情况。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接