使用IRON SUITE

2025指南:最佳C# PDF程式庫(免費優先,視需要購買)

當大多數人想到PDF(可攜式文件格式)時,他們想到的是充滿資訊的文件。 而且他們是對的,因為現在PDF是用於分享資訊最常用的文件格式,已成為一種標準。 但當程序員查看PDF時,他們不僅看到資訊; 他們分析格式、內容類型及其其他技術方面。

在編程生成PDF檔時,維護內容的結構是最重要的任務。 而這並不像看上去那麼簡單,因為當我們提到內容時,並不僅僅意味著文本,它還包括圖像、圖表、音頻甚至影片。 另外,編程編輯PDF現在是常見的需求。

在人工智慧時代,我們希望完全掌控PDF。 有時我們需要根據政策編輯文本,保護PDF以保證敏感文件的安全,提取數據以便處理,或動態生成報告。 這些流程有很多使用案例。 這些是開發人員在編程處理PDF檔時常見的問題:

  1. 如何在處理各種類型的媒體作為內容時保持PDF文件的格式化佈局

  2. 以正確的順序提取文本,尤其是當文本在列中時

  3. 在處理擁有大量頁面的PDF文件時遇到的記憶體限制

  4. 表單處理是開發人員面臨的主要問題

  5. 將PDF文件轉換為其他合適的文件類型

為了簡化這項任務,PDF程式庫應運而生。 在這篇文章中,我們將討論多個C# PDF程式庫,例如IronPDF和Aspose.PDF,以及它們的定價模式。 我們將深入了解實際使用案例並理解這些程式庫如何在幾步內使得PDF創建和編輯編程操作簡單且適合上線。

1. IronPDF:C# PDF程式庫

IronPDF是一個全面的.NET PDF程式庫,開發人員可以使用它來創建、編輯PDF文件,將PDF文件轉換為任何其他格式,以及執行許多其他的PDF操作。 在處理大型PDF文件時,使用的內存非常少。 它完全在您的本地機器上運行,因此您不依賴於需要伺服器級別的處理。

此程式庫也兼容最新的.NET Framework,其與.NET專案的整合非常順暢。 您只需要在NuGet Package Manager中運行以下命令,IronPDF將可以在專案中使用:

Install-Package IronPdf

您無需安裝任何其他程式庫,因為它完全獨立於外部依賴項。 當您安裝此程式庫時,它會自動一次安裝所有需要的依賴。

IronPDF的最重要特性是其像素級精確轉換HTML為PDF的能力。 IronPDF提供多種方法從HTML內容創建PDF文件。 您可以將HTML字符串、HTML文件或URL直接轉換成PDF。 它也支持CSS和JavaScript,以確保生成的PDF文件準確反映原始HTML呈現。

除了基礎操作,IronPDF還支持PDF表單、各層級加密和添加數位簽名。 您可以從PDF文件中提取圖像和文本。 您還可以添加文本或HTML標頭和頁腳、合併和拆分PDF、修改多個文本段落及尋找和替換文本。 IronPDF不僅支持從HTML創建PDFs,還支持從DOCX、RTF、MD和圖像文件轉換為PDF。 此程式庫非常輕量並對記憶體管理非常高效(基本操作所需的記憶體小於10MB)。 IronPDF跟踪其有關穩定性和性能的里程碑,您可以從這裡訪問。

IronPDF提供多層次的支援。 您可以通過即時聊天、創建票據或電子郵件聯絡到工程師。 支援團隊提供7天24小時服務。IronPDF還有詳細的教程和文檔涵蓋大部分您需要了解或有疑問的主題。

IronPDF是一個經過測試、優化並被眾多知名公司信任的為其線上產品提供的生產準備就緒的程式庫。 這使其成為您的專案中用於PDF運行最佳的PDF程式庫之一。 讓我們來看看IronPDF程式庫的代碼示例。

代碼示例

將HTML轉換為PDF

using IronPdf;
var renderer = new ChromePdfRenderer();

// 1. HTML String to PDF
var pdf1 = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf1.SaveAs("html-string.pdf");

// 2. HTML String with Assets (Images, CSS, JS)
var pdf2 = renderer.RenderHtmlAsPdf(
    "<img src='logo.png'><link rel='stylesheet' href='style.css'>",
    @"C:\assets\"
);
pdf2.SaveAs("html-with-assets.pdf");

// 3. HTML File to PDF
var pdf3 = renderer.RenderHtmlFileAsPdf("example.html");
pdf3.SaveAs("html-file.pdf");

// 4. URL to PDF
var pdf4 = renderer.RenderUrlAsPdf("https://ironpdf.com");
pdf4.SaveAs("url.pdf");
using IronPdf;
var renderer = new ChromePdfRenderer();

// 1. HTML String to PDF
var pdf1 = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
pdf1.SaveAs("html-string.pdf");

