跳過到頁腳內容
產品比較

從字節數組創建PDF C# iTextSharp(vs IronPDF)

在現代 .NET 應用程式中,建立和管理 PDF 文件是一個常見的需求,無論是生成報告、發票還是數字記錄。 Developers often turn to third-party PDF libraries for this task, and two of the most popular options in the .NET ecosystem are IronPDF and iText 7 (the successor to iTextSharp).

每個函式庫都提供了針對不同使用案例的強大工具集。 但是哪一個最適合在 C# 中將 [位元陣列](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/dd831853(v=vs.120) 生成 PDF? 本文透過比較、程式碼範例和見解將其分解,幫助 .NET 開發人員做出正確的選擇。

無論您是構建企業級應用程式還是小型內部工具,選擇合適的 PDF 函式庫都可以節省開發時間並確保可靠的輸出。 讓我們來看看每個函式庫提供了哪些功能。

PDF 函式庫介紹

PDF 函式庫的用途是什麼?

C# 中的 PDF 函式庫允許開發人員以程式化方式生成、操控和讀取 PDF 文件。 它們滿足了廣泛的使用案例,例如:

  • 匯出報告和發票
  • 從網頁表單生成動態內容
  • 將 HTML 網頁或範本轉換成 PDF
  • 將頁碼、圖表、影像等視覺元素添加到 PDF 文件中
  • 合併或拆分文件
  • 數字簽署 PDF

它們在數據可移植性以及遵循 PDF/A 這樣的標準以用於歸檔或可訪問性要求方面也發揮了重要作用。

iTextSharp 和 IronPDF:頂尖競爭者

在現有的 .NET PDF 函式庫中,iTextSharpIronPDF 已經成為領先的解決方案之一,每個都有其獨特的優勢:

  • iTextSharp 是一個成熟的開源函式庫,基於 Java 的 iText,提供強大的 PDF 控制,但存在高難度學習曲線和許可限制。
  • IronPDF,一個現代的商業函式庫,專注於簡單性、速度和網頁整合,允許將 HTML 和 ASP.NET 視圖直接轉換為 PDF 文件。

為什麼選擇合適的函式庫很重要

選擇兩者不僅僅是個人偏好問題,還影響生產力、維護性、性能,甚至是法律許可的合規性。 需求快速轉變、需要頻繁格式更改或從 HTML 範本渲染 PDF 的專案將從快速開發中受益,而企業級應用程式可能會優先考慮標準合規性和長期可維護性。

功能比較

iText 7 for .NET(iTextSharp 的繼任者)

iText 7iTextSharp 的官方繼任者,具有完全重新設計的架構。 它是一個功能強大、可擴展的函式庫,適合在法律、金融和政府等合規要求高的行業中創建、編輯和驗證 PDF。 iText 7 套件支持 PDF/A、PDF/UA、數位簽名、修訂和表單創建。

雖然它仍是基於 AGPL 許可的開源,但商業許可可用於專有專案。

iText 7 主要功能

  • 現代 API,取代 iTextSharp 的舊結構
  • 模塊化支持:HTML 到 PDF、PDF/A、表單、修訂、數位簽名
  • 適合企業應用的高性能
  • 非常適合 PDF/A、可訪問性、合規性

請注意您需要使用 itext7 進行核心 PDF 操作,並可能單獨包含如 html2pdf 等選項附件。

安裝 (NuGet)

要下載 iText 7 的核心包以生成 PDF:

Install-Package itext7

透過 NuGet Package Manager Console 安裝 iText 7

您還可以透過方案畫面的包管理器安裝 iText 7。 要執行此操作,您首先需要進入工具下拉選單,然後找到“NuGet 包管理器 > 為方案管理 NuGet 包”。

Visual Studio 工具下拉選單

然後,搜索 iText 7,然後點選“安裝”。

iText 7 NuGet 包頁面

程式碼範例:使用 iText 7 從位元陣列創建 PDF 文件

