為什麼選擇 PDFBox?
Apache PDFBox 是成熟的 Java PDF 函式庫,透過 IKVM 編譯為 .NET 組件,提供:
- 純 .NET 運作,無需安裝 Adobe Acrobat
- 開源免費 (Apache License 2.0)
- 功能完整:文字提取、合併分割、加密解密、表單填寫、轉圖片、列印
- 支援 PDF 1.7 規範 (ISO 32000-1)
環境準備
- 下載 PDFBox-0.7.3 for .NET (或較新版 PDFBox 2.x/3.x via NuGet)
- 參考兩個 DLL:
- `PDFBox-0.7.3.dll` (核心)
- `IKVM.GNU.Classpath.dll` (Java 執行環境)
- 專案目標框架:.NET Framework 4.x (舊版) 或 .NET Standard 2.0+ (新版)
核心功能實作
1. PDF 文字提取
using org.pdfbox.pdmodel;
using org.pdfbox.util;
public static string ExtractTextFromPdf(string pdfPath)
{
using (var doc = PDDocument.load(pdfPath))
{
var stripper = new PDFTextStripper();
return stripper.getText(doc);
}
}
// 進階:指定頁面範圍
public static string ExtractTextFromPdf(string pdfPath, int startPage, int endPage)
{
using (var doc = PDDocument.load(pdfPath))
{
var stripper = new PDFTextStripper();
stripper.setStartPage(startPage);
stripper.setEndPage(endPage);
return stripper.getText(doc);
}
}
// 進階:依區域提取 (座標篩選)
public static string ExtractTextByRegion(string pdfPath, int pageNum, Rectangle region)
{
using (var doc = PDDocument.load(pdfPath))
{
var stripper = new PDFTextStripperByArea();
stripper.addRegion("region1", region);
stripper.extractRegions(doc.getPage(pageNum - 1));
return stripper.getTextForRegion("region1");
}
}
2. PDF 合併
public static void MergePdfs(string[] sourceFiles, string outputFile)
{
using (var outputDoc = new PDDocument())
{
foreach (string file in sourceFiles)
{
using (var sourceDoc = PDDocument.load(file))
{
// 將來源文件所有頁面匯入目標文件
var pages = sourceDoc.getDocumentCatalog().getAllPages();
foreach (PDPage page in pages)
{
outputDoc.addPage(page);
}
}
}
outputDoc.save(outputFile);
}
}
// 串流版本 (不寫入磁碟)
public static byte[] MergePdfsToBytes(string[] sourceFiles)
{
using (var outputDoc = new PDDocument())
using (var ms = new MemoryStream())
{
foreach (string file in sourceFiles)
{
using (var sourceDoc = PDDocument.load(file))
{
foreach (PDPage page in sourceDoc.getDocumentCatalog().getAllPages())
outputDoc.addPage(page);
}
}
outputDoc.save(ms);
return ms.ToArray();
}
}
3. 文字寫入檔案輔助方法
public static void WriteToTextFile(string text, string filePath)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException("輸出檔案路徑不得為空");
// 確保目錄存在
var dir = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
{
writer.Write(text);
}
}
完整應用範例:批次處理資料夾下所有 PDF
public static void BatchExtractPdfText(string folderPath, string outputFolder)
{
if (!Directory.Exists(outputFolder))
Directory.CreateDirectory(outputFolder);
var pdfFiles = Directory.GetFiles(folderPath, "*.pdf");
foreach (var pdfFile in pdfFiles)
{
try
{
string text = ExtractTextFromPdf(pdfFile);
string fileName = Path.GetFileNameWithoutExtension(pdfFile) + ".txt";
string outputPath = Path.Combine(outputFolder, fileName);
WriteToTextFile(text, outputPath);
Console.WriteLine($"完成: {pdfFile}");
}
catch (Exception ex)
{
Console.WriteLine($"失敗: {pdfFile} - {ex.Message}");
}
}
}
PDFBox 支援的完整功能清單
| 功能類別 | 主要類別/方法 | 說明 |
| 文字提取 | PDFTextStripper, PDFTextStripperByArea | 完整文字、指定頁面、指定區域、保留版面 |
| 文件合併 | PDDocument.addPage(), PDDocumentMerger | 多檔合併、插入頁面、重新排序 |
| 文件分割 | PDDocument.getPage(), 新建 Document | 單頁拆分、範圍擷取 |
| 加密/解密 | PDDocument.protect(), StandardProtectionPolicy | 密碼保護、權限控制 (列印、複製、修改) |
| 表單處理 | PDAcroForm, PDField | 填寫表單、匯出 FDF/XFDF、扁平化 |
| 圖片轉換 | PDFRenderer, PDFBox.convertToImage() | PDF 轉 PNG/JPEG/TIFF、解析度控制 |
| 建立 PDF | PDDocument, PDPageContentStream | 從文字、圖片建立 PDF、繪圖、字型嵌入 |
| 列印 | PDFPrintable, PrinterJob | 無訊息列印、指定印表機 |
| Lucene 整合 | PDFDocument, LucenePDFDocument | PDF 全文檢索索引 |
常見問題與解決方案
| 問題 | 原因 | 解決方案 |
| 中文亂碼/空白 | 字型未嵌入、無對應字型 | 使用 `PDFTextStripper.setSortByPosition(true)`;確保 PDF 內嵌字型 |
| 文字順序錯亂 | PDF 內部儲存順序非閱讀順序 | `stripper.setSortByPosition(true)` 依座標排序 |
| 大檔案 OOM | 一次載入整份文件 | 分頁處理、使用 `PDFTextStripper.getText(page)` 單頁提取 |
| IKVM 版本衝突 | 多專案引用不同版本 | 統一 NuGet 管理、繫結重導向 |
| .NET Core 不支援 | 舊版 PDFBox 0.7.3 僅支援 .NET Framework | 升級 PDFBox 2.x/3.x (NuGet: `PDFBox`) |
現代替代方案比較
| 函式庫 | 語言 | .NET Core 支援 | 授權 | 特色 |
| PDFBox (IKVM) | Java→.NET | 2.x+ 支援 | Apache 2.0 | 功能最完整、成熟穩定 |
| PdfSharp | C# 原生 | 支援 | MIT | 輕量、易用、建立 PDF 強 |
| iText 7 (iTextSharp) | Java/C# | 支援 | AGPL/商業 | 功能最強、商業需付費 |
| QuestPDF | C# 原生 | 支援 | MIT | 現代 API、排版強、熱門新秀 |
| SkiaSharp + PDF | C++/C# | 支援 | MIT | 跨平台繪圖、轉 PDF |
總結
PDFBox 透過 IKVM 將成熟的 Java PDF 處理能力帶入 .NET 生態系,對於「文字提取」、「文件合併」等核心需求提供了可靠的開源解決方案。本文涵蓋從基本提取合併到批次處理、進階區域提取的完整實作。現代 .NET Core 專案建議直接使用 PDFBox 3.x (NuGet) 或評估 PdfSharp/QuestPDF 等原生替代方案,獲得更好的效能與開發體驗。