// 2. HTML String with Assets (Images, CSS, JS)
var pdf2 = renderer.RenderHtmlAsPdf(
    "<img src='logo.png'><link rel='stylesheet' href='style.css'>",
    @"C:\assets\"
);
pdf2.SaveAs("html-with-assets.pdf");

// 3. HTML File to PDF
var pdf3 = renderer.RenderHtmlFileAsPdf("example.html");
pdf3.SaveAs("html-file.pdf");

// 4. URL to PDF
var pdf4 = renderer.RenderUrlAsPdf("https://ironpdf.com");
pdf4.SaveAs("url.pdf");
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

' 1. HTML String to PDF
Dim pdf1 = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
pdf1.SaveAs("html-string.pdf")

' 2. HTML String with Assets (Images, CSS, JS)
Dim pdf2 = renderer.RenderHtmlAsPdf("<img src='logo.png'><link rel='stylesheet' href='style.css'>", "C:\assets\")
pdf2.SaveAs("html-with-assets.pdf")

' 3. HTML File to PDF
Dim pdf3 = renderer.RenderHtmlFileAsPdf("example.html")
pdf3.SaveAs("html-file.pdf")

' 4. URL to PDF
Dim pdf4 = renderer.RenderUrlAsPdf("https://ironpdf.com")
pdf4.SaveAs("url.pdf")
$vbLabelText   $csharpLabel

從PDF中提取文本和圖像

using IronPdf;
using IronSoftware.Drawing;
using System.Collections.Generic;

// Load PDF document
var pdf = PdfDocument.FromFile("sample.pdf");

// 1. Extract All Text
string allText = pdf.ExtractAllText();

// 2. Extract Text from Specific Page
string pageText = pdf.ExtractTextFromPage(0); 

// 3. Extract Text from Multiple Pages
for (int i = 0; i < pdf.PageCount; i++)
{
    string text = pdf.ExtractTextFromPage(i);
    Console.WriteLine($"Page {i + 1}: {text}");
}

// 4. Extract All Images
var allImages = pdf.ExtractAllImages();
foreach (var image in allImages)
{
    image.SaveAs($"image_{allImages.IndexOf(image)}.png");
}

// 5. Extract Images from Specific Page
List<AnyBitmap> pageImages = pdf.ExtractBitmapsFromPage(0);

// 6. Extract Raw Images (as byte arrays)
var rawImages = pdf.ExtractAllRawImages();
for (int i = 0; i < rawImages.Count; i++)
{
    System.IO.File.WriteAllBytes($"raw_image_{i}.png", rawImages[i]);
}

// 7. Extract Both Text & Images from Each Page
for (int i = 0; i < pdf.PageCount; i++)
{
    string text = pdf.ExtractTextFromPage(i);
    List<AnyBitmap> images = pdf.ExtractBitmapsFromPage(i);

    Console.WriteLine($"Page {i + 1}: {text}");
    Console.WriteLine($"Found {images.Count} images");
}
using IronPdf;
using IronSoftware.Drawing;
using System.Collections.Generic;

// Load PDF document
var pdf = PdfDocument.FromFile("sample.pdf");

// 1. Extract All Text
string allText = pdf.ExtractAllText();

// 2. Extract Text from Specific Page
string pageText = pdf.ExtractTextFromPage(0); 

// 3. Extract Text from Multiple Pages
for (int i = 0; i < pdf.PageCount; i++)
{
    string text = pdf.ExtractTextFromPage(i);
    Console.WriteLine($"Page {i + 1}: {text}");
}

// 4. Extract All Images
var allImages = pdf.ExtractAllImages();
foreach (var image in allImages)
{
    image.SaveAs($"image_{allImages.IndexOf(image)}.png");
}

// 5. Extract Images from Specific Page
List<AnyBitmap> pageImages = pdf.ExtractBitmapsFromPage(0);

// 6. Extract Raw Images (as byte arrays)
var rawImages = pdf.ExtractAllRawImages();
for (int i = 0; i < rawImages.Count; i++)
{
    System.IO.File.WriteAllBytes($"raw_image_{i}.png", rawImages[i]);
}

// 7. Extract Both Text & Images from Each Page
for (int i = 0; i < pdf.PageCount; i++)
{
    string text = pdf.ExtractTextFromPage(i);
    List<AnyBitmap> images = pdf.ExtractBitmapsFromPage(i);

    Console.WriteLine($"Page {i + 1}: {text}");
    Console.WriteLine($"Found {images.Count} images");
}
Imports IronPdf
Imports IronSoftware.Drawing
Imports System.Collections.Generic
Imports System.IO

' Load PDF document
Dim pdf = PdfDocument.FromFile("sample.pdf")

' 1. Extract All Text
Dim allText As String = pdf.ExtractAllText()

' 2. Extract Text from Specific Page
Dim pageText As String = pdf.ExtractTextFromPage(0)

' 3. Extract Text from Multiple Pages
For i As Integer = 0 To pdf.PageCount - 1
    Dim text As String = pdf.ExtractTextFromPage(i)
    Console.WriteLine($"Page {i + 1}: {text}")
Next

' 4. Extract All Images
Dim allImages = pdf.ExtractAllImages()
For Each image In allImages
    image.SaveAs($"image_{allImages.IndexOf(image)}.png")
Next

' 5. Extract Images from Specific Page
Dim pageImages As List(Of AnyBitmap) = pdf.ExtractBitmapsFromPage(0)

' 6. Extract Raw Images (as byte arrays)
Dim rawImages = pdf.ExtractAllRawImages()
For i As Integer = 0 To rawImages.Count - 1
    File.WriteAllBytes($"raw_image_{i}.png", rawImages(i))
Next

' 7. Extract Both Text & Images from Each Page
For i As Integer = 0 To pdf.PageCount - 1
    Dim text As String = pdf.ExtractTextFromPage(i)
    Dim images As List(Of AnyBitmap) = pdf.ExtractBitmapsFromPage(i)

    Console.WriteLine($"Page {i + 1}: {text}")
    Console.WriteLine($"Found {images.Count} images")
Next
$vbLabelText   $csharpLabel

編輯PDF文件:標頭和頁腳

using IronPdf;
using System;
var renderer = new ChromePdfRenderer();

// 1. Add Footer with Page Numbers
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
    MaxHeight = 15, // mm
    DrawDividerLine = true
};
renderer.RenderingOptions.MarginBottom = 25;