using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.GeneratePdfWithIText7();
        // Save the PDF to a file
        File.WriteAllBytes("output.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] GeneratePdfWithIText7()
    {
        using (var ms = new MemoryStream())
        {
            var writer = new PdfWriter(ms);
            var pdf = new iText.Kernel.Pdf.PdfDocument(writer);
            var doc = new Document(pdf);

            doc.Add(new Paragraph("Hello from iText 7 for .NET!"));

            doc.Close(); // Always close the document to finalize content  
            return ms.ToArray();
        }
    }
}
using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.GeneratePdfWithIText7();
        // Save the PDF to a file
        File.WriteAllBytes("output.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] GeneratePdfWithIText7()
    {
        using (var ms = new MemoryStream())
        {
            var writer = new PdfWriter(ms);
            var pdf = new iText.Kernel.Pdf.PdfDocument(writer);
            var doc = new Document(pdf);

            doc.Add(new Paragraph("Hello from iText 7 for .NET!"));

            doc.Close(); // Always close the document to finalize content  
            return ms.ToArray();
        }
    }
}
Imports System.IO
Imports iText.Kernel.Pdf
Imports iText.Layout
Imports iText.Layout.Element

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfBytes() As Byte = pdfGenerator.GeneratePdfWithIText7()
		' Save the PDF to a file
		File.WriteAllBytes("output.pdf", pdfBytes)
	End Sub
End Class

Friend Class PdfGenerator
	Public Function GeneratePdfWithIText7() As Byte()
		Using ms = New MemoryStream()
			Dim writer = New PdfWriter(ms)
			Dim pdf = New iText.Kernel.Pdf.PdfDocument(writer)
			Dim doc = New Document(pdf)

			doc.Add(New Paragraph("Hello from iText 7 for .NET!"))

			doc.Close() ' Always close the document to finalize content
			Return ms.ToArray()
		End Using
	End Function
End Class
$vbLabelText   $csharpLabel

輸出 PDF 文件

iText 7 PDF 輸出

解釋

  • PdfWriter 將內容寫入到 MemoryStream
  • PdfDocument 管理 PDF 的內部結構。
  • Document 用於添加高級內容(文字、影像、表格)。
  • 在調用 doc.Close() 之後,PDF 內容將被完全寫入並可以作為位元陣列返回。

這個範例展示了相較於 iTextSharp 的 更模塊化和可讀的 API 的 iText 7。然而,它仍然缺乏對 HTML/CSS 的原生渲染支持,除非您包括單獨授權的 pdfhtml。

iText 7 的優缺點

優點:

  • 全面的 PDF 控制\ iText 7 提供對 PDF 元素的完全控制,例如表格、表單和數位簽名。 這使得它非常適合要求特定 PDF 標準(如 PDF/A 或 PDF/UA)的合規性重應用。

  • 模塊化和可擴展\ iText 7 是模塊化的,這意味著您可以僅安裝所需的特定模組(例如,將 HTML 轉換為 PDF 的 pdfhtml)。 這樣就可以在不使用所有功能的情況下實現更輕量的實施。

  • 支持複合 PDF 標準\ iText 7 支持 ISO 標準,如 PDF/A(存檔)、PDF/UA(可訪問性)和 PDF/X(打印),使其適合專業和法律環境,這需要重要的合規性。

  • 豐富的文檔和支持\ iText 7 擁有完整的文檔和大型社區。 公司還提供專業支持,確保開發人員在需要時可以獲得協助。

  • 免費版本可用 (AGPL)\ 開發人員可以在 AGPL 許可的條件下免費使用 iText 7,這對於開源專案或個人使用來說是理想的。

缺點:

  • AGPL 商業用途許可\ 雖然 iText 7 提供免費版本,但商業用戶必須遵守 AGPL 許可,這要求發布任何使用 iText 7 的軟體的源碼,或者支付商業許可費。

  • 學習曲線陡峭\ iText 7 的 API 更複雜且功能豐富,可能導致比更簡單函式庫如 IronPDF 的學習曲線更陡峭。 開發人員需要熟悉其低級文檔結構和模塊化架構。

  • 對簡單任務而言過於繁重\ iText 7 在基本的 PDF 任務上可能會顯得笨重,如簡單的文件創建或基本的 HTML 到 PDF 轉換,特別是與簡化流程的函式庫如 IronPDF 相比。

  • 需要外部模組進行 HTML 到 PDF 轉換\ iText 7 中的 HTML 到 PDF 轉換僅通過額外的 pdfhtml 模組提供,需要單獨安裝,且未必能如 IronPDF 一樣流暢地處理現代網頁內容。

