java - 从java中的特定位置提取文本
问题描述
我想从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
在过滤之前不会将较大的文本块拆分为较小的文本块。如果文本是以大块的形式编写的,而您只想要其中的一部分,则需要对原始内容进行预处理,即分成更小的块。
幸运的是,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);
推荐阅读
- systemd - Systemd 有服务等待对象注册
- redux - 如何实现redux-toolkit和next,js又不丢SSR
- docker - 删除 docker 容器上的大日志文件后如何回收 ubuntu 主机上的磁盘空间
- amazon-redshift - 无法使用 Epoch 日期转换为红移日期创建自动刷新视图
- c - 警告:导入 unistd.h 后函数“sbrk”的隐式声明
- azure - Azure API 提取
策略的响应状态码 - apache-kafka - Kafka 使用 Confluent Playbooks 从 5.4.1 升级到 6.1.2
- c# - 如何使用 .net core 删除 pfx 证书
- linux - Bash 计算循环中文件和行的总数
- python-3.x - 如何在 Pywinauto 中移动和调整 UIAWrapper 而不将焦点放在被移动的窗口上