// 2. Add Header with Logo
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = "<img src='logo.png'>",
    MaxHeight = 20, // mm
    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
};
renderer.RenderingOptions.MarginTop = 25;

// 3. Render HTML to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Document Title</h1><p>Content...</p>");
pdf.SaveAs("output.pdf");
using IronPdf;
using System;
var renderer = new ChromePdfRenderer();

// 1. Add Footer with Page Numbers
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
    MaxHeight = 15, // mm
    DrawDividerLine = true
};
renderer.RenderingOptions.MarginBottom = 25;

// 2. Add Header with Logo
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = "<img src='logo.png'>",
    MaxHeight = 20, // mm
    BaseUrl = new Uri(@"C:\assets\images\").AbsoluteUri
};
renderer.RenderingOptions.MarginTop = 25;

// 3. Render HTML to PDF
var pdf = renderer.RenderHtmlAsPdf("<h1>Document Title</h1><p>Content...</p>");
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports System

Dim renderer As New ChromePdfRenderer()

' 1. Add Footer with Page Numbers
renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
    .HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
    .MaxHeight = 15, ' mm
    .DrawDividerLine = True
}
renderer.RenderingOptions.MarginBottom = 25

' 2. Add Header with Logo
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
    .HtmlFragment = "<img src='logo.png'>",
    .MaxHeight = 20, ' mm
    .BaseUrl = New Uri("C:\assets\images\").AbsoluteUri
}
renderer.RenderingOptions.MarginTop = 25

' 3. Render HTML to PDF
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Document Title</h1><p>Content...</p>")
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

表單處理

using IronPdf;

// Load existing PDF with form fields
var pdf = PdfDocument.FromFile("EditableForm.pdf");

// Fill text fields
pdf.Form.FindFormField("firstname").Value = "John";
pdf.Form.FindFormField("lastname").Value = "Smith";
pdf.Form.FindFormField("email").Value = "john.smith@example.com";

// Fill radio button
pdf.Form.FindFormField("gender").Value = "Male";

// Fill dropdown/combobox
pdf.Form.FindFormField("country").Value = "USA";

// Fill checkbox ("Yes" to check, "No" to uncheck)
pdf.Form.FindFormField("subscribe").Value = "Yes";

// Fill textarea (use \r\n for line breaks)
pdf.Form.FindFormField("comments").Value = "This is a comment.\r\nSecond line here.";

// Save filled form
pdf.SaveAs("FilledForm.pdf");
using IronPdf;

// Load existing PDF with form fields
var pdf = PdfDocument.FromFile("EditableForm.pdf");

// Fill text fields
pdf.Form.FindFormField("firstname").Value = "John";
pdf.Form.FindFormField("lastname").Value = "Smith";
pdf.Form.FindFormField("email").Value = "john.smith@example.com";

// Fill radio button
pdf.Form.FindFormField("gender").Value = "Male";

// Fill dropdown/combobox
pdf.Form.FindFormField("country").Value = "USA";

// Fill checkbox ("Yes" to check, "No" to uncheck)
pdf.Form.FindFormField("subscribe").Value = "Yes";

// Fill textarea (use \r\n for line breaks)
pdf.Form.FindFormField("comments").Value = "This is a comment.\r\nSecond line here.";

// Save filled form
pdf.SaveAs("FilledForm.pdf");
Imports IronPdf

