Apache PDFBox 是 Java 處理 PDF 的開源函式庫,支援文字擷取、PDF 建立、表單填寫、列印等功能。本文示範使用 PDFTextStripper 從 PDF 檔案中擷取純文字內容。另一知名函式庫 iText 側重 PDF 建立與操作,兩者可互補。
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version> <!-- 或更新版本 -->
</dependency>
PDFBox 2.x 版本 API 與 1.x 差異較大,本文以 2.x 為主。子專案 FontBox 處理字體,JempBox 處理 XMP 中繼資料。
package pdf;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class StripPDFContent {
/**
* 從 PDF 檔案擷取指定頁範圍的文字
* @param file PDF 檔案
* @return 擷取的文字內容
*/
public static String getText(File file) throws IOException {
// 參數設定
boolean sortByPosition = false; // false: 依內容流順序;true: 依座標排序
int startPage = 1; // 起始頁 (1-based)
int endPage = 10; // 結束頁
try (PDDocument document = PDDocument.load(file)) {
PDFTextStripper stripper = new PDFTextStripper();
stripper.setSortByPosition(sortByPosition);
stripper.setStartPage(startPage);
stripper.setEndPage(endPage);
return stripper.getText(document);
} catch (IOException e) {
System.err.println("PDF 解析失敗: " + e.getMessage());
throw e;
}
}
public static void main(String[] args) {
File file = new File("/path/to/your/file.pdf");
try {
String content = getText(file);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 方法 | 說明 |
|---|---|
setSortByPosition(boolean) | true 依座標由上至下、左至右排序;false 依 PDF 內容流順序(預設) |
setStartPage(int) / setEndPage(int) | 指定擷取頁碼範圍 (1-based),預設全文 |
setShouldSeparateByBeads(boolean) | 多欄版面是否以分隔符分隔(預設 false) |
getText(PDDocument) | 執行擷取並回傳字串 |
public class CustomStripper extends PDFTextStripper {
@Override
protected void writeString(String text, List textPositions) throws IOException {
// 可依字型、大小、顏色、位置過濾或轉換
if (textPositions.get(0).getFontSize() > 14) {
super.writeString("[標題]" + text + "[/標題]");
} else {
super.writeString(text);
}
}
}
try (PDDocument doc = PDDocument.load(file, "password")) {
// 解密後正常擷取
}
setSortByPosition(true) 或自訂 CustomStripper| 場景 | 推薦 | 理由 |
|---|---|---|
| 文字擷取、內容分析 | PDFBox | PDFTextStripper 功能完善、API 直覺 |
| PDF 建立、報表產生、表單填寫 | iText | 排版引擎強大、文件豐富 |
| 商業專案 | 視授權而定 | iText 5+ 採 AGPL,商業用途需購買授權;PDFBox 採 Apache 2.0 |