跳過到頁腳內容
遷移指南

如何從 Apache PDFBox 轉移到 IronPDF

從 Apache PDFBox 轉移到 IronPDF:完整的 C# 遷移指南。

Apache PDFBox 是備受推崇的開放源碼 Java 函式庫,用於 PDF 操作。 然而,對於 .NET 開發人員而言,唯一可用的選擇是非官方社群驅動的移植,這帶來了重大的挑戰 - Java 式的 API、不完整的功能涵蓋以及稀少的 .NET 社群支援。 本綜合指南提供了從 Apache PDFBox .NET 移植到IronPDF的逐步遷移路徑,IronPDF 是專為 .NET 生態系統從底層建立的原生 .NET PDF 函式庫。

為何要遷離 Apache PDFBox .NET Ports? 雖然 Apache PDFBox 在 Java 生態系統中表現優異,但其非官方的 .NET 移植卻提出了影響 .NET 開發團隊的幾項挑戰。 ### 非官方埠狀態 Apache PDFBox 基本上是一個 Java 函式庫。 所有 .NET 版本均為社群驅動的移植版本,缺乏 Apache 專案的官方支援。 這些移植版本經常落後於 Java 版本,可能會錯過重要功能、錯誤修正或安全更新。 對於建置應用程式的團隊而言,其長期使用需求可延長至 2025 年和 2026 年,這種不確定性會造成技術風險。 ### Java-First API 設計 移植的 API 保留了在 .NET 程式碼中感覺陌生的 Java 慣例。 開發人員會遇到 `camelCase` 方法而不是 `PascalCase`, Java `File` 物件而不是標準的 .NET 字串, 以及明確的 `close()` 呼叫而不是 `IDisposable` 模式。 這種認知上的開銷會影響開發速度和程式碼的可維護性。 ### 無 HTML 渲染能力 Apache PDFBox 專為 PDF 操作而設計,而非 HTML 至 PDF 的轉換。 建立 PDF 需要以手動方式建立頁面,並進行精確的座標定位 - 這個過程既乏味又容易出錯,無法滿足現代文件產生的需求。 ### 有限的 .NET 社群支援 圍繞 Apache PDFBox 連接埠的 .NET 生態系統非常稀少。 與擁有活躍的 .NET 社群的圖書館相比,尋找針對 .NET 特定問題的說明、範例或最佳實務相當困難。 ### 潛在的 JVM 相依性 某些 Apache PDFBox 移植可能需要 Java 執行時元件,增加了以 .NET 為重點的基礎架構中部署與環境管理的複雜性。 ## Apache PDFBox vs. IronPDF:主要差異 瞭解這些程式庫的基本差異有助於規劃有效的遷移策略。 |範疇|Apache PDFBox .NET 連接埠|IronPDF| |--------|-------------------------|---------| |**原生設計**|以 Java 為中心,非官方的 .NET 移植|原生 .NET,專業支援| |**API 風格**|Java 慣例 (`camelCase`, `close()`)|成語 C# (`PascalCase`, `using`)| |**HTML 渲染**|不支援 (手動建頁)|完全基於 Chromium 的 HTML/CSS/JS| |**PDF製作**|手動坐標定位|基於 CSS 的版面設計| |**社群**|Java 為主,.NET 資源稀少|活躍的 .NET 社群,下載量超過 10M| |<強>支援document.close()pdf.ExtractAllText()PDDocument.load(path)document.save(路徑)pdf.SaveAs(路徑)document.close()document.getNumberOfPages()pdf.PageCountpdf.Pages[index]pdf.ExtractAllText()pdf.Pages[n].Textmerger.addSource(file)merger.mergeDocuments()PdfDocument.Merge(pdfs)splitter.split(document)pdf.CopyPages(indices)pdf.SecuritySettingspolicy.setUserPassword()policy.setOwnerPassword()pdf.SecuritySettings.OwnerPasswordpolicy.setPermissions()pdf.SecuritySettings.AllowUserXxxHello World

This is HTML to PDF

