跳過到頁腳內容
產品比較

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

在現代的 .NET 應用程式中,不論是產生報表、發票或數位記錄,建立和管理 PDF 檔案都是常見的需求。 開發人員通常會求助第三方 PDF 函式庫來完成這項任務,而在 .NET 生態系統中最受歡迎的兩個選項是 IronPDFiText 7(iTextSharp 的繼承者)。

每個函式庫都針對不同的使用情況提供強大的工具集。 但是哪一個最適合從 C# 中的 byte array 產生 PDF 呢? 本文將透過比較、程式碼範例和深入的分析,協助 .NET 開發人員做出正確的選擇。

無論您是在建立企業級應用程式或小型內部工具,選擇正確的 PDF 函式庫都能節省您的開發時間,並確保穩健的輸出。 讓我們來探討每個函式庫所提供的功能。

PDF 程式庫簡介

PDF 函式庫有何用途?

C# 中的 PDF 函式庫可讓開發人員以程式化的方式產生、處理及讀取 PDF 檔案。 這些工具有多種用途,例如:.NET、Java、Python 或 Node js:

  • 匯出報告和發票
  • 從網頁表單產生動態內容
  • 將 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 套件管理員控制台安裝 iText 7

您也可以透過 Package Manager for Solution 螢幕安裝 iText 7。 若要執行這項工作,您首先需要前往"工具"下拉式功能表,然後尋找"NuGet 套件管理員 > 管理解決方案的 NuGet 套件"。

Visual Studio 的工具下拉選單

然後,只要搜尋 iText 7,然後按一下"安裝"即可。

iText 7 NuGet 套件頁面

程式碼範例:使用 iText 7 從 Byte Array 建立 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 Output

說明

  • PdfWriter 將內容寫入 MemoryStream 中。
  • PdfDocument 管理 PDF 的內部結構。
  • Document 用來新增高階內容 (文字、圖片、表格)。
  • 在呼叫 doc.Close() 之後,PDF 內容已完全寫好,並準備以位元組陣列的形式傳回。

本範例展示 iText 7 與 iTextSharp 相比,更具模組化與可讀性的 API。然而,它仍然缺乏渲染 HTML/CSS 的本機支援,除非您包含 pdfhtml(需另外取得授權)。

iText 7 的優缺點

