Apache PDFBox 是一個開源的 Java PDF 函式庫,支援建立、操作、提取 PDF 文件內容。本文示範如何使用 PDFBox 的 PDFTextStripper 類別,從 PDF 檔案中擷取指定頁碼範圍的純文字內容。
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-app</artifactId>
<version>2.0.27</version> <!-- 請使用最新版本 -->
</dependency>
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 {
public static String getText(File file, int startPage, int endPage) throws IOException {
try (PDDocument document = PDDocument.load(file)) {
PDFTextStripper stripper = new PDFTextStripper();
stripper.setSortByPosition(true); // 依位置排序文字
stripper.setStartPage(startPage); // 起始頁 (1-based)
stripper.setEndPage(endPage); // 結束頁
return stripper.getText(document);
}
}
public static void main(String[] args) {
File file = new File("/path/to/your/document.pdf");
try {
String content = getText(file, 1, 10); // 提取第 1-10 頁
System.out.println(content);
} catch (IOException e) {
System.err.println("PDF 文字提取失敗: " + e.getMessage());
e.printStackTrace();
}
}
}
AutoCloseable,建議用 try-with-resources 自動關閉。setSortByPosition(true):依照座標位置排序輸出文字,閱讀順序更自然。setStartPage(int) / setEndPage(int):限定提取頁碼範圍 (1 起算)。getText(PDDocument):執行提取並回傳字串。FontBox 子專案,可進一步分析字體資訊。JempBox 子專案支援 XMP 元資料讀寫。PDAcroForm 操作互動式表單欄位。PDDocument.load(file, password) 解密。