java从PDF中提取文本位置
我试图在PDF中找到文本元素的位置。为此,我扩展了PDFTextStripper。我用multi-page LaTeX-produced PDF进行测试
public class TextFinder extends PDFTextStripper {
private static final Logger logger =
LoggerFactory.getLogger(TextFinder.class);
private PDRectangle mediaBox;
public static class CMProcessor extends OperatorProcessor {
@Override
public void process(PDFOperator operator, List<COSBase> arguments)
throws IOException {
if ("cm".equals(operator.getOperation())) {
logger.debug("CM operation");
}
}
}
private CMProcessor cmProcessor = new CMProcessor();
public TextFinder() throws IOException {
this.registerOperatorProcessor("cm", cmProcessor);
}
@Override
protected void startPage(PDPage page) throws IOException {
super.startPage(page);
mediaBox = page.findMediaBox();
logger.debug(String.format("MEDIA (%f,%f) (%f,%f)",
mediaBox.getLowerLeftX(), mediaBox.getLowerLeftY(),
mediaBox.getUpperRightX(), mediaBox.getUpperRightY()));
}
@Override
protected void writeString(String text, List<TextPosition> textPositions)
throws IOException {
for (TextPosition position : textPositions) {
float x = position.getXDirAdj();
float y = mediaBox.getHeight() - position.getYDirAdj();
logger.debug(String.format("(%f,%f) (%f,%f)", x, y,
x + position.getWidthDirAdj(), y + position.getHeightDir()));
}
super.writeString(text, textPositions);
}
}
我面临的问题是,所有位置的转换方式似乎都是(0,0)是最左边最上面的文本元素的坐标:
MEDIA (0.000000,0.000000) (595.270020,841.890015)
(0.000000,0.000000) (11.486961,14.255401)
(11.486961,0.000000) (20.660002,14.255401)
(20.660002,0.000000) (36.733482,14.255401)
多亏了mkl,这个问题是由自定义运算符处理器引起的。没有它,一切正常。但我需要操作员处理器,因为我用它来寻找图像。我仍然不太明白,为什么添加自定义处理器会影响PDFTextStripper的行为
# 1 楼答案
原因是你的添加
实际上,取代了现有的处理器。原始版本对于确定页面上的正确位置很重要
解决方案是连锁处理器