IronPDF for .NET:一個強大的 PDF 函式庫

IronPDF 是一個高階的 .NET 函式庫,設計用來簡化 PDF 文件的生成,專注於開發人員的生產力。 它特別有效於渲染 HTML 內容和樣式,使其非常適合現代網頁到 PDF 的工作流。

關鍵功能:

  • 從位元陣列創建 PDF 文件,並處理 PDF 文件而不需要安裝 Adobe Reader
  • 使用完整的 Chromium 引擎直接渲染 HTML 到 PDF,從 HTML 內容生成 PDF 文件
  • 支持 MVC 視圖、Razor 頁面和本地/遠程 URL
  • 開箱即用支持影像文件、JavaScript、CSS 和響應式佈局
  • 易於使用的語法和最小的設置要求
  • 永久授權且無 AGPL 限制

安裝 IronPDF

IronPDF 同樣可以通過 NuGet 安裝,通過在 NuGet Package Manager Console 中運行以下命令:

Install-Package IronPdf

通過 Package Manager Console 安裝 IronPDF

或者,您可以在方案畫面的 NuGet 包管理器中安裝它。 為此,導覽至“工具 > NuGet 包管理器 > 為方案管理 NuGet 包”。

Visual Studio 工具下拉選單

然後,搜索 IronPDF,然後點選“安裝”。

IronPDF NuGet 包管理器畫面

安裝後,您可以在幾秒內開始將完整的 HTML 網頁渲染為 PDF 文件,無需額外的模組。 它支持現代的 CSS、JavaScript,甚至是互動的網頁內容,無需額外的設定。

程式碼範例:使用 IronPDF 從位元陣列創建 PDF 文件

using IronPdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.GeneratePdfWithIronPdf();
        // Save the PDF to a file
        File.WriteAllBytes("output.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] GeneratePdfWithIronPdf()
    {
        var renderer = new ChromePdfRenderer();
        var pdfDoc = renderer.RenderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
        return pdfDoc.BinaryData;
    }
}
using IronPdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.GeneratePdfWithIronPdf();
        // Save the PDF to a file
        File.WriteAllBytes("output.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] GeneratePdfWithIronPdf()
    {
        var renderer = new ChromePdfRenderer();
        var pdfDoc = renderer.RenderHtmlAsPdf("<h1>Hello from IronPDF!</h1>");
        return pdfDoc.BinaryData;
    }
}
Imports IronPdf
Imports System.IO

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfBytes() As Byte = pdfGenerator.GeneratePdfWithIronPdf()
		' Save the PDF to a file
		File.WriteAllBytes("output.pdf", pdfBytes)
	End Sub
End Class

Friend Class PdfGenerator
	Public Function GeneratePdfWithIronPdf() As Byte()
		Dim renderer = New ChromePdfRenderer()
		Dim pdfDoc = renderer.RenderHtmlAsPdf("<h1>Hello from IronPDF!</h1>")
		Return pdfDoc.BinaryData
	End Function
End Class
$vbLabelText   $csharpLabel

輸出 PDF 文件

IronPDF 輸出

解釋

  • using IronPdf 語句匯入 IronPDF 函式庫,以訪問所有 PDF 相關類。
  • var renderer = new ChromePdfRenderer() 創建一個新的 HTML 到 PDF 渲染器,使用無牌的 Chromium 引擎。
  • renderer.RenderHtmlAsPdf(...) 將給定的 HTML 字串轉換為 PDF 文件。 您也可以傳入文件路徑或 URLs。
  • pdfDoc.BinaryData 返回最終的 PDF 作為一個位元陣列,可以用於儲存、串流或資料庫存儲。

IronPDF 的優缺點

優點:

  • 無痛的 HTML 到 PDF 渲染\ 直接將 HTML、CSS 和 JavaScript 內容渲染到具有完全樣式的 PDFs 中,包括 Bootstrap 和自訂字體,無需複雜的佈局代碼或額外的模組。

  • 快速啟動和直觀的 API\ 在幾行代碼中創建完全樣式化的 PDF 文件,具有乾淨的語法,並兼容 .NET Core 和 .NET Framework。

  • 對網頁技術的全面支持\ IronPDF 支持 JavaScript、現代 CSS、SVG 和媒體查詢,大多數函式庫如無使用無牌瀏覽器如 Chromium(IronPDF 在內部使用)則很難支持這些技術。

  • 內建影像和資產處理\ 輕鬆加入影像、本地文件,甚至從遠程 URL 獲取資源,無需額外設定。

  • 永久授權且無 AGPL\ 與 iText 7 不同,IronPDF 提供靈活的商業許可,無需遵循開源 AGPL 的限制。

  • 對 MVC 和 Razor 視圖的支持優異\ 無縫地將 ASP.NET 應用程式中的 .cshtml Razor 視圖轉換為可打印的 PDFs。

