我想从 pdf 中提取特定文本,我有文本的确切位置
我尝试使用 itext7 进行提取,但是当我创建具有正确尺寸的提取矩形时,它似乎太大而无法匹配文本,但尺寸是正确的,我尝试了 SimpleTextExtractionStrategy 和 LocationTextExtractionStrategy 结果相同 pdfFile
private void estraiValori(PdfPage page) {
for (Entry<String, Elemento> entry : templateMap.entrySet()) {
String key = entry.getKey();
Elemento value=(Elemento) entry.getValue();
//Rectangle tmp=new Rectangle((float)238.64,(float) 14.8,(float) 122,(float) 28.7);
TextRegionEventFilter fontFilter = new TextRegionEventFilter(value.getDim()); //getDim is a rectangle
FilteredEventListener listener = new FilteredEventListener();
//LocationTextExtractionStrategy extractionStrategy = listener.attachEventListener(new LocationTextExtractionStrategy(), fontFilter);
SimpleTextExtractionStrategy extractionStrategy = listener.attachEventListener(new SimpleTextExtractionStrategy(), fontFilter);
new PdfCanvasProcessor(listener).processPageContent(page);//page is a PdfPage
String actualText = extractionStrategy.getResultantText();
System.out.println(actualText);
}
}
最佳答案
可以通过多种方式在 PDF 中显示(视觉上)相同的内容。您可以逐个字形或整个句子附加文本字形。 TextRegionEventFilter
在过滤之前不会将较大的文本 block 拆分为较小的文本 block 。如果文本是以大块形式编写的,而您只需要其中的一部分,则需要对原始内容进行预处理,即分成更小的 block 。
幸运的是,iText 提供了一种开箱即用的方法来做到这一点 - 该类称为 GlyphTextEventListener
,它可以链接到其他 ITextExtractionStrategy
实例。只需按以下方式将监听器包装到 ITextExtractionStrategy
中即可:
TextRegionEventFilter filter = new TextRegionEventFilter(new Rectangle(x1, y1, x2, y2));
ITextExtractionStrategy filteredListener = new FilteredTextEventListener(new LocationTextExtractionStrategy(), filter);
ITextExtractionStrategy fineGrainedListener = new GlyphTextEventListener(filteredListener);
new PdfCanvasProcessor(fineGrainedListener).processPageContent(page);
关于java - 从java中的特定位置提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56057382/