2012-01-11 125 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。

希望它有幫助。