缺點:

  • 商業使用需授權\ 雖然有免費試用版,但 IronPDF 並非開源軟體。 預算緊湊的專案可能需要評估許可成本。

  • 初始包尺寸較大\ 由於其捆綁了一個無牌的 Chromium 引擎,NuGet 包比一些替代方案更大。

實用程式碼範例比較

本節中的以下程式碼範例將展示這些函式庫的實際應用,我們將使用相同的任務來比較 IronPDFiText 7。 兩個函式庫將在相同的場景下被測試:從 URL 生成 PDF,將影像渲染為 PDF,以及將樣式化的 HTML 轉換為 PDF,同時使用位元陣列來處理 PDF 內容。 這將允許開發人員評估每個函式庫如何處理這些常見的使用案例。

1. 使用位元陣列從 URL 生成簡單的 PDF

IronPDF

using IronPdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.GeneratePdfFromUrlWithIronPdf();

        // Save the PDF to a file
        File.WriteAllBytes("ironpdf-from-url.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] GeneratePdfFromUrlWithIronPdf()
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.WaitForJavaScript(5000);
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;

        var pdf = renderer.RenderUrlAsPdf("https://www.apple.com");
        return pdf.BinaryData;
    }
}
using IronPdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.GeneratePdfFromUrlWithIronPdf();

        // Save the PDF to a file
        File.WriteAllBytes("ironpdf-from-url.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] GeneratePdfFromUrlWithIronPdf()
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.WaitForJavaScript(5000);
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;

        var pdf = renderer.RenderUrlAsPdf("https://www.apple.com");
        return pdf.BinaryData;
    }
}
Imports IronPdf
Imports System.IO

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfBytes() As Byte = pdfGenerator.GeneratePdfFromUrlWithIronPdf()

		' Save the PDF to a file
		File.WriteAllBytes("ironpdf-from-url.pdf", pdfBytes)
	End Sub
End Class

Friend Class PdfGenerator
	Public Function GeneratePdfFromUrlWithIronPdf() As Byte()
		Dim renderer = New ChromePdfRenderer()
		renderer.RenderingOptions.EnableJavaScript = True
		renderer.RenderingOptions.WaitForJavaScript(5000)
		renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print

		Dim pdf = renderer.RenderUrlAsPdf("https://www.apple.com")
		Return pdf.BinaryData
	End Function
End Class
$vbLabelText   $csharpLabel

輸出 PDF

URL 到 PDF IronPDF 輸出

IronPDF 使用無牌 Chromium 引擎進行網頁的 像素級渲染,具有完整的 JavaScript 和 CSS 支持。

iText 7

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using System.Net.Http;
using System.Threading.Tasks;
using iText.Html2pdf;
using System.IO;

class Program
{
    static async Task Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = await pdfGenerator.GeneratePdfFromUrlWithIText7Async();

        // Save the PDF to a file
        File.WriteAllBytes("itext7-from-url.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public async Task<byte[]> GeneratePdfFromUrlWithIText7Async()
    {
        using var httpClient = new HttpClient();
        string html = await httpClient.GetStringAsync("https://www.apple.com");

        using var stream = new MemoryStream();
        HtmlConverter.ConvertToPdf(html, stream);
        return stream.ToArray();
    }
}
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using System.Net.Http;
using System.Threading.Tasks;
using iText.Html2pdf;
using System.IO;

class Program
{
    static async Task Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = await pdfGenerator.GeneratePdfFromUrlWithIText7Async();