"); pdf.SaveAs("output.pdf"); Console.WriteLine("PDF created successfully"); } } ``` IronPDF 基於 Chromium 的渲染引擎提供完整的 HTML、CSS 和 JavaScript 支援。 如需進階方案,請參閱 [HTML to PDF 文件](https://ironpdf.com/how-to/html-file-to-pdf/)。 ### 合併多個 PDF 文件 **Apache PDFBox .NET Port 實作:** ```csharp // Apache PDFBox .NET port attempt (incomplete support) using PdfBoxDotNet.Pdmodel; using PdfBoxDotNet.Multipdf; using System; using System.IO; class Program { static void Main() { // PDFBox-dotnet ports have incomplete API coverage var merger = new PDFMergerUtility(); merger.AddSource("document1.pdf"); merger.AddSource("document2.pdf"); merger.SetDestinationFileName("merged.pdf"); merger.MergeDocuments(); Console.WriteLine("PDFs merged"); } } ``` **IronPDF 實作:** ```csharp // NuGet: Install-Package IronPdf using IronPdf; using System; using System.Collections.Generic; class Program { static void Main() { var pdf1 = PdfDocument.FromFile("document1.pdf"); var pdf2 = PdfDocument.FromFile("document2.pdf"); var pdf3 = PdfDocument.FromFile("document3.pdf"); var merged = PdfDocument.Merge(pdf1, pdf2, pdf3); merged.SaveAs("merged.pdf"); Console.WriteLine("PDFs merged successfully"); } } ``` IronPdf 的靜態 `Merge` 方法可直接接受多個文件,省去了實用類模式。 ### 從零開始創建 PDF 最顯著的差異出現在建立 PDF 時。 Apache PDFBox 需要手動坐標定位。 **Apache PDFBox .NET Port 實作:** ```csharp using org.apache.pdfbox.pdmodel; using org.apache.pdfbox.pdmodel.font; using org.apache.pdfbox.pdmodel.edit; public void CreatePdf(string outputPath) { PDDocument document = new PDDocument(); try { PDPage page = new PDPage(); document.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(document, page); PDFont font = PDType1Font.HELVETICA_BOLD; contentStream.beginText(); contentStream.setFont(font, 24); contentStream.moveTextPositionByAmount(72, 700); contentStream.drawString("Hello World"); contentStream.endText(); contentStream.beginText(); contentStream.setFont(PDType1Font.HELVETICA, 12); contentStream.moveTextPositionByAmount(72, 650); contentStream.drawString("This is a paragraph of text."); contentStream.endText(); contentStream.close(); document.save(outputPath); } finally { document.close(); } } ``` **IronPDF 實作:** ```csharp using IronPdf; public void CreatePdf(string outputPath) { var renderer = new ChromePdfRenderer(); string html = @"

Hello World

This is a paragraph of text.

