Pdfbox PDFTextStripperByArea坐标移位



我有坐标问题。PDFTextStripperByArea区域似乎被推得太高了。

考虑下面的示例片段:

...
PDPage page = (PDPage) allPages.get(0);
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
// define region for extraction -- the coordinates and dimensions are x, y, width, height
Rectangle2D.Float region = new Rectangle2D.Float(x, y, width, height);
stripper.addRegion("test region", region);
// overlay the region with a cyan rectangle to check if I got the coordinates and dimensions right 
PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);
contentStream.setNonStrokingColor( Color.CYAN );
contentStream.fillRect(x, y, width, height );
contentStream.close();
// extract the text from the defined region
stripper.extractRegions(page);
String content = stripper.getTextForRegion("test region"); 
... 
document.save(...); ...
青色矩形很好地覆盖了所需的区域。另一方面,stripper遗漏了矩形底部的几条线,并包括矩形上方的几条线——看起来它被"向上"移动了(通过y坐标)。发生了什么事?

正如Christian在他的评论中所说,问题在于fillRect()方法的坐标系统和PDFTextStripperByArea的坐标系统是不同的。

第一个函数期望原点在页面的左下角,而第二个函数期望原点在左上角。

因此,要使其工作,将给定给PDFTextStripperByArea的区域更改为:

Rectangle2D.Float region = new Rectangle2D.Float(x, ph - y - height, width, height);

其中ph为页面高度:

float ph = page.getMediaBox().getUpperRightY();

PS:我知道这是一个非常古老的问题,但是当我面临同样的问题时,谷歌带我来这里,所以我将添加我的答案。

文本通常包含在定位矩形内。有时,文本不在该矩形内的预期位置,PDFBox使用该矩形尝试猜测文本的位置。因此,如果文本从捕获区域外开始并流入该区域,则可能无法提取。

草图:文本框在捕获区域外开始,但文本在其中流动。它可能不会被捕获。

____________
|Page      |
|   _______|
|   |Area ||
|   |     ||
| ..|.....||
| ⁞ |Text⁞||
| ⁞ |____⁞||
| ⁞......⁞ |
|__________|

最新更新