        // Save the PDF to a file
        File.WriteAllBytes("itext7-from-url.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public async Task<byte[]> GeneratePdfFromUrlWithIText7Async()
    {
        using var httpClient = new HttpClient();
        string html = await httpClient.GetStringAsync("https://www.apple.com");

        using var stream = new MemoryStream();
        HtmlConverter.ConvertToPdf(html, stream);
        return stream.ToArray();
    }
}
Imports iText.Kernel.Pdf
Imports iText.Layout
Imports iText.Layout.Element
Imports System.Net.Http
Imports System.Threading.Tasks
Imports iText.Html2pdf
Imports System.IO

Friend Class Program
	Shared Async Function Main(ByVal args() As String) As Task
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfBytes() As Byte = Await pdfGenerator.GeneratePdfFromUrlWithIText7Async()

		' Save the PDF to a file
		File.WriteAllBytes("itext7-from-url.pdf", pdfBytes)
	End Function
End Class

Friend Class PdfGenerator
	Public Async Function GeneratePdfFromUrlWithIText7Async() As Task(Of Byte())
		Dim httpClient As New HttpClient()
		Dim html As String = Await httpClient.GetStringAsync("https://www.apple.com")

		Dim stream = New MemoryStream()
		HtmlConverter.ConvertToPdf(html, stream)
		Return stream.ToArray()
	End Function
End Class
$vbLabelText   $csharpLabel

輸出

iText 7 URL 到 PDF 輸出

iText 7 使用 HttpClient 擷取原始 HTML 並使用 HtmlConverter 渲染,但 不支持 JavaScript 執行(根據 iText 的官方文檔,建議使用 Selenium 或類似的瀏覽器自動化工具進行 JavaScript 預處理),且 CSS 樣式有限。 雖然 iText7 在版本 7.1.15(2021 年)中添加了部分 flexbox 支持,但許多 CSS3 屬性仍不受支持,特別是對於複雜的現代佈局。

2. 使用位元陣列從影像創建新的 PDF 文件

IronPDF

using IronPdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.CreatePdfWithImage();

        // Save the PDF to a file
        File.WriteAllBytes("ironpdf-with-image.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] CreatePdfWithImage()
    {
        var pdf = ImageToPdfConverter.ImageToPdf("example.png");
        return pdf.BinaryData;
    }
}
using IronPdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.CreatePdfWithImage();

        // Save the PDF to a file
        File.WriteAllBytes("ironpdf-with-image.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] CreatePdfWithImage()
    {
        var pdf = ImageToPdfConverter.ImageToPdf("example.png");
        return pdf.BinaryData;
    }
}
Imports IronPdf
Imports System.IO

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfBytes() As Byte = pdfGenerator.CreatePdfWithImage()

		' Save the PDF to a file
		File.WriteAllBytes("ironpdf-with-image.pdf", pdfBytes)
	End Sub
End Class

Friend Class PdfGenerator
	Public Function CreatePdfWithImage() As Byte()
		Dim pdf = ImageToPdfConverter.ImageToPdf("example.png")
		Return pdf.BinaryData
	End Function
End Class
$vbLabelText   $csharpLabel

輸出

IronPDF 影像到 PDF 輸出

使用 IronPDF 的 ImageToPdfConverter 工具,輕鬆生成影像到 PDF。 使用此工具,您可以輕鬆地從影像(如 PNG 文件或 JPGs)創建 PDF 文件。

iText 7

using iText.Kernel.Pdf;
using iText.Layout;
using iText.IO.Image;
using iText.Layout.Element;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.CreatePdfWithImage();

        // Save the PDF to a file
        File.WriteAllBytes("iText-with-image.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] CreatePdfWithImage()
    {
        using var ms = new MemoryStream();
        using var writer = new PdfWriter(ms);
        using var pdfDoc = new iText.Kernel.Pdf.PdfDocument(writer);
        var document = new Document(pdfDoc);

        var img = new Image(ImageDataFactory.Create("https://itextpdf.com/sites/default/files/2018-11/iText%207%20Product%20software%20-%20webimages_509x339px_V2_iText%207%20Core.png"));
        document.Add(img);
        document.Close();

        return ms.ToArray();
    }
}
using iText.Kernel.Pdf;
using iText.Layout;
using iText.IO.Image;
using iText.Layout.Element;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.CreatePdfWithImage();