' Load existing PDF with form fields
Dim pdf = PdfDocument.FromFile("EditableForm.pdf")

' Fill text fields
pdf.Form.FindFormField("firstname").Value = "John"
pdf.Form.FindFormField("lastname").Value = "Smith"
pdf.Form.FindFormField("email").Value = "john.smith@example.com"

' Fill radio button
pdf.Form.FindFormField("gender").Value = "Male"

' Fill dropdown/combobox
pdf.Form.FindFormField("country").Value = "USA"

' Fill checkbox ("Yes" to check, "No" to uncheck)
pdf.Form.FindFormField("subscribe").Value = "Yes"

' Fill textarea (use vbCrLf for line breaks)
pdf.Form.FindFormField("comments").Value = "This is a comment." & vbCrLf & "Second line here."

' Save filled form
pdf.SaveAs("FilledForm.pdf")
$vbLabelText   $csharpLabel

從上面的例子可以看到,使用IronPDF僅需要幾行代碼即可對PDF文件進行任何操作。 這非常簡單和直接。 方法名稱易於理解和實現。

授權

IronPDF可以免費用於開發目的,您也可以下載免費試用版。 但對於生產環境,您需要購買IronPDF的授權。 IronPDF的授權模式非常靈活,提供了兩種類型的授權:

  1. 訂閱授權

  2. 永久授權

訂閱授權為您每月花費59美元(按年繳),包括1位開發人員、1個專案及每年15,000次API呼叫。 在配額超過後,每次額外的呼召需要0.03美元。

永久授權從$2,998開始,有多種選擇,您可以根據需要進行選擇。 此授權的最佳部分是一次付款。 您不需要再付費即可使用IronPDF。

Csharp Pdf Libraries Tool 1 related to 授權

2. Aspose.PDF for .NET

Aspose.PDF也是由Aspose開發的C# PDF程式庫,作為他們.NET程式庫套件的一部分,廣泛用於商業上的PDF相關任務,如創建複雜報告、敏感文件、定製PDF文件等。 它是C#中最常用的PDF程式庫之一。 它也支持最新的.NET Framework。

Aspose.PDF不僅可以從HTML內容創建PDF文件,還支持從XML文件提取數據以實現真正的數據,而不是創建靜態文件。 此功能對於創建複雜報告非常有用。 與IronPDF類似,您可以在PDF文件中添加文本、圖像、圖表及許多其他類型的內容。 Aspose.PDF還提供數位簽名嵌入、註釋處理、標頭及頁腳,以及從PDF文件提取文本。 您可以從PDF中提取結構化的數據。 該程式庫使用所提及的功能很好地處理PDF編輯。

除了Aspose.PDF程式庫的這些優點外,還存在多個缺點。 此程式庫的主要缺點是其價格非常高(起價為1679美元),且其定價模型非常複雜,不易理解。 與IronPDF不同,您必須為每個過程單獨購買模型,如開發和部署。 此外,這個程式庫非常資源消耗(當生成包含400多幅圖像的PDFs時,超過2GB)。 需要大量記憶體來處理PDF運作,這非常令人沮喪。 無疑,這個程式庫在其所做的事情上很好,但它有非常陡峭的學習曲線。 其代碼不易理解,需要非常詳細的學習會議才能理解。

代碼示例

使用文本、圖像及表格生成PDF文件

using Aspose.Pdf;
using Aspose.Pdf.Text;

using (var document = new Document())
{
    // Add page objects
    var page = document.Pages.Add();

    // Add image - requires Rectangle positioning (You can add tiff images as well)
    page.AddImage("logo.png", new Rectangle(20, 730, 120, 830));

    // Add text - requires manual positioning
    var header = new TextFragment("Company Report");
    header.TextState.Font = FontRepository.FindFont("Arial");
    header.TextState.FontSize = 24;
    header.HorizontalAlignment = HorizontalAlignment.Center;
    header.Position = new Position(130, 720);
    page.Paragraphs.Add(header);

    // Add table - extensive configuration required
    var table = new Table
    {
        ColumnWidths = "100 100 100",
        Border = new BorderInfo(BorderSide.Box, 1f, Color.Black),
        DefaultCellBorder = new BorderInfo(BorderSide.Box, 0.5f, Color.Gray),
        DefaultCellPadding = new MarginInfo(4.5, 4.5, 4.5, 4.5)
    };

    // Add header row
    var headerRow = table.Rows.Add();
    headerRow.Cells.Add("Name");
    headerRow.Cells.Add("Age");
    headerRow.Cells.Add("City");

    // Style each header cell individually
    foreach (Cell cell in headerRow.Cells)
    {
        cell.BackgroundColor = Color.LightGray;
        cell.DefaultCellTextState.FontSize = 12;
    }

    // Add data row
    var dataRow = table.Rows.Add();
    dataRow.Cells.Add("John Doe");
    dataRow.Cells.Add("30");
    dataRow.Cells.Add("New York");

    page.Paragraphs.Add(table);

    // Save document
    document.Save("Report.pdf");
}
using Aspose.Pdf;
using Aspose.Pdf.Text;

