2012-01-11 255 views
6

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

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

+3

我不完全清楚你在做什么。阅读文本和提取文本通常是同一件事。 iText不会将文本保存到一个文件中,但是一旦你有了文本,你就可以很容易地做到这一点。只要iText实际上是文本(不是轮廓线或位图),iText就可以提取文本。当搜索这个网站时,也会查找iText的.Net端口iTextSharp。它有更多的问题/答案,C#的代码几乎完全相同。 – 2012-01-11 19:01:28

回答

3

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

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

13

像西奥多说,你可以从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。

希望它有帮助。