        // Save the PDF to a file
        File.WriteAllBytes("iText-with-image.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] CreatePdfWithImage()
    {
        using var ms = new MemoryStream();
        using var writer = new PdfWriter(ms);
        using var pdfDoc = new iText.Kernel.Pdf.PdfDocument(writer);
        var document = new Document(pdfDoc);

        var img = new Image(ImageDataFactory.Create("https://itextpdf.com/sites/default/files/2018-11/iText%207%20Product%20software%20-%20webimages_509x339px_V2_iText%207%20Core.png"));
        document.Add(img);
        document.Close();

        return ms.ToArray();
    }
}
Imports iText.Kernel.Pdf
Imports iText.Layout
Imports iText.IO.Image
Imports iText.Layout.Element
Imports System.IO

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfBytes() As Byte = pdfGenerator.CreatePdfWithImage()

		' Save the PDF to a file
		File.WriteAllBytes("iText-with-image.pdf", pdfBytes)
	End Sub
End Class

Friend Class PdfGenerator
	Public Function CreatePdfWithImage() As Byte()
		Dim ms = New MemoryStream()
		Dim writer = New PdfWriter(ms)
		Dim pdfDoc = New iText.Kernel.Pdf.PdfDocument(writer)
		Dim document As New Document(pdfDoc)

		Dim img = New Image(ImageDataFactory.Create("https://itextpdf.com/sites/default/files/2018-11/iText%207%20Product%20software%20-%20webimages_509x339px_V2_iText%207%20Core.png"))
		document.Add(img)
		document.Close()

		Return ms.ToArray()
	End Function
End Class
$vbLabelText   $csharpLabel

輸出

iText 7 PDF 含影像輸出

手動創建文檔佈局並使用 ImageDataFactory 顯式插入影像。

3. 使用位元陣列將樣式化的 HTML 內容轉換為 PDF

IronPDF

using IronPdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.CreateStyledPdf();

        // Save the PDF to a file
        File.WriteAllBytes("ironpdf-styled-html.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] CreateStyledPdf()
    {
        string html = @"
        <html>
            <head>
                <style>
                    body { 
                        background-color: #f0f0f0; 
                        margin: 20px; 
                        padding: 20px; 
                        border-radius: 5px; 
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    }
                    h1 { 
                        color: navy;
                        font-size: 32px;   
                        text-align: center;
                       }
                    p { 
                        font-size: 16px; 
                        font-weight: bold;
                      }
                </style>
            </head>
            <body>
                <h1>Welcome to IronPDF</h1>
                <p>This is a simple PDF document generated using IronPDF.</p>
            </body>
        </html>";

        var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(html);
        return pdf.BinaryData;
    }
}
using IronPdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.CreateStyledPdf();

        // Save the PDF to a file
        File.WriteAllBytes("ironpdf-styled-html.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] CreateStyledPdf()
    {
        string html = @"
        <html>
            <head>
                <style>
                    body { 
                        background-color: #f0f0f0; 
                        margin: 20px; 
                        padding: 20px; 
                        border-radius: 5px; 
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    }
                    h1 { 
                        color: navy;
                        font-size: 32px;   
                        text-align: center;
                       }
                    p { 
                        font-size: 16px; 
                        font-weight: bold;
                      }
                </style>
            </head>
            <body>
                <h1>Welcome to IronPDF</h1>
                <p>This is a simple PDF document generated using IronPDF.</p>
            </body>
        </html>";

        var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(html);
        return pdf.BinaryData;
    }
}
Imports IronPdf
Imports System.IO

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfBytes() As Byte = pdfGenerator.CreateStyledPdf()

		' Save the PDF to a file
		File.WriteAllBytes("ironpdf-styled-html.pdf", pdfBytes)
	End Sub
End Class

Friend Class PdfGenerator
	Public Function CreateStyledPdf() As Byte()
		Dim html As String = "
        <html>
            <head>
                <style>
                    body { 
                        background-color: #f0f0f0; 
                        margin: 20px; 
                        padding: 20px; 
                        border-radius: 5px; 
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    }
                    h1 { 
                        color: navy;
                        font-size: 32px;   
                        text-align: center;
                       }
                    p { 
                        font-size: 16px; 
                        font-weight: bold;
                      }
                </style>
            </head>
            <body>
                <h1>Welcome to IronPDF</h1>
                <p>This is a simple PDF document generated using IronPDF.</p>
            </body>
        </html>"