using (var document = new Document())
{
    // Add page objects
    var page = document.Pages.Add();

    // Add image - requires Rectangle positioning (You can add tiff images as well)
    page.AddImage("logo.png", new Rectangle(20, 730, 120, 830));

    // Add text - requires manual positioning
    var header = new TextFragment("Company Report");
    header.TextState.Font = FontRepository.FindFont("Arial");
    header.TextState.FontSize = 24;
    header.HorizontalAlignment = HorizontalAlignment.Center;
    header.Position = new Position(130, 720);
    page.Paragraphs.Add(header);

    // Add table - extensive configuration required
    var table = new Table
    {
        ColumnWidths = "100 100 100",
        Border = new BorderInfo(BorderSide.Box, 1f, Color.Black),
        DefaultCellBorder = new BorderInfo(BorderSide.Box, 0.5f, Color.Gray),
        DefaultCellPadding = new MarginInfo(4.5, 4.5, 4.5, 4.5)
    };

    // Add header row
    var headerRow = table.Rows.Add();
    headerRow.Cells.Add("Name");
    headerRow.Cells.Add("Age");
    headerRow.Cells.Add("City");

    // Style each header cell individually
    foreach (Cell cell in headerRow.Cells)
    {
        cell.BackgroundColor = Color.LightGray;
        cell.DefaultCellTextState.FontSize = 12;
    }

    // Add data row
    var dataRow = table.Rows.Add();
    dataRow.Cells.Add("John Doe");
    dataRow.Cells.Add("30");
    dataRow.Cells.Add("New York");

    page.Paragraphs.Add(table);

    // Save document
    document.Save("Report.pdf");
}
Imports Aspose.Pdf
Imports Aspose.Pdf.Text

Using document As New Document()
    ' Add page objects
    Dim page = document.Pages.Add()

    ' Add image - requires Rectangle positioning (You can add tiff images as well)
    page.AddImage("logo.png", New Rectangle(20, 730, 120, 830))

    ' Add text - requires manual positioning
    Dim header = New TextFragment("Company Report")
    header.TextState.Font = FontRepository.FindFont("Arial")
    header.TextState.FontSize = 24
    header.HorizontalAlignment = HorizontalAlignment.Center
    header.Position = New Position(130, 720)
    page.Paragraphs.Add(header)

    ' Add table - extensive configuration required
    Dim table = New Table With {
        .ColumnWidths = "100 100 100",
        .Border = New BorderInfo(BorderSide.Box, 1.0F, Color.Black),
        .DefaultCellBorder = New BorderInfo(BorderSide.Box, 0.5F, Color.Gray),
        .DefaultCellPadding = New MarginInfo(4.5, 4.5, 4.5, 4.5)
    }

    ' Add header row
    Dim headerRow = table.Rows.Add()
    headerRow.Cells.Add("Name")
    headerRow.Cells.Add("Age")
    headerRow.Cells.Add("City")

    ' Style each header cell individually
    For Each cell As Cell In headerRow.Cells
        cell.BackgroundColor = Color.LightGray
        cell.DefaultCellTextState.FontSize = 12
    Next

    ' Add data row
    Dim dataRow = table.Rows.Add()
    dataRow.Cells.Add("John Doe")
    dataRow.Cells.Add("30")
    dataRow.Cells.Add("New York")

    page.Paragraphs.Add(table)

    ' Save document
    document.Save("Report.pdf")
End Using
$vbLabelText   $csharpLabel

您可以看到Aspose.PDF生成新PDF文件所需的代碼非常複雜。 您必須手動設置代碼中的每個坐標。 您必須手動設計每個PDF物件的元素,非常耗時且效率不高。 但是,它對PDF文件提供了細粒度的控制。

授權

Aspose.PDF有多種授權選擇,但大多數採取即用即付模式。 授權起價是1679美元。相較IronPDF授權(從$2,998開始),它非常昂貴。

Csharp Pdf Libraries Tool 2 related to 授權

3. iTextSuite for .NET

iTextSuite(常被稱為iText & iText)是Apryse提供的PDF開發SDK。 它是一個全面的程式庫套件,擁有我們需要在.NET應用程式中執行PDF操作的所有工具。 與上述程式庫類似,您可以創建、編輯、編輯、加密和執行許多其他操作在PDF文件上。

iTextSuite非常好地處理所有PDF創建和編輯任務,無論是創建簡單的發票還是涉及到關於財務模塊的報告複雜佈局。 它在系統上也不會帶來太大負擔,可以完美處理大型文件。 它快速處理文件,並且不會產生顯著的延遲。

