C#建立PDF - 使用IronPDF的完整指南
當大多數人想到PDF(可攜式文件格式)時,他們想到的是一個充滿資訊的文件。 他們是對的,因為目前PDF是最常用的資訊共享文件格式,並已成為標準。 但當程式員查看PDF時,他們不僅僅看到資訊; 他們還分析格式、內容型別及其他技術方面。
在以程式方式建立PDF文件時,保持內容結構是最重要的任務。 這並不是一個像看起來那麼簡單的任務,因為當我們說到內容時,這不僅僅意味著文字,它還包括圖像、圖表、音訊,甚至是影片。 此外,程式化地編輯PDF現在是一個常見的需求。
在人工智慧時代,我們希望完全控制PDF。 有時我們需要因政策問題編輯文字,保護PDF以保障敏感文件的安全,提取資料進行處理,或者動態生成報告。 這些過程有很多用途。 這些是開發者在程式化處理PDF文件時常見的問題:
如何在處理各種媒體作為內容時保持PDF文件的格式化佈局
以正確的順序提取文字,尤其是當有欄位中的文字時
處理有大量頁面的PDF文件時的記憶體限制
表單處理是開發者面臨的主要問題
- 將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即可在專案中使用:
您不需要安裝任何其他程式庫,因為它完全獨立於外部依賴。 當您安裝這個程式庫時,它會自動一次性安裝所有所需的依賴。
IronPDF最重要的功能是它能夠以像素級精度將HTML轉換為PDF。 IronPDF提供多種方法從HTML內容建立PDF文件。 您可以直接將HTML字串、HTML文件或URL轉換為PDF。 它也支持CSS和JavaScript,以確保生成的PDF文件準確反映原始HTML渲染。
除了基本操作,IronPDF還支持PDF表單、所有級別加密和新增數位簽名。 您可以從PDF文件中提取圖像和文字。 您還可以新增文字或HTML頁眉和頁腳,合併和拆分PDF,修改多個文字段落,發現並替換文字。 IronPDF不僅支持從HTML建立PDF,還支持從DOCX、RTF、MD和圖像文件轉換為PDF。 這個程式庫非常輕量級且高效的記憶體管理(基本操作需要少於10MB的記憶體)。 IronPDF跟蹤其在穩定性和性能方面的里程碑,您可以從這裡獲取。
IronPDF提供多層次的支援。 您可以通過即時聊天、建立服務工單或電子郵件與工程師聯繫。 支援團隊全天候提供服務。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")從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編輯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")表單處理
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")如您從上述範例中所見,您只需使用幾行程式碼就能通過IronPDF在PDF文件上執行任何操作。 這非常簡單和直接。 方法名稱易於理解和實施。
授權
IronPDF可以免費用於開發目的,您也可以下載免費試用版。 但對於生產環境,您需要購買IronPDF的授權。 IronPDF的授權模式是靈活的,因為它提供兩種授權型別:
訂閱授權
- 永久授權
訂閱授權每月費用為59美元(每年收費一次),包括1名開發者、1個專案和每年15,000次API調用。 超出配額後的額外API調用每次費用為0.03美元。
永久授權從$2,998開始,並有多種選擇,您可以根據需求選擇。 這種授權的最大好處是一次性付款。 您無需再次為使用IronPDF付款。

