使用pdfbox解析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();
}
}在代碼區域右鍵 -> 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>