使用iText提取PDF文本

时间:2012-01-11 14:40:03

标签: itext

我们正在进行信息提取方面的研究,我们想使用iText。

我们正在探索iText。根据我们审查的文献,iText是最好的工具。是否可以在iText中从每行的pdf中提取文本?我在这里发布了与我相关的stackoverflow中的一个问题,但它只是读取文本而不是提取它。任何人都可以帮我解决我的问题吗?谢谢。

2 个答案:

答案 0 :(得分:16)

像西奥多一样,你可以从pdf中提取文字,就像克里斯指出的那样

  

只要它实际上是文本(不是轮廓或位图)

最好的办法是购买Bruno Lowagie的书Itext。在第二版中,第15章介绍了提取文本。

但你可以看看他的网站上的例子。 http://itextpdf.com/examples/iia.php?id=279

你可以解析它来创建一个普通的txt文件。 这是一个代码示例:

/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

package part4.chapter15;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

public class ExtractPageContent {

    /** The original PDF that will be parsed. */
    public static final String PREFACE = "resources/pdfs/preface.pdf";
    /** The resulting text file. */
    public static final String RESULT = "results/part4/chapter15/preface.txt";

    /**
     * Parses a PDF to a plain text file.
     * @param pdf the original PDF
     * @param txt the resulting text
     * @throws IOException
     */
    public void parsePdf(String pdf, String txt) throws IOException {
        PdfReader reader = new PdfReader(pdf);
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        PrintWriter out = new PrintWriter(new FileOutputStream(txt));
        TextExtractionStrategy strategy;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
            out.println(strategy.getResultantText());
        }
        reader.close();
        out.flush();
        out.close();
    }

    /**
     * Main method.
     * @param    args    no arguments needed
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        new ExtractPageContent().parsePdf(PREFACE, RESULT);
    }
}

注意许可证

  

此示例仅适用于iText的AGPL版本。

如果你看一下其他例子,它将展示如何省略部分文本或如何提取部分pdf。

希望它有所帮助。

答案 1 :(得分:3)

iText允许您这样做,但无法保证文本块的粒度,这取决于生成文档时使用的实际pdf渲染器。

很有可能每个单词或甚至字母都有自己的文本块。这些也不需要按词汇顺序排列,为了获得可靠的结果,您可能需要根据文本块的坐标对文本块进行重新排序。此外,您可能需要计算是否需要在文本块之间插入空格。

相关问题