首页 > 解决方案 > 从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);



        }


    }

标签: javapdfitext7text-extraction

解决方案


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

推荐阅读