iTextSharp - 如何获取单词在页面上的位置 [英] iTextSharp - How to get the position of word on a page

查看:29
本文介绍了iTextSharp - 如何获取单词在页面上的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 iTextSharp 和 reader.GetPageContent 方法从 PDF 中提取文本.我需要为文档中找到的每个单词找到矩形/位置.有没有办法使用 iTextSharp 在 PDF 中获取单词的矩形/位置?

I am using iTextSharp and the reader.GetPageContent method to pull the text out of a PDF. I need to find the rectangle/position for each word found in the document. Is there any way to get the rectangle/position of a word in a PDF using iTextSharp?

推荐答案

是的.查看 text.pdf.parser 包,特别是 LocationTextExtractionStrategy.实际上,这也可能不起作用.您可能想要编写自己的 TextExtractionStrategy 以输入 PdfTextExtractor:

Yes there is. Check out the text.pdf.parser package, specifically LocationTextExtractionStrategy. Actually, that might not do the trick either. You'll probably want to write your own TextExtractionStrategy to feed into PdfTextExtractor:

MyTexExStrat strat = new MyTexExStrat();
PdfTextExtractor.getTextFromPage(reader, pageNum, strat);
// get the strings-n-rects from strat.

public class MyTexExStrat implements TextExtractionStrategy {
    void beginTextBlock() {}
    void endTextBlock() {}
    void renderImage(ImageRenderInfo info) {}
    void renderText(TextRenderInfo info) {
      // track text and location here.
    }
}

您可能需要查看 LocationTextExtractionStrategy 的源代码,以了解它如何组合共享基线的文本.您甚至可以修改 LTES 来存储并行的字符串和矩形数组.

You'll probably want to look at the source for LocationTextExtractionStrategy to see how it combines text that shares a baseline. You might even just modify LTES to store parallel arrays of strings and rects.

PS:要构建矩形,您只需获取 AscentLine &DescentLine 并将这些坐标用作顶角和底角:

PS: to build the rects, you can just get the AscentLine & DescentLine and use those coordinates as the top and bottom corners:

Vector bottomLeft = info.getDescentLine().getStartPoint();
Vector topRight = info.getAscentLine().getEndPoint();
Rectangle rect = new Rectangle(bottomLeft.get(Vector.I1),
                               bottomLeft.get(Vector.I2),
                               topRight.get(Vector.I1),
                               topRight.get(Vector.I2));

警告:上面的代码说明文本是水平的并且从左到右进行.旋转文本会搞砸,垂直文本或从右到左(阿拉伯语、希伯来语)的文本也是如此.对于大多数应用程序,以上应该没问题,但要知道它的局限性.

Warning: The above code ass-u-mes that the text is horizontal and proceeds from left to right. Rotated text will screw it up, as will vertical text or right-to-left (Arabic, Hebrew) text. For most applications, the above should be fine, but know it's limits.

打猎不错.

这篇关于iTextSharp - 如何获取单词在页面上的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