除了所有這些優點外,您在考慮這個程式庫時,還需要了解與iTextSuite相關的一些缺點。 相較於市場上的替代品,這個程式庫的成本據說非常高。 其原始價格不會在其價格頁面上顯示。 您必須聯絡客服以獲取報價。 它也提供AGPL授權,但這要求您在使用AGPL授權的iTextSuite時讓您的產品開源。與Aspose類似,它也有陡峭的學習曲線,不適合初學者。 高級PDF操作需要對PDF和程式庫結構的詳細理解。

代碼示例

創建帶有樣式和顏色的PDF文件表格

using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;

public void CreateStyledTable(string dest)
{
    using var writer = new PdfWriter(dest);
    using var pdf = new PdfDocument(writer);
    var document = new Document(pdf);

    // Create a 2-column table
    Table table = new Table(2, false);

    // Header cells with gray background
    Cell cell11 = new Cell(1, 1)
        .SetBackgroundColor(ColorConstants.GRAY)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("State"));

    Cell cell12 = new Cell(1, 1)
        .SetBackgroundColor(ColorConstants.GRAY)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("Capital"));

    // Data cells
    Cell cell21 = new Cell(1, 1)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("New York"));

    Cell cell22 = new Cell(1, 1)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("Albany"));

    Cell cell31 = new Cell(1, 1)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("New Jersey"));

    Cell cell32 = new Cell(1, 1)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("Trenton"));

    // Add all cells to table
    table.AddCell(cell11);
    table.AddCell(cell12);
    table.AddCell(cell21);
    table.AddCell(cell22);
    table.AddCell(cell31);
    table.AddCell(cell32);

    document.Add(table);
    document.Close();
}
using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;

public void CreateStyledTable(string dest)
{
    using var writer = new PdfWriter(dest);
    using var pdf = new PdfDocument(writer);
    var document = new Document(pdf);

    // Create a 2-column table
    Table table = new Table(2, false);

    // Header cells with gray background
    Cell cell11 = new Cell(1, 1)
        .SetBackgroundColor(ColorConstants.GRAY)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("State"));

    Cell cell12 = new Cell(1, 1)
        .SetBackgroundColor(ColorConstants.GRAY)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("Capital"));

    // Data cells
    Cell cell21 = new Cell(1, 1)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("New York"));

    Cell cell22 = new Cell(1, 1)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("Albany"));

    Cell cell31 = new Cell(1, 1)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("New Jersey"));

    Cell cell32 = new Cell(1, 1)
        .SetTextAlignment(TextAlignment.CENTER)
        .Add(new Paragraph("Trenton"));

    // Add all cells to table
    table.AddCell(cell11);
    table.AddCell(cell12);
    table.AddCell(cell21);
    table.AddCell(cell22);
    table.AddCell(cell31);
    table.AddCell(cell32);

    document.Add(table);
    document.Close();
}
Imports iText.Kernel.Colors
Imports iText.Kernel.Pdf
Imports iText.Layout
Imports iText.Layout.Element
Imports iText.Layout.Properties

Public Sub CreateStyledTable(dest As String)
    Using writer As New PdfWriter(dest)
        Using pdf As New PdfDocument(writer)
            Dim document As New Document(pdf)

            ' Create a 2-column table
            Dim table As New Table(2, False)

            ' Header cells with gray background
            Dim cell11 As New Cell(1, 1)
            cell11.SetBackgroundColor(ColorConstants.GRAY) _
                  .SetTextAlignment(TextAlignment.CENTER) _
                  .Add(New Paragraph("State"))

            Dim cell12 As New Cell(1, 1)
            cell12.SetBackgroundColor(ColorConstants.GRAY) _
                  .SetTextAlignment(TextAlignment.CENTER) _
                  .Add(New Paragraph("Capital"))

            ' Data cells
            Dim cell21 As New Cell(1, 1)
            cell21.SetTextAlignment(TextAlignment.CENTER) _
                  .Add(New Paragraph("New York"))

            Dim cell22 As New Cell(1, 1)
            cell22.SetTextAlignment(TextAlignment.CENTER) _
                  .Add(New Paragraph("Albany"))

            Dim cell31 As New Cell(1, 1)
            cell31.SetTextAlignment(TextAlignment.CENTER) _
                  .Add(New Paragraph("New Jersey"))

            Dim cell32 As New Cell(1, 1)
            cell32.SetTextAlignment(TextAlignment.CENTER) _
                  .Add(New Paragraph("Trenton"))

            ' Add all cells to table
            table.AddCell(cell11)
            table.AddCell(cell12)
            table.AddCell(cell21)
            table.AddCell(cell22)
            table.AddCell(cell31)
            table.AddCell(cell32)

            document.Add(table)
            document.Close()
        End Using
    End Using
End Sub
$vbLabelText   $csharpLabel

從上面的例子可以理解iTextSuite代碼的複雜性。這增加了開發時間和構建大應用程式的複雜性。

授權