"; using var pdf = renderer.RenderHtmlAsPdf(html); pdf.SaveAs(outputPath); } ``` 基於 HTML/CSS 的創作省去了座標計算、字型管理和內容串流操作。 ### 新增密碼保護 **Apache PDFBox .NET Port 實作:** ```csharp using org.apache.pdfbox.pdmodel; using org.apache.pdfbox.pdmodel.encryption; public void ProtectPdf(string inputPath, string outputPath, string password) { PDDocument document = PDDocument.load(new File(inputPath)); try { AccessPermission ap = new AccessPermission(); ap.setCanPrint(true); ap.setCanExtractContent(false); StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password, ap); spp.setEncryptionKeyLength(128); document.protect(spp); document.save(outputPath); } finally { document.close(); } } ``` **IronPDF 實作:** ```csharp using IronPdf; public void ProtectPdf(string inputPath, string outputPath, string password) { using var pdf = PdfDocument.FromFile(inputPath); pdf.SecuritySettings.UserPassword = password; pdf.SecuritySettings.OwnerPassword = password; pdf.SecuritySettings.AllowUserPrinting = PdfPrintSecurity.FullPrintRights; pdf.SecuritySettings.AllowUserCopyPasteContent = false; pdf.SaveAs(outputPath); } ``` IronPdf 使用強式類型的屬性,而非獨立的權限與政策物件。 ### 新增水印 **Apache PDFBox .NET Port 實作:** ```csharp using org.apache.pdfbox.pdmodel; using org.apache.pdfbox.pdmodel.edit; using org.apache.pdfbox.pdmodel.font; public void AddWatermark(string inputPath, string outputPath, string watermarkText) { PDDocument document = PDDocument.load(new File(inputPath)); try { PDFont font = PDType1Font.HELVETICA_BOLD; for (int i = 0; i < document.getNumberOfPages(); i++) { PDPage page = document.getPage(i); PDPageContentStream cs = new PDPageContentStream( document, page, PDPageContentStream.AppendMode.APPEND, true, true); cs.beginText(); cs.setFont(font, 72); cs.setNonStrokingColor(200, 200, 200); cs.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(45), 200, 400)); cs.showText(watermarkText); cs.endText(); cs.close(); } document.save(outputPath); } finally { document.close(); } } ``` **IronPDF 實作:** ```csharp using IronPdf; public void AddWatermark(string inputPath, string outputPath, string watermarkText) { using var pdf = PdfDocument.FromFile(inputPath); pdf.ApplyWatermark( $"

{watermarkText}

