跳至页脚内容
产品比较

创建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).

每个库都为不同的用例提供了强大的工具集。 但哪一个最适合从 [字节数组](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/dd831853(v=vs.120) 在 C# 中生成 PDF? 本文通过比较、代码示例和见解来帮助 .NET 开发人员做出正确的选择。

无论您是构建企业级应用程序还是小型内部工具,选择正确的 PDF 库都可以为您节省开发时间并确保强大的输出。 让我们探索每个库提供的功能。

PDF 库简介

PDF 库有哪些用途?

C# 的 PDF 库允许开发人员以编程方式生成、操作和读取 PDF 文件。 它们适用于广泛的用例,例如:

  • 导出报告和发票
  • 从 Web 表单生成动态内容
  • 将 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、可访问性、合规性

[{i:(对于核心 PDF 操作,您需要使用 itext7,并且可以单独包括 html2pdf 等可选附加组件。)}]

安装(NuGet)

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

Install-Package itext7

通过 NuGet 包管理器控制台安装 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 内容完全写入并准备好作为字节数组返回。

这个示例展示了 iText 7 的 更模块化和可读的 API 与 iTextSharp 相比。然而,它仍然缺乏渲染 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 等较简单的库学习曲线陡峭。 开发人员需要熟悉其低级文档结构和模块化架构。

  • 简单任务的重量级\ 与 IronPDF 等简化流程的库相比,iText 7 在执行简单的 PDF 任务(如简单的文档创建或基本的 HTML 到 PDF 转换)时可能显得繁琐。

  • HTML 到 PDF 需要外部模块\ iText 7 的 HTML 到 PDF 转换仅通过附加的 pdfhtml 模块提供,该模块需要单独安装,并且可能无法像 IronPDF 那样无缝处理现代网页内容。

IronPDF for .NET:强大的 PDF 库

IronPDF 是一个高级 .NET 库,旨在简化 PDF 文档生成,专注于开发人员的生产力。 它尤其适用于渲染 HTML 内容和样式,使其非常适合现代 Web 到 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 包管理器安装它。 为此,请导航到“工具 > 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 文档。 您还可以传入文件路径或 URL。
  • pdfDoc.BinaryData 返回最终的 PDF 作为字节数组,准备好进行保存、流传输或数据库存储。

IronPDF。 的优缺点

优点

  • 轻松实现 HTML 到 PDF 渲染\ 将 HTML、CSS 和 JavaScript 内容直接渲染为 PDF,具有完整的样式,包括 Bootstrap 和自定义字体——无需复杂的布局代码或额外模块。

  • 快速开始和直观的 API\ 在几行代码中创建完全样式化的 PDF 文件,语法简洁,并完全兼容 .NET Core 和 .NET Framework。

  • 对 Web 技术的全面支持\ IronPDF 支持 JavaScript、现代 CSS、SVG 和媒体查询——大多数库在这方面存在困难,除非它们使用像 Chromium 这样的无头浏览器(IronPDF 在内部是这样做的)。

  • 内置图像和资产处理\ 轻松包含图像、本地文件,甚至可以从远程 URL 中提取资产,无需额外配置。

  • 永久许可证和无 AGPL\ 与 iText 7 不同,IronPDF 提供灵活的商业许可证,没有开源 AGPL 义务的限制。

  • 非常适合 MVC 和 Razor 视图\ 无缝转换 ASP.NET 应用程序中的 .cshtml Razor 视图为可打印的 PDF。

缺点

  • 商业用途需授权\ 虽然有免费试用版,但 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 文件或 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

输出

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 借助其 Chromium 引擎完全支持标签或外部样式表中的 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

输出

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 和快速设置使其非常适合快速开发和现实世界的生产使用——特别是在使用字节数组、文件流或基于 Web 的 PDF 生成时。

另一方面,iText 7 是一个强大且受人尊敬的库,采用更传统的布局驱动方法。 它提供了对文档结构的良好控制,非常适合需要精细操作的开发人员,但学习曲线较陡峭,缺乏现代 HTML 渲染功能。

结论如下:

  • 想要从现代 Web 内容、样式化 HTML 或快速原型中获得 像素完美 的输出? 选择 IronPDF。
  • 需要具备精细控制的低级 PDF 创建工具? iText 7 可能是合适的选择。

准备开始使用 IronPDF 吗?\ 下载免费试用版,看看在 C# 中创建专业的、基于字节数组的 PDF 是多么简单,仅需几行代码即可完成。

[{i:(iText 7 是其各自所有者的注册商标。 本网站与 iText 7 无关,未获得其认可或赞助。所有产品名称、徽标和品牌均为其各自所有者的财产。 比较仅供参考,反映的是撰写时的公开信息。]

常见问题解答

如何在 C# 中将字节数组转换为 PDF?

您可以使用 IronPDF 将字节数组转换为 C# 中的 PDF。只需使用 `PdfDocument.FromBytes` 方法将字节数组加载到 IronPDF 文档中,该方法将解析数据并生成 PDF 文档。

使用 IronPDF 进行 HTML 到 PDF 转换的好处是什么?

IronPDF 擅长将 HTML 转换为 PDF,因为它使用无头版 Chromium 引擎,支持现代 CSS 和 JavaScript。这使其非常适合将动态网页内容呈现为像素完美的 PDF 文档。

使用 IronPDF 生成 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 包管理器。在包管理器控制台中运行命令 `Install-Package IronPdf` 将其添加到您的项目中。

IronPDF 可以从 ASP.NET 视图创建 PDF 吗?

是的,IronPDF 可以直接将 ASP.NET 视图呈现到 PDF 文档中。此功能允许开发人员轻松将具有复杂布局和样式的网页转换为 PDF。

哪些类型的应用程序最受益于使用 IronPDF?

需要将动态网页内容(如报告和发票)转换为 PDF 的应用程序最受益于使用 IronPDF。其快速设置和 Web 技术支持使其非常适合需要频繁更新和现代设计的项目。

iText 7 的模块化架构如何影响其使用?

iText 7 的模块化架构允许根据需要添加特定的 PDF 功能,例如 HTML 转换或数字签名。这提供了灵活性,但可能需要为每个模块进行额外的学习和安装。

IronPDF 和 iText 7 之间的许可差异是什么?

IronPDF 提供适合商业应用程序的永久许可,无 AGPL 约束。相比之下,iText 7 提供在开源项目下使用的 AGPL 许可证,商业使用需要付费许可证。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。