2. Aspose.PDF for .NET
Aspose.PDF是一個由Aspose開發的C# PDF程式庫,是Aspose他們.NET程式庫套件的一部分,廣泛用於商業上與PDF相關的任務,如建立複雜報告、敏感文件、自定義PDF文件等。 它是C#中最常用的PDF程式庫之一。 它也支持最新的.NET Framework。
Aspose.PDF不僅可以從HTML內容建立PDF文件,還支持從XML文件中提取資料以實現真實資料,而不是建立靜態文件。 這一功能對於建立複雜報告非常有幫助。 和IronPDF類似,您可以在PDF文件中新增文字、圖像、圖表和許多其他型別的內容。 Aspose.PDF還提供數位簽名嵌入、註釋處理、頁眉頁腳及從PDF文件中提取文字。 您可以從PDF中提取結構化資料。 該程式庫通過使用所述功能很好地處理PDF編輯。
除了Aspose.PDF程式庫的這些優點外,也有多個缺點。 這個程式庫的主要缺點是價格非常高(起價1,679美元),其定價模式也很難理解。 與IronPDF不同的是,您需要分別購買每個過程的模型,如開發和部署。 此外,該程式庫非常耗資源(生成包含400多張圖像的PDF時超過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您可以看到,Aspose.PDF所需的程式碼用來建立新的PDF文件非常複雜。 您必須在程式碼中手動設置每個座標。 必須手動設置每個PDF物件元素的樣式,這非常耗時且效率低下。 然而,它提供了對PDF文件的細粒度控制。
授權
Aspose.PDF有多種授權選擇,但大多是按使用付費的。 授權價格從1,679美元起。與IronPDF授權選擇(起價$2,998)相比非常昂貴。

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從上述例子中可以看出iTextSuite程式碼的複雜性。它增加了構建大應用程式的開發時間和複雜性。
授權
iTextSuite提供兩種授權模式。 一個是商業授權,另一個是AGPL授權。 您可以在AGPL授權下免費在生產中使用iTextSuite,但您也需要開源您的產品。 關於商業授權,沒有在授權頁面上提及價格。 您需請求報價,也可聯絡客服。

4. PDFSharp
PDFSharp是一個C#開源方案,解決開發者在程式化執行PDF操作時面臨的PDF問題。 它支持最新的.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")PDFSharp仍然是需要輕量且免費方案進行基本PDF生成並具有精確位置控制的開發者的穩定選擇。 但也要準備好解決其限制或與其他工具結合使用以滿足更多高級要求。
授權
PDFSharp按MIT License授權發佈,完全免費使用。 您只需包括原始版權聲明並在您的發佈版中提及該授權。
5. PDFPig
PDFPig是另一個為.NET開發者構建的開源程式庫,讓您能夠讀取和提取PDF文件的內容。 該程式庫從PDF文件中提取每個字母的位置和大小。 它檢索圖片、閱讀PDF註釋和表單、存取超連結及顯示嵌入的文件。 您還可以存取文件的元資料並查看內部PDF結構。
與類似.NET工具相比,該程式庫在基準測試中表現良好,並有效地使用記憶體。 以零成本的替代品提供商業選擇。 它定期收到更新並保持活躍的GitHub文件。
該程式庫有明確的限制,您應該知道。 它不會將HTML或其他格式轉換為PDF。 它無法從PDF頁面生成圖像,但像docnet或PDFtoImage之類的工具可以填補這個空白。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授權
PDFPig按Apache 2.0 License授權發佈,此授權只要求您在您的發佈中包含原始版權聲明和授權文字。 除此要求之外,您可以自由地以任何方式使用該程式庫。
結論
綜合來說,讓我們比較一下這些C# PDF程式庫的定價和授權模式。
IronPDF提供靈活的定價方案,適合個人和公司。開發用途免費,並且包含免費試用。 定價非常合理,僅從$2,998開始。 憑藉其全面的功能設置、卓越的支持和生產就緒的穩定性,IronPDF提供了最佳的性價比。
Aspose.PDF按使用支付模式,授權起價為1,679美元,比其他選擇顯著昂貴。 儘管它提供了細緻控制,但陡峭的學習曲線和高成本可能不適合所有預算。
iTextSuite並未在其網站上發布透明的定價。您必須聯係他們的支持團隊以獲取報價,這意味著定價因情況而異。 它們確實提供免費使用的AGPL授權,但這要求您將整個產品開源。
PDFSharp和PDFPig分別按MIT和Apache 2.0授權完全免費。 然而,與商業選擇相比,它們的功能有限。 PDFSharp缺乏HTML到PDF轉換,對大型文件處理困難,且PDFPig主要為只讀程式庫。
選擇合適的PDF程式庫取決於您的具體需求和預算。 如果您需要基本操作並具備技術專長,開源選擇非常好。 然而,對於需要高級功能、可靠支援和全面文件的功能豐富的應用,IronPDF脫穎而出,成為最具成本效益和功能完整的解決方案。