iTextSuite提供兩種授權模式。 一種是商業授權,另一種是AGPL授權。 您可以在生產中免費使用AGPL授權的iTextSuite,但您也將需要將您的產品開源。 關於商業授權,授權頁面上並沒有提到價格。 您需要請求報價或可以聯絡客服。

Csharp Pdf Libraries Tool 3 related to 授權

4. PDFSharp

PDFSharp是一個針對開發人員在編程執行PDF操作時面臨問題的C#開源解決方案。 它支持最新的.NET框架,包括.NET Core。 它是一個輕量級解決方案,涉及開發人員關於PDF的所有基本需求。

PDFSharp能夠輕鬆處理大多數常見的PDF操作。 您可以創建文件、插入圖像、繪製形狀以及編輯文字字體和大小。 您可以將任何內容放置在任何位置,因為PDFSharp給您完整的PDF控制。

然而,PDFSharp有一些限制您需要瞭解。 它不支持原生的HTML轉PDF,對於開發人員來說這是個大缺憾,因為HTML在PDF中使樣式和排版變得非常簡單。 當它必須處理多個大文件時,其性能受到影響。 您無法進行諸如加密和表單填寫等複雜操作。 並且缺乏官方支援渠道。 如果您在使用此程式庫時遇到任何問題,您只能依賴社群或您自己的問題解決技能。

代碼示例

使用多種文字樣式創建PDF

using PdfSharp.Pdf;
using PdfSharp.Drawing;

// Create document
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);

// Example of different font styles
XFont regularFont = new XFont("Arial", 12, XFontStyleEx.Regular);
XFont boldFont = new XFont("Arial", 12, XFontStyleEx.Bold);
XFont italicFont = new XFont("Arial", 12, XFontStyleEx.Italic);
XFont boldItalicFont = new XFont("Arial", 12, XFontStyleEx.BoldItalic);

// Position for the first text
double y = 50;
double x = 50;
double lineHeight = 20;

// Draw text in different styles - REQUIRES manual positioning
gfx.DrawString("Regular text in Arial", regularFont, XBrushes.Black, x, y);
y += lineHeight;
gfx.DrawString("Bold text in Arial", boldFont, XBrushes.Black, x, y);
y += lineHeight;
gfx.DrawString("Italic text in Arial", italicFont, XBrushes.Black, x, y);
y += lineHeight;
gfx.DrawString("Bold and Italic text in Arial", boldItalicFont, XBrushes.Black, x, y);

// Save document
document.Save("FormattedText.pdf");
using PdfSharp.Pdf;
using PdfSharp.Drawing;

// Create document
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);

// Example of different font styles
XFont regularFont = new XFont("Arial", 12, XFontStyleEx.Regular);
XFont boldFont = new XFont("Arial", 12, XFontStyleEx.Bold);
XFont italicFont = new XFont("Arial", 12, XFontStyleEx.Italic);
XFont boldItalicFont = new XFont("Arial", 12, XFontStyleEx.BoldItalic);

// Position for the first text
double y = 50;
double x = 50;
double lineHeight = 20;

// Draw text in different styles - REQUIRES manual positioning
gfx.DrawString("Regular text in Arial", regularFont, XBrushes.Black, x, y);
y += lineHeight;
gfx.DrawString("Bold text in Arial", boldFont, XBrushes.Black, x, y);
y += lineHeight;
gfx.DrawString("Italic text in Arial", italicFont, XBrushes.Black, x, y);
y += lineHeight;
gfx.DrawString("Bold and Italic text in Arial", boldItalicFont, XBrushes.Black, x, y);

// Save document
document.Save("FormattedText.pdf");
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing

' Create document
Dim document As New PdfDocument()
Dim page As PdfPage = document.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)

' Example of different font styles
Dim regularFont As New XFont("Arial", 12, XFontStyleEx.Regular)
Dim boldFont As New XFont("Arial", 12, XFontStyleEx.Bold)
Dim italicFont As New XFont("Arial", 12, XFontStyleEx.Italic)
Dim boldItalicFont As New XFont("Arial", 12, XFontStyleEx.BoldItalic)

' Position for the first text
Dim y As Double = 50
Dim x As Double = 50
Dim lineHeight As Double = 20

' Draw text in different styles - REQUIRES manual positioning
gfx.DrawString("Regular text in Arial", regularFont, XBrushes.Black, x, y)
y += lineHeight
gfx.DrawString("Bold text in Arial", boldFont, XBrushes.Black, x, y)
y += lineHeight
gfx.DrawString("Italic text in Arial", italicFont, XBrushes.Black, x, y)
y += lineHeight
gfx.DrawString("Bold and Italic text in Arial", boldItalicFont, XBrushes.Black, x, y)

' Save document
document.Save("FormattedText.pdf")
$vbLabelText   $csharpLabel

對於需要輕量級、免費解決方案以精確定位控制進行基礎PDF生成的開發人員來說,PDFSharp仍然是個不錯的選擇。 但請準備好解決其局限性或用其他工具將其補充以獲得更高級的需求。