		Dim pdf = (New ChromePdfRenderer()).RenderHtmlAsPdf(html)
		Return pdf.BinaryData
	End Function
End Class
$vbLabelText   $csharpLabel

輸出

IronPDF 樣式化的 HTML 到 PDF 輸出

IronPDF 完全支持標籤中的 CSS 或外部樣式表,多虧了其 Chromium 引擎。

iText 7 + pdfHTML

using iText.Kernel.Pdf;
using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.CreateStyledPdf();

        // Save the new document to the specified file location
        File.WriteAllBytes("iText-styled-html.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] CreateStyledPdf()
    {
        string html = @"
        <html>
            <head>
                <style>
                    body { 
                        background-color: #f0f0f0; 
                        margin: 20px; 
                        padding: 20px; 
                        border-radius: 5px; 
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    }
                    h1 { 
                        color: navy;
                        font-size: 32px;   
                        text-align: center;
                       }
                    p { 
                        font-size: 16px; 
                        font-weight: bold;
                      }
                </style>
            </head>
            <body>
                <h1>Welcome to iText 7</h1>
                <p>This is a simple PDF document generated using iText 7 and pdfHTML.</p>
            </body>
        </html>";

        using var ms = new MemoryStream();
        ConverterProperties properties = new ConverterProperties();
        HtmlConverter.ConvertToPdf(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)), ms, properties);
        return ms.ToArray();
    }
}
using iText.Kernel.Pdf;
using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var pdfGenerator = new PdfGenerator();
        byte[] pdfBytes = pdfGenerator.CreateStyledPdf();

        // Save the new document to the specified file location
        File.WriteAllBytes("iText-styled-html.pdf", pdfBytes);
    }
}

class PdfGenerator
{
    public byte[] CreateStyledPdf()
    {
        string html = @"
        <html>
            <head>
                <style>
                    body { 
                        background-color: #f0f0f0; 
                        margin: 20px; 
                        padding: 20px; 
                        border-radius: 5px; 
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    }
                    h1 { 
                        color: navy;
                        font-size: 32px;   
                        text-align: center;
                       }
                    p { 
                        font-size: 16px; 
                        font-weight: bold;
                      }
                </style>
            </head>
            <body>
                <h1>Welcome to iText 7</h1>
                <p>This is a simple PDF document generated using iText 7 and pdfHTML.</p>
            </body>
        </html>";

        using var ms = new MemoryStream();
        ConverterProperties properties = new ConverterProperties();
        HtmlConverter.ConvertToPdf(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)), ms, properties);
        return ms.ToArray();
    }
}
Imports iText.Kernel.Pdf
Imports iText.Html2pdf
Imports System.IO

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfGenerator As New PdfGenerator()
		Dim pdfBytes() As Byte = pdfGenerator.CreateStyledPdf()

		' Save the new document to the specified file location
		File.WriteAllBytes("iText-styled-html.pdf", pdfBytes)
	End Sub
End Class

Friend Class PdfGenerator
	Public Function CreateStyledPdf() As Byte()
		Dim html As String = "
        <html>
            <head>
                <style>
                    body { 
                        background-color: #f0f0f0; 
                        margin: 20px; 
                        padding: 20px; 
                        border-radius: 5px; 
                        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                    }
                    h1 { 
                        color: navy;
                        font-size: 32px;   
                        text-align: center;
                       }
                    p { 
                        font-size: 16px; 
                        font-weight: bold;
                      }
                </style>
            </head>
            <body>
                <h1>Welcome to iText 7</h1>
                <p>This is a simple PDF document generated using iText 7 and pdfHTML.</p>
            </body>
        </html>"

		Dim ms = New MemoryStream()
		Dim properties As New ConverterProperties()
		HtmlConverter.ConvertToPdf(New MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)), ms, properties)
		Return ms.ToArray()
	End Function
End Class
$vbLabelText   $csharpLabel

輸出

iText 7 樣式化的 HTML 到 PDF 輸出

需要安裝付費附加的 pdfHTML 才能處理 HTML 轉換任務。

比較總結

功能 IronPDF iText 7 (含 pdfHTML)
將 URL 渲染為 PDF 完整的 Chromium 渲染 擷取 HTML,無本地 JS 支持
添加影像 通過 HTML 或專用影像壓印工具嵌入 手動影像工廠
渲染樣式化的 HTML 完全支持 CSS 只有通過 pdfHTML 支持 CSS
返回位元陣列
設置複雜度 簡單 中等(手動佈局)
輸出質量 像素級 良好但靜態

