使用pdfbox解析pdf文檔

jopen 10年前發布 | 143K 次閱讀 PDF工具包 PDFBox

 

首先介紹一下pdfbox,

    1、使用PDFBox處理PDF文檔

    PDF全稱Portable Document Format,是Adobe公司開發的電子文件格式。這種文件格式與操作系統平臺無關,可以在Windows、Unix或Mac OS等操作系統上通用。

PDF文件格式將文字、字型、格式、顏色及獨立于設備和分辨率的圖形圖像等封裝在一個文件中。如果要抽取其中的文本信息,需要根據它的文件格式來進行解析。幸好目前已經有不少工具能幫助我們做這些事情。

    2、PDFBox的下載


    最常見的一種PDF文本抽取工具就是PDFBox了,訪問網址http://sourceforge.net/projects/pdfbox/,進入如 圖7-1所示的下載界面。讀者可以在該網頁下載其最新的版本。本書采用的是PDFBox-0.7.3版本。PDFBox是一個開源的Java PDF庫,這個庫允許你訪問PDF文件的各項信息。在接下來的例子中,將演示如何使用PDFBox提供的API,從一個PDF文件中提取出文本信息。

    3、在Eclipse中配置


    以下是在Eclipse中創建工程,并建立解析PDF文件的工具類的過程。

   (1)在Eclipse的workspace中創建一個普通的Java工程:ch7。

   (2)把下載的PDFBox-0.7.3.zip解壓。

   (3)進入external目錄下,可以看到,這里包括了PDFBox所有用到的外部包。復制下面的Jar包到工程ch7的lib目錄下(如還未建立lib目錄,則先創建一個)。

l bcmail-jdk14-132.jar

l bcprov-jdk14-132.jar

l checkstyle-all-4.2.jar

l FontBox-0.1.0-dev.jar

l lucene-core-2.0.0.jar

    然后再從PDFBox的lib目錄下,復制PDFBox-0.7.3.jar到工程的lib目錄下。

   (4)在工程上單擊右鍵,在彈出的快捷菜單中選擇“Build Path->Config Build Path->Add Jars”命令,把工程lib目錄下面的包都加入工程的Build Path。

    4、使用PDFBox解析PDF內容


    在剛剛創建的Eclipse工程中,創建一個pdf包,并創建一個PdfParser類。該類包含一個getText方法,用于從一個PDF中獲取文本信息,其代碼如下。

 
package pdf;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.util.PDFTextStripper;
public class PdfParser {
// TODO 自動生成方法存根
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("搜索引擎第八章.pdf");
BufferedWriter writer = new BufferedWriter(new FileWriter("change.txt"));
PDFParser p = new PDFParser(fis);
p.parse();
PDFTextStripper ts = new PDFTextStripper();
String s = ts.getText(p.getPDDocument());
writer.write(s);
System.out.println(s);
fis.close();
writer.close();
}
}


</div>

以下是個人的案例,可以借鑒一下。可能會出現控制臺亂碼的問題,這里貼一下解決方案:

解決辦法: 
在代碼區域右鍵 -> run as -> run configurations -> common(右側) -> console encoding 
如果出現此錯誤,此時的編碼格式應該是UTF-8,選擇Other,這時可能沒有GBK選項,如果沒有,則執行之后操作。

好了,下面是個人的代碼:

package pdf;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
public class PdfParser {
public void geText(String file) throws Exception {
// 是否排序
  boolean sort = false;
// pdf文件名
  String pdfFile = file;
// 輸入文本文件名稱
  String textFile = null;
// 編碼方式
  String encoding = "UTF-8";
// 開始提取頁數
  int startPage = 1;
// 結束提取頁數
  int endPage = Integer.MAX_VALUE;
// 文件輸入流,生成文本文件
  Writer output = null;
// 內存中存儲的PDF Document
  PDDocument document = null;
try {
     try {
        // 首先當作一個URL來裝載文件,如果得到異常再從本地文件系統//去裝載文件
        URL url = new URL(pdfFile);
        document = PDDocument.load(url);
        // 獲取PDF的文件名
        String fileName = url.getFile();

// 以原來PDF的名稱來命名新產生的txt文件 if (fileName.length() > 4) { File outputFile = new File(fileName.substring(0, fileName.length() - 4) + ".txt"); textFile = outputFile.getName(); } } catch (MalformedURLException e) {

// 如果作為URL裝載得到異常則從文件系統裝載 document = PDDocument.load(pdfFile); if (pdfFile.length() > 4) { textFile = pdfFile.substring(0, pdfFile.length() - 4) + ".txt"; } } // 文件輸入流,寫入文件倒textFile output = new OutputStreamWriter(new FileOutputStream(textFile), encoding); // PDFTextStripper來提取文本 PDFTextStripper stripper = null; stripper = new PDFTextStripper(); // 設置是否排序 stripper.setSortByPosition(sort); // 設置起始頁 stripper.setStartPage(startPage); // 設置結束頁 stripper.setEndPage(endPage); // 調用PDFTextStripper的writeText提取并輸出文本 stripper.writeText(document, output); } finally { if (output != null) { // 關閉輸出流 output.close(); } if (document != null) { // 關閉PDF Document document.close(); } } } public static void main(String[] args){ PdfParser test = new PdfParser(); try { // 取得C盤下的index.pdf的內容 test.geText("C:\云計算入門.pdf"); FileReader fr = new FileReader("C:\云計算入門.txt");//需要讀取的文件路徑 BufferedReader br= new BufferedReader(fr); String s = br.readLine(); while(s!=null)//如果當前行不為空 { System.out.println(s);//打印當前行 s= br.readLine();//讀取下一行 } br.close();//關閉BufferReader流 fr.close();

} catch (Exception e) { e.printStackTrace(); }

} }</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!