1. 程式人生 > >PDFBOX處理PDF文件

PDFBOX處理PDF文件

首先,在學習中接觸到了pdfbox,感覺用它處理pdf文件確實很方便,從網上找到一段處理文件的程式碼,但執行中發現一些問題,具體的解決方法如下,希望給你有所幫助,

首先在myeclipse中建立一個java工程,

從pdfbox官網中下載pdfbox,然後將pdfbox中的相關jar包匯入工程中,建立buildpath,具體方法可以從網上搜索。

建立一個java檔案,

具體程式碼如下:

package pdfbox;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

public class Pdfbox {
public static final String DEFAULT_ENCODING = "UTF-8";


// "ISO-8859-1";
// "ISO-8859-6";
// "US-ASCII";
// "UTF-8";
// "UTF-16";
// "UTF-16BE";
// "UTF-16LE";
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 = 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) {
Pdfbox test = new Pdfbox();
try {
test.geText("D:\\中文測試.pdf");
FileReader fr = new FileReader("D:\\中文測試.txt");
BufferedReader br =  new BufferedReader(fr);
String s = br.readLine();
while(s!=null)
{
System.out.println(s);
s = br.readLine();
}br.close();
fr.close();


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

}

可能出現的問題:

處理英文pdf可以抽出文字,但中文的無法解決,會出現亂碼或者報錯:

首先,可能編碼方式不對,輸入流編碼方式最好用UTF-8,workspace的編碼方式預設是GBK,

其次:pdf文件格式不規範,有些pdf文件是處理時會報錯或亂碼,可嘗試換一個正規格式的文件。

最後:我用的是pdfbox0.7.3版的,據說據說是pdfBox從0.7.3版本開始就沒有編譯好的dll,

從網上下載一個pdfbox-1.1.0的jar檔案,解壓後將裡面的

fontbox-1.0.0.jar和pdfbox-1.1.0.jar放入到工程的lib資料夾中,然後通過buildpath——>configurebuildpath——>addjars

置換開始匯入的兩個檔名相同的舊版本檔案。再次執行就會發現,問題解決了!!