Java 从PDF中提取文本位置
我正在尝试查找PDF中文本元素的位置。为此,我扩展了PDFTextStripper。我正在用它做测试Java 从PDF中提取文本位置,java,pdf,text,position,pdfbox,Java,Pdf,Text,Position,Pdfbox,我正在尝试查找PDF中文本元素的位置。为此,我扩展了PDFTextStripper。我正在用它做测试 public class TextFinder extends PDFTextStripper { private static final Logger logger = LoggerFactory.getLogger(TextFinder.class); private PDRectangle mediaBox; public static cla
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);
}
}
多亏了mkl,这个问题是由自定义运算符处理器引起的。没有它,一切正常。但我需要操作员处理器,因为我用它来查找图像。我仍然不太明白,为什么添加自定义处理器会影响PDFTextStripper的行为
为什么添加自定义处理器会影响PDFTextStripper的行为
原因是你的加入
实际上替换了现有的处理器。原始版本对于确定页面上的正确位置很重要
解决方案是连锁处理。我只是想重现你的问题。但是,运行代码时,我会得到不同的坐标,特别是不是从0,0开始。您使用哪个PDFBox版本?我使用1.8.8进行了测试。如果我没记错的话,以前有一个版本,
writeString
检索到一个bugtextPositions
列表。对不起,我的错。我没有向代码段中添加自定义运算符处理器,这实际上是导致此问题的原因。但我仍然不太明白,为什么添加自定义处理器会影响PDFTextStripper的行为。-实际上,您不添加而是替换现有的,并且转换矩阵在确定位置的上下文中非常重要。我将此注释作为实际答案。我通过重写PDFStreamEngine.processOperator(pdfooperator operator,List arguments)解决了此问题
而不是使用运算符处理器
。这本质上也是链接。您只是链接processOperator调用,而不是Processor.process调用。
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)
registerOperatorProcessor("cm", cmProcessor);