", rotation: 45, opacity: 50); pdf.SaveAs(outputPath); } ``` IronPdf 的[基於 HTML 的水印](https://ironpdf.com/how-to/backgrounds-and-foregrounds/)消除了頁面迭代和矩陣計算。 ### URL 轉 PDF Apache PDFBox 不支援 URL 至 PDF 的轉換。 IronPdf 提供本機支援: ```csharp using IronPdf; public void ConvertUrlToPdf(string url, string outputPath) { var renderer = new ChromePdfRenderer(); using var pdf = renderer.RenderUrlAsPdf(url); pdf.SaveAs(outputPath); } ``` 如需完整的 URL 轉換選項,請參閱 [URL to PDF 文件](https://ironpdf.com/how-to/url-to-pdf/)。 ### 頁首和頁尾 Apache PDFBox 需要在每個頁面上手動定位,沒有內建的頁首/頁尾支援。 IronPdf 提供宣告式配置: ```csharp using IronPdf; public void CreatePdfWithHeaderFooter(string html, string outputPath) { var renderer = new ChromePdfRenderer(); renderer.RenderingOptions.TextHeader = new TextHeaderFooter { CenterText = "Document Title", FontSize = 12 }; renderer.RenderingOptions.TextFooter = new TextHeaderFooter { CenterText = "Page {page} of {total-pages}", FontSize = 10 }; using var pdf = renderer.RenderHtmlAsPdf(html); pdf.SaveAs(outputPath); } ``` 如需進階佈局,請參閱 [headers and footers 文件](https://ironpdf.com/how-to/headers-and-footers/)。 ## ASP.NET Core 整合。 IronPDF 可與現代 .NET 網路應用程式自然整合: ```csharp [HttpPost] public IActionResult GeneratePdf([FromBody] ReportRequest request) { var renderer = new ChromePdfRenderer(); using var pdf = renderer.RenderHtmlAsPdf(request.Html); return File(pdf.BinaryData, "application/pdf", "report.pdf"); } ``` ### 同步支援 Apache PDFBox 連接埠不支援 async 作業。 IronPdf 提供完整的 async/await 功能: ```csharp using IronPdf; public async Task GeneratePdfAsync(string html) { var renderer = new ChromePdfRenderer(); using var pdf = await renderer.RenderHtmlAsPdfAsync(html); return pdf.BinaryData; } ``` ### 依賴注入配置 ```csharp public interface IPdfService { Task GeneratePdfAsync(string html); string ExtractText(string pdfPath); } public class IronPdfService : IPdfService { private readonly ChromePdfRenderer _renderer; public IronPdfService() { _renderer = new ChromePdfRenderer(); _renderer.RenderingOptions.PaperSize = PdfPaperSize.A4; } public async Task GeneratePdfAsync(string html) { using var pdf = await _renderer.RenderHtmlAsPdfAsync(html); return pdf.BinaryData; } public string ExtractText(string pdfPath) { using var pdf = PdfDocument.FromFile(pdfPath); return pdf.ExtractAllText(); } } ``` ## 效能最佳化 ### 記憶體使用量比較 |工作場景|Apache PDFBox .NET 移植|IronPDF| 筆記 | |----------|------------------------|---------|-------| |文字擷取|~80 MB|~50 MB|IronPdf 更有效率| |PDF 建立|~100 MB|~60 MB|HTML 渲染已優化| |批次 (100 PDF)|高(手動清理)|~100 MB|使用 `using` 語句| ### 最佳化提示 **使用 ` 使用`語句:** ```csharp //自動化cleanup with IDisposable pattern using var pdf = PdfDocument.FromFile(path); ``` **批次作業的重複使用渲染器:** ```csharp var renderer = new ChromePdfRenderer(); foreach (var html in htmlList) { using var pdf = renderer.RenderHtmlAsPdf(html); pdf.SaveAs($"output_{i}.pdf"); } ``` **在 Web 應用程式中使用 Async:** ```csharp using var pdf = await renderer.RenderHtmlAsPdfAsync(html); ``` ## 排除常見的遷移問題 ### 問題:未找到 Java 型方法名稱 用 `PascalCase` .NET 對應方法取代 `camelCase` Java 方法: ```csharp // PDFBox: stripper.getText(document) // IronPDF: pdf.ExtractAllText() // PDFBox: document.getNumberOfPages() // IronPDF: pdf.PageCount ``` ### 問題:沒有 `close()` 方法。 IronPDF 使用 `IDisposable` 模式: ```csharp // PDFBox document.close(); // IronPDF using var pdf = PdfDocument.FromFile(path); //自動化disposal at end of scope ``` ### 問題:沒有 `PDFTextStripper` 同等級產品。 文字擷取簡化為單一方法: ```csharp // IronPDF: Just call ExtractAllText() string text = pdf.ExtractAllText(); // Per-page extraction: string pageText = pdf.Pages[0].Text; ``` ### 問題:`PDFMergerUtility` 未找到。 使用靜態 `Merge` 方法: ```csharp //IronPDFuses static Merge var merged = PdfDocument.Merge(pdf1, pdf2, pdf3); ``` ## 遷移後檢查清單 完成程式碼遷移後,請驗證下列事項: - [ ] 執行所有現有的單元與整合測試 - [ ] 比較 PDF 輸出與先前版本的視覺效果 - [ ] 測試文字擷取的精確度 - [ ] 驗證授權是否正常運作 (`IronPdf.License.IsLicensed`) - [ ] 與先前實作比較的效能基準 - [ ] 更新 CI/CD 管道的相依性 - [ ] 為您的開發團隊記錄新的模式 ## Future-Proofing Your PDF Infrastructure 由於 .NET 10 即將推出,而 C# 14 也將引進新的語言功能,因此選擇原生的 .NET PDF 函式庫可確保與不斷演進的執行時功能相容。IronPDFfor .NET 承諾支援最新的 .NET 版本,這意味著當專案延伸至 2025 年和 2026 年時,您的移轉投資將獲得回報。 ## 其他資源 - [IronPDF文件](https://ironpdf.com/docs/)。 - [HTML to PDF Tutorials](https://ironpdf.com/tutorials/) - [API Reference](https://ironpdf.com/object-reference/api/) - [NuGet 套件](https://www.nuget.org/packages/IronPdf/)。 - [授權選項](https://ironpdf.com/licensing/) --- 從 Apache PDFBox .NET 移植到 IronPDF,可將您的 PDF 程式碼基礎從 Java 風格的模式轉換為成語化的 C#。 從手動坐標定位轉換到 HTML/CSS 渲染,結合原生的 async 支援和現代的 .NET 整合,提供更乾淨、更易維護的程式碼,並有專業的支援支援您的生產應用程式。
Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。