Pros:

  • 全面的 PDF 控制/strong iText 7 可完全控制 PDF 元素,例如表格、表單和數位簽名。 這使得它非常適合需要特定 PDF 標準 (例如 PDF/A 或 PDF/UA)、合規性較高的應用程式。

  • Modular and Scalable(模組化與可擴充性 iText 7 是模組化的,這意味著您可以只安裝所需的特定模組 (例如,pdfhtml 用於 HTML 到 PDF 的轉換)。 如果您並非使用所有功能,這可讓實作更加輕量。

  • Supports Complex PDF Standards(支援複雜的 PDF 標準 iText 7 支援 ISO 標準,例如 PDF/A(歸檔)、PDF/UA(可存取性)和 PDF/X(列印),因此適用於合規性極為重要的專業和法律環境。

  • 豐富的文件與支援\ iText 7 具有全面的說明文件和龐大的社群。 本公司也提供專業支援,確保開發人員在需要時能獲得協助。

  • 免費版本 (AGPL)\ 開發人員可在 AGPL 授權下免費使用 iText 7,非常適合開放原始碼專案或個人使用。

Cons:

  • 適用於商業用途的 AGPL 授權條款\ 雖然 iText 7 提供免費版本,但商業使用者必須遵守 AGPL 授權,這需要釋出任何使用 iText 7 的軟體的原始碼,或支付商業授權。

  • 陡峭的學習曲線/strong iText 7 的 API 較為複雜且功能豐富,相較於 IronPDF 等較簡單的函式庫,可能會造成較陡峭的學習曲線。 開發人員需要熟悉其低階文件結構和基於模組的架構。

  • Heavyweight for Simple Tasks (簡單任務的重量級工具 iText 7 對於基本的 PDF 工作,例如簡單的文件建立或基本的 HTML 至 PDF 轉換,可能會覺得很麻煩,尤其是與 IronPDF 之類的函式庫比較時,這些函式庫可以簡化流程。

  • Requires External Modules for HTML to PDF\ iText 7 中的 HTML 至 PDF 轉換功能僅可透過附加的 pdfhtml 模組實現,該模組需要單獨安裝,且可能無法像 IronPDF 一樣無縫處理現代網路內容。

IronPDF for .NET:功能強大的 PDF 函式庫

IronPDF for .NET 是一個高階 .NET 函式庫,專為簡化 PDF 文件的產生而設計,著重於開發人員的生產力。 它對於呈現 HTML 內容和樣式特別有效,是現代 Web-to-PDF 工作流程的理想選擇。

主要功能:

  • 從位元組陣列建立 PDF 檔案,並在不需安裝 Adobe Reader 的情況下處理 PDF 文件
  • 使用完整的 Chromium 引擎將 HTML 直接渲染為 PDF,從 HTML 內容建立 PDF 文件
  • 可與 MVC 視圖、Razor 頁面及本機/遠端 URL 搭配使用
  • 支援開箱即用的影像檔案、JavaScript、CSS 及回應式版面設計
  • 易於使用的語法和最少的設定需求
  • 永久授權且無 AGPL 約束

安裝 IronPDF。

IronPdf 也可以透過 NuGet 安裝,只要在 NuGet 套件管理員控制台執行下列指令即可:

Install-Package IronPdf

透過套件管理員控制台安裝 IronPdf

另外,您也可以透過 NuGet 套件管理程式為 Solution screen 安裝。 為此,請導航至"工具 > NuGet 套件管理員 > 管理解決方案的 NuGet 套件"。

Tools dropdown menu in Visual Studio

然後,搜尋 IronPdf,並點選"安裝"。

IronPDF NuGet 包管理器畫面

安裝之後,您就可以在幾秒鐘內開始將完整的 HTML 頁面繪製成 PDF - 不需要額外的模組。 它支援現代的 CSS、JavaScript,甚至是互動式網頁內容,無須額外設定。

程式碼範例:使用 IronPDF 從 Byte Array 建立 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 Output

說明

  • using IronPdf 語句導入 IronPDF 函式庫,以存取所有 PDF 相關的類別。
  • var renderer = new ChromePdfRenderer() 創建一個由無頭 Chromium 引擎驅動的新 HTML-to-PDF 渲染器。
  • renderer.RenderHtmlAsPdf(...)將給定的 HTML 字串轉換成 PDF 文件。 您也可以傳入檔案路徑或 URL。
  • pdfDoc.BinaryData將最終的 PDF 傳回為一個位元組陣列,準備好儲存、串流或資料庫儲存。

IronPDF。 的優缺點

Pros:

  • Effortless HTML to PDF Rendering(輕鬆地將 HTML 渲染成 PDF 直接將 HTML、CSS 和 JavaScript 內容渲染為 PDF,並提供完整的樣式,包括 Bootstrap 和自訂字型 - 不需要複雜的排版程式碼或額外的模組。

  • Quick Start & Intuitive API(快速上手和直觀的 API 僅需幾行程式碼即可建立完全風格化的 PDF 檔案,語法簡潔,並與 .NET Core 和 .NET Framework 完全相容。

  • 對網路技術的全面支援/strong IronPDF 支援 JavaScript、現代 CSS、SVGs 和媒體查詢 - 這是大多數軟體函式庫難以做到的,除非他們使用像 Chromium 之類的無頭瀏覽器(IronPDF 內部也是這麼做)。

  • Built-in Image & Asset Handling(內建影像與資產處理 輕鬆包含圖片、本機檔案,甚至從遠端 URL 擷取資產,無須額外設定。

  • 永久授權與無 AGPL\ 與 iText 7 不同的是,IronPDF 提供彈性的商業授權,不受開放原始碼 AGPL 義務的限制。

  • Excellent for MVC & Razor Views\ 將 ASP.NET 應用程式中的 .cshtml Razor View 無縫轉換為可列印的 PDF。

Cons:

  • Commercial Use Requires License\ 雖然有免費試用版,但 IronPdf 並非開放原始碼。 預算緊縮的專案可能需要評估授權成本。

  • Larger Initial Package Size(較大的初始套件尺寸 由於捆綁了無頭 Chromium 引擎,NuGet 套件比某些替代方案更重。

實用程式碼範例比較

本節中的下列程式碼範例展示了這些函式庫的實作,其間我們將比較 IronPDFiText 7 使用相同的任務。 這兩個函式庫都將通過相同的情境:從 URL 產生 PDF、將圖片渲染為 PDF,以及將 HTML 風格轉換為 PDF,同時使用位元組陣列處理我們的 PDF 內容。 這可讓開發人員評估每個函式庫如何處理這些常見的使用個案。

1.使用 Byte Array 從 URL 產生簡單的 PDF2.

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 to PDF IronPDF output

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

Output

iText 7 URL 至 PDF 輸出

iText 7 使用 HttpClient 取得原始 HTML,並使用 HtmlConverter 渲染 HTML,但它不支援 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

Output

將 IronPDF 影像轉換成 PDF 輸出

使用 IronPDF 的 ImageToPdfConverter 工具,輕鬆將圖像轉換為 PDF。 有了它,您可以輕鬆地從 PNG 檔案或 JPG 等影像建立 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

Output

iText 7 PDF with image output

使用 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

Output

IronPdf 風格的 HTML 至 PDF 輸出

得益於其 Chromium 引擎,IronPdf 完全支援標籤或外部樣式表中的 CSS。

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

Output

iText 7 風格的 HTML 至 PDF 輸出

需要安裝 pdfHTML 付費附加元件,才能處理 HTML 轉換工作。

比較摘要

Feature IronPDF iText 7 (含 pdfHTML)
將 URL 渲染成 PDF 完整的 Chromium 渲染 擷取 HTML,不支援原生 JS
Add Image 透過 HTML 或其專用的圖片戳記工具嵌入 手動影像工廠
渲染樣式化的 HTML 完整的 CSS 支援 僅透過 pdfHTML 支援 CSS
返回位元組陣列
設定複雜度 簡單 中度(手動排版)
輸出品質 完美的像素 良好但靜態

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

IronPDFiText 7 之間做出選擇取決於您的專案需求 - 但若談到 開發人員經驗、易用性和現代化的渲染精準度,IronPDF 顯然更勝一籌。

如果您正在處理動態 HTML內容、網頁渲染,或需要從 URL 建立 PDF 檔案,並完全支援 JavaScript 與 CSS,IronPDF 基於 Chromium 的引擎將提供無與倫比的逼真度。 其直觀的 API 和快速的設定使其成為快速開發和實際生產使用的理想選擇 - 尤其是在處理位元組陣列、檔案流或基於 Web 的 PDF 生成時。

另一方面,iText 7 是功能強大且備受推崇的函式庫,採用較傳統的排版驅動方式。 它提供了穩固的文件結構控制,非常適合需要細緻操作的開發人員,但它的學習曲線較陡,而且缺乏現代化的 HTML 渲染功能。

底線如下:

  • 想要像素完美的現代網頁內容輸出、樣式化 HTML 或快速原型設計嗎? Go with IronPDF.
  • 需要細粒度控制的低階 PDF 建立工具嗎? iText 7 可能是合適的選擇。

準備開始使用 IronPDF? 下載免費試用版,看看只需幾行程式碼就能在 C# 中輕鬆製作專業、以位元組為基礎的 PDF。

[{i:(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 機器人,結合科技與創意的樂趣。