授權

PDFSharp採用MIT License發布,可以完全免費使用。 您只需在您的分發中包含原版權聲明並提到授權即可。

5. PDFPig

PDFPig是另一個為.NET開發人員而建的開源庫,允許您從PDF文件中讀取和提取內容。 該程式庫可從PDF檔中提取單個字母的位置和大小。 它檢索影像、讀取PDF註釋和表單、訪問超鏈接及暴露嵌入文件。 您還可以訪問文件元數據並查看內部PDF結構。

該程式庫在基準測試中相較於類似的.NET工具表現良好,且對記憶體的使用非常高效。 它提供了一個免費的商業選擇。 它獲得定期更新並維持積極的GitHub文檔。

該程式庫有明顯的限制,您應該了解。 它不會將HTML或其他格式轉換成PDF。 儘管像docnet或PDFtoImage等單獨的工具可以填補這個空白,但它無法從PDF頁面生成影像。PDF表格是唯讀的; 您不能修改或添加表單值。 對於表格提取,您需要外部工具,如Tabula Sharp或Camelot Sharp。您無法在構建文件時添加或編輯超鏈接。 相比於像IronPDF這樣更全面的程式庫,PDFPig提供的功能較少且文檔也不夠詳盡。

代碼示例

基本文本提取

using System;
using System.Collections.Generic;
using System.Linq;
using UglyToad.PdfPig;
using UglyToad.PdfPig.Content;

public static class Program
{
    public static void Main()
    {
        using (PdfDocument document = PdfDocument.Open(@"C:\path\to\file.pdf"))
        {
            foreach (Page page in document.GetPages())
            {
                // Extract all letters
                IReadOnlyList<Letter> letters = page.Letters;
                string text = string.Join(string.Empty, letters.Select(x => x.Value));

                // Extract words
                IEnumerable<Word> words = page.GetWords();

                // Extract images
                IEnumerable<IPdfImage> images = page.GetImages();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using UglyToad.PdfPig;
using UglyToad.PdfPig.Content;

public static class Program
{
    public static void Main()
    {
        using (PdfDocument document = PdfDocument.Open(@"C:\path\to\file.pdf"))
        {
            foreach (Page page in document.GetPages())
            {
                // Extract all letters
                IReadOnlyList<Letter> letters = page.Letters;
                string text = string.Join(string.Empty, letters.Select(x => x.Value));

                // Extract words
                IEnumerable<Word> words = page.GetWords();

                // Extract images
                IEnumerable<IPdfImage> images = page.GetImages();
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports UglyToad.PdfPig
Imports UglyToad.PdfPig.Content

Public Module Program
    Public Sub Main()
        Using document As PdfDocument = PdfDocument.Open("C:\path\to\file.pdf")
            For Each page As Page In document.GetPages()
                ' Extract all letters
                Dim letters As IReadOnlyList(Of Letter) = page.Letters
                Dim text As String = String.Join(String.Empty, letters.Select(Function(x) x.Value))

                ' Extract words
                Dim words As IEnumerable(Of Word) = page.GetWords()

                ' Extract images
                Dim images As IEnumerable(Of IPdfImage) = page.GetImages()
            Next
        End Using
    End Sub
End Module
$vbLabelText   $csharpLabel

授權

PDFPig採用Apache 2.0 License發布,這只需您在您的分發中包含原版權聲明和授權文字。 除了這個要求,您可以完全自由地使用這個程式庫。

結論

總之,讓我們來比較這些C# PDF程式庫的定價和授權模式。

IronPDF提供適合個人和公司使用的靈活價格方案。對於開發目的,它是免費的,還包括免費試用版。 價格非常合理,起價僅$2,998。 憑藉其全面的功能集、出色的支持及適合上線的穩定性,IronPDF 提供了最值得的價值。

Aspose.PDF採用按需付費模式,授權起價為1679美元,與替代品相比,它顯著更昂貴。 雖然它提供了細粒度控制,但陡峭的學習曲線和高成本可能不適合所有預算。

iTextSuite不在其網站上公布透明的價格。您必須聯繫他們的支持團隊獲取報價,這就意味著價格因案而異。 雖然他們提供AGPL授權免費使用,但這要求您將整個產品開源。

PDFSharpPDFPig在MIT和Apache 2.0許可下被完全免費使用。 然而,與商業選擇相比,它們的功能是有限的。 PDFSharp缺乏HTML到PDF的轉換且對大文件束手無策,而PDFPig主要是只讀的程式庫。

選擇正確的PDF程式庫取決於您的具體需求和預算。 如果您需要基礎操作並擁有技術專業知識,開源選擇非常合適。 然而,對於需要豐富功能的應用程式來說,可靠的支持和全面的文檔,IronPDF脫穎而出,成為功能最全面和成本效益最高的解決方案。