結論:您應該選擇哪個 .NET 函式庫?

Choosing between IronPDF and iText 7 depends on your project’s needs — but when it comes to developer experience, ease of use, and modern rendering accuracy, IronPDF clearly stands out.

If you're working with dynamic HTML content, web rendering, or need to create PDF files from URLs with full JavaScript and CSS support, IronPDF's Chromium-based engine delivers unmatched fidelity. 它直觀的 API 和快速設置使其非常適合快速開發和真實的生產使用 —— 特別是在處理位元陣列、文件流或基於網頁的 PDF 生成時。

另一方面,iText 7 是一個強大且備受尊敬的函式庫,具有更傳統的、佈局驅動的方法。 它提供了對文檔結構的強大控制,非常適合需要細粒度操作的開發人員,但它的學習曲線更陡,缺乏現代 HTML 渲染的能力。

底線是:

  • 想要來自現代網頁內容、樣式化的 HTML 或快速原型設計的 像素級 輸出? 選擇 IronPDF。
  • 需要低級 PDF 創建工具和精細的控制? iText 7 可能是合適的選擇。

準備好開始使用 IronPDF 嗎?\ 下載免費試用版,看看用 C# 創建專業的、基於位元陣列的 PDF 是多麼簡單,只需幾行代碼。

請注意iText 7 是其各自擁有者的註冊商標。 本網站與 iText 7 無關,未受其認可或贊助。所有產品名稱、標誌和品牌均為其各自擁有者的財產。 比較僅供信息參考,並反映撰寫時公開可用的信息。

常見問題解答

如何在 C# 中將 byte 陣列轉換為 PDF?

您可以使用 IronPDF 在 C# 中將 byte 陣列轉換為 PDF。只需使用 `PdfDocument.FromBytes` 方法將 byte 陣列載入到 IronPDF 文件中,該方法將解析數據並生成 PDF 文件。

使用 IronPDF 進行 HTML 至 PDF 轉換的好處是什麼?

IronPDF 在將 HTML 轉換為 PDF 上表現出色,因為它使用無頭 Chromium 引擎,支持現代 CSS 和 JavaScript。這使得它非常適合將動態網頁內容轉換為像素完美的 PDF 文件。

使用 IronPDF 比使用 iText 7 來生成 PDF 的主要優勢是什麼?

IronPDF 提供了一個更簡單的 API 和更快捷的設置,適用於需要將 HTML 轉換為 PDF 的項目,完全支持 CSS 和 JavaScript。它尤其適合需要快速開發和網頁內容整合的應用程序。

iText 7 如何處理 PDF 合規性?

iText 7 專為合規要求高的行業設計,支持 PDF/A、PDF/UA 和 PDF/X 等標準。它提供了對 PDF 創建的強大控制,適合合規性至關重要的應用程序。

在 .NET 項目中安裝 IronPDF 的過程是什麼?

要安裝 IronPDF,您可以使用 Visual Studio 中的 NuGet 套件管理器。在 Package Manager Console 中運行命令 `Install-Package IronPdf` 以將其添加到您的項目中。

IronPDF 可以從 ASP.NET 視圖創建 PDF 嗎?

是的,IronPDF 可以直接將 ASP.NET 視圖呈現為 PDF 文件。此功能使開發人員可以輕鬆地將具有複雜佈局和樣式的網頁轉換為 PDF。

哪些類型的應用最能受益於使用 IronPDF?

需要將動態網頁內容(如報告和發票)轉換為 PDF 的應用程序最有利於使用 IronPDF。其快速設置和網絡技術支持使其非常適合需要頻繁更新和現代設計的項目。

iText 7 的模組化架構如何影響其使用?

iText 7 的模組化架構允許根據需要添加特定的 PDF 功能,例如 HTML 轉換或數字簽名。這提供了靈活性,但每個模組可能需要額外的學習和安裝。

IronPDF 和 iText 7 之間的授權差異是什麼?

IronPDF 提供適合商業應用的永久授權,無 AGPL 限制。相比之下,iText 7 在開源項目中可用於 AGPL 授權,商業用途需付費授權。

Curtis Chau
技術作家

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

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