【问题标题】:Extract text from specific position in java从java中的特定位置提取文本
【发布时间】:2019-05-09 10:27:07
【问题描述】:

我想从 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 吗?如果没有,那么我怀疑任何人都可以帮助你。请仔细检查您的坐标。您是否知道在 PDF 中 Y 坐标从底部到顶部增加?
  • @AlexeySubach 感谢您的回答,我从评论中获取坐标,并通过 PdfAnnotation 中的 getRectangle().toRectangle() 方法从 pdf“模板”中提取矩形,所以我认为尺寸应该是正确的我也尝试手动测试只是为了做一些测试,但结果不正确要么 pdf 链接 ---> filebin.net/28jtoqiquxmlu6d3/test1.pdf?t=ry878rac
  • 您用来标记模板的 pdf2Data 使用一些启发式方法来提取文本。有问题的数据字段区域确实包含视觉上的文本(并且它是由 pdf2Data 提取的),但是当 iText 确定文本是否完全位于矩形内时,它会考虑字形的上升和下降,并且这些可能大于“彩色" 字形的区域,因此你的问题。如果您真的想为此编写自己的代码,则必须使用更大的矩形。
  • @AlexeySubach 但我有相反的问题,我接收的文本比我预期的要多,或者我错过了什么?

标签: java pdf itext7 text-extraction


【解决方案1】:

有多种方法可以在 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多