使用IRONPDF

C# PDF生成器综合指南:使用IronPDF轻松生成和处理PDF

生成PDF文档是C#开发人员常见且通常必需的需求。 无论您是负责创建发票、详细的商业报告、转换网页内容还是管理各种其他业务文档,一个可靠的C# PDF生成器都是至关重要的。 许多开发人员寻找.NET库,这些库不仅简化了这些任务,而且提供了强大的功能,比如高保真度地将HTML转换为PDF,编辑现有的PDF,或从头开始以编程方式创建新的PDF。

如果您正在寻找这样一种强大且易于使用的解决方案,那您来对地方了。 本指南重点介绍IronPDF,这是一个领先的.NET库,精心设计以简化C#中的PDF生成和操作。 我们将引导您了解IronPDF如何解决常见的PDF生成需求,提供一个实用的教程帮助您快速入门,并讨论为什么IronPDF脱颖而出,成为您开发工具包中的强大利器。

我们将涵盖:

  • 了解 C# PDF 生成的领域。
  • 为什么IronPDF是处理C# PDF任务的绝佳选择。
  • 在您的C#项目中设置IronPDF(Windows窗体示例)。
  • 从HTML内容和实时URL生成PDF。
  • 关键功能使IronPDF成为高效而强大的C# PDF库

为什么选择IronPDF作为您的C#PDF生成器?

在评估C# PDF库时,开发人员通常优先考虑易用性、渲染准确性(尤其是HTML到PDF转换)、全面的功能集和整体性能。 IronPDF 在以下领域表现出色:

  • 简洁性和开发者生产力: 正如您将在本教程中看到的那样,IronPDF可以让您仅用少量的C#代码生成和操作PDF文档。 它抽象掉了通常在其他PDF操作方法或更冗长的库中遇到的底层复杂性。
  • 像素完美的HTML转PDF渲染: 一个突出的特点是IronPDF使用嵌入式Chrome渲染引擎。这确保了HTML、CSS和JavaScript的渲染具有与现代网页浏览器中相同的精确度和保真度。 这对于从网页内容生成专业外观的文档至关重要,而这正是一些C#的免费PDF库可能不足之处。
  • 全面的PDF功能: IronPDF不仅仅是一个PDF创建器。 这是一款完整的C# PDF工具,支持大量操作:

    • 编辑现有 PDF 文档

    • 合并和拆分 PDF

    • 添加页眉、页脚、水印和页码

    • 填写和读取 PDF 表单

    • 使用密码和权限保护文档
  • 数字签名 PDF
  • 优秀的支持和最新的文档:作为一个商业支持的库,IronPDF提供专业的技术支持,并维护广泛且清晰的文档,使开发人员能够快速高效地实现解决方案。
  • 跨平台兼容性:使用IronPDF在Windows、Linux、macOS、Docker和Azure上开发和部署应用程序,支持.NET(Core、Standard、Framework)。

    现在,让我们深入探讨如何在C# Windows窗体应用程序中使用IronPDF生成PDF。

步骤 1:设置 Visual Studio 项目以进行 C# PDF 生成

第一步是创建一个Visual Studio项目。 在本教程中,我们将使用 Windows Forms 应用程序模板,但 IronPDF 可无缝与 Web 应用程序(ASP.NET)、控制台应用程序、WPF 等配合使用。

打开 Visual Studio。

打开用于 C# 项目的 Visual Studio

单击 "创建新项目"。

在 Visual Studio 中创建新的项目用于 C# PDF 生成器

从模板中选择“Windows 窗体应用程序 (.NET Framework 或 .NET Core)”,然后点击“下一步”。 将出现以下窗口。 为您的项目命名(例如,MyCSharpPdfGenerator)。

为PDF生成命名C#项目

命名项目

然后,点击“下一步”。 从下拉菜单中选择您所需的 .NET Framework(IronPDF 支持广泛的范围)。

选择用于IronPDF C#项目的.NET Framework

选择 .NET Framework

点击“创建”按钮。 项目将被创建并准备好进行下一步。

为 C# PDF 生成创建的 Visual Studio 项目

第2步:安装IronPDF C#库 - 您的PDF生成关键

可以通过使用 NuGet 将 IronPDF 轻松添加到您的项目中。 这是确保您拥有最新版本和所有必要依赖项的推荐方法。

选项 1:包管理器控制台(最快)

在 Visual Studio 中,转到 工具 > NuGet 包管理器 > 包管理器控制台。 然后,输入以下命令并按回车:

Install-Package IronPdf
Install-Package IronPdf
SHELL

选项2:NuGet包管理器GUI

  1. 在解决方案资源管理器中右键点击您的项目,并选择“管理 NuGet 包...”

  2. 点击“浏览”标签并搜索“IronPdf”。

  3. 从搜索结果中选择IronPdf包,然后点击“安装”。

    通过 NuGet 包管理器 GUI 安装 IronPDF C# 库

选项 3:手动安装(下载 DLL)

或者,您可以直接从IronPDF网站下载IronPDF DLL

  1. 下载并将DLL解压缩到合适的位置(例如,您的解决方案目录中的“Libs”文件夹)。

  2. 在 Visual Studio 的解决方案资源管理器中,右键点击 ".NET Framework 项目" 的 "References" 或 ".NET Core/5+ 项目" 的 "Dependencies",然后选择 "Add Reference..." 或 "Add Project Reference...",然后点击 "Browse"。

  3. 导航并选择IronPdf.dll

步骤 3:设计一个简单的 Windows 窗体界面(可选)

在本教程中,我们将创建一个基本的用户界面来触发PDF生成。 如果您正在构建一个 Web 或控制台应用程序,您可以将 IronPDF 逻辑直接集成到控制器、服务或类中。

在 Visual Studio 中转到工具箱(查看 > 工具箱)。 将以下控件拖放到您的Form1设计界面:

  • 一个Label(例如,将您的应用程序命名为“C# PDF Generator Demo”)。
  • 一个RichTextBox(命名为PdfText)用于输入HTML/文本。
  • 一个用于输入网址的TextBox(命名为URL)。
  • 两个Button控件。

    • 将第一个按钮的文本设置为“Generate PDF From Text”(将其命名为GeneratePDFFromTextButton)。

    • 将第二个按钮的文本设置为“从 URL 生成 PDF”(命名为GeneratePDFFromURLButton)。

    为 C# PDF Generator 应用程序设计 Windows 窗体

步骤 4:编写 C# 代码从文本/HTML 生成 PDF

现在,让我们添加C#逻辑。 双击表单设计器中的“Generate PDF From Text”按钮(GeneratePDFFromTextButton)。 这将在您的Form1.cs文件中创建一个事件处理程序方法。

首先,在 Form1.cs 文件的顶部添加 IronPDF 命名空间:

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

然后,实现按钮的click事件处理程序。 此代码将从RichTextBox中获取文本(可以是纯文本或HTML),并将其转换为PDF文档。

private void GeneratePDFFromTextButton_Click(object sender, EventArgs e)
{
    // It's recommended to set your license key once at application startup.
    // IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 
    // If no key is set, IronPDF will watermark PDFs after a trial period.

    // Use SaveFileDialog to let the user choose where to save the PDF
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Default to My Documents
    saveFileDialog1.Title = "Save PDF File As";
    saveFileDialog1.DefaultExt = "pdf";
    saveFileDialog1.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    saveFileDialog1.FilterIndex = 1; // Start with PDF files selected
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filename = saveFileDialog1.FileName;

        // The core of PDF generation from HTML/Text using IronPDF
        // IronPDF's ChromePdfRenderer accurately renders HTML, CSS, and JavaScript.
        var renderer = new ChromePdfRenderer();

        // The RenderHtmlAsPdf method converts an HTML string to a PDF document.
        // This is incredibly powerful for generating dynamic reports, invoices, tickets, etc.
        // from HTML templates.
        using (var pdfDocument = renderer.RenderHtmlAsPdf(PdfText.Text))
        {
            pdfDocument.SaveAs(filename);
        }

        MessageBox.Show("PDF Generated Successfully at: " + filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
private void GeneratePDFFromTextButton_Click(object sender, EventArgs e)
{
    // It's recommended to set your license key once at application startup.
    // IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 
    // If no key is set, IronPDF will watermark PDFs after a trial period.

    // Use SaveFileDialog to let the user choose where to save the PDF
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Default to My Documents
    saveFileDialog1.Title = "Save PDF File As";
    saveFileDialog1.DefaultExt = "pdf";
    saveFileDialog1.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    saveFileDialog1.FilterIndex = 1; // Start with PDF files selected
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filename = saveFileDialog1.FileName;

        // The core of PDF generation from HTML/Text using IronPDF
        // IronPDF's ChromePdfRenderer accurately renders HTML, CSS, and JavaScript.
        var renderer = new ChromePdfRenderer();

        // The RenderHtmlAsPdf method converts an HTML string to a PDF document.
        // This is incredibly powerful for generating dynamic reports, invoices, tickets, etc.
        // from HTML templates.
        using (var pdfDocument = renderer.RenderHtmlAsPdf(PdfText.Text))
        {
            pdfDocument.SaveAs(filename);
        }

        MessageBox.Show("PDF Generated Successfully at: " + filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
Private Sub GeneratePDFFromTextButton_Click(ByVal sender As Object, ByVal e As EventArgs)
	' It's recommended to set your license key once at application startup.
	' IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 
	' If no key is set, IronPDF will watermark PDFs after a trial period.

	' Use SaveFileDialog to let the user choose where to save the PDF
	Dim saveFileDialog1 As New SaveFileDialog()
	saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Default to My Documents
	saveFileDialog1.Title = "Save PDF File As"
	saveFileDialog1.DefaultExt = "pdf"
	saveFileDialog1.Filter = "PDF files (*.pdf) *.pdf All files (*.*) *.*"
	saveFileDialog1.FilterIndex = 1 ' Start with PDF files selected
	saveFileDialog1.RestoreDirectory = True

	If saveFileDialog1.ShowDialog() = DialogResult.OK Then
		Dim filename As String = saveFileDialog1.FileName

		' The core of PDF generation from HTML/Text using IronPDF
		' IronPDF's ChromePdfRenderer accurately renders HTML, CSS, and JavaScript.
		Dim renderer = New ChromePdfRenderer()

		' The RenderHtmlAsPdf method converts an HTML string to a PDF document.
		' This is incredibly powerful for generating dynamic reports, invoices, tickets, etc.
		' from HTML templates.
		Using pdfDocument = renderer.RenderHtmlAsPdf(PdfText.Text)
			pdfDocument.SaveAs(filename)
		End Using

		MessageBox.Show("PDF Generated Successfully at: " & filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
	End If
End Sub
$vbLabelText   $csharpLabel

C# PDF 生成代码的解释:

  • IronPdf.License.LicenseKey:建议设置您的 IronPDF 许可证密钥。 如果您有一个,请取消注释该行并将"YourLicenseKey..."替换为您的实际密钥。 IronPDF无需许可证密钥即可运行,但在试用期后,文档将带有水印。
  • SaveFileDialog:这提供了一个标准的 Windows 对话框,供用户选择 PDF 的保存位置和文件名。
  • ChromePdfRenderer:这是 IronPDF HTML 转 PDF 功能的核心。 它使用嵌入的Chromium引擎以实现最高精度。
  • RenderHtmlAsPdf(PdfText.Text):这个单一方法调用从你的RichTextBox(可以是丰富的HTML)中获取字符串内容,并将其转换成PDF文档对象。
  • SaveAs(filename):此方法将生成的PDF文档保存到用户指定的路径。
  • 使用using语句用于pdfDocument确保资源得到正确管理。

    注意,IronPDF如何将HTML到PDF转换这样一个潜在复杂的任务简化为仅仅几行关键代码。 这对于需要快速且可靠地生成 PDF C#的开发人员来说是一个重要的优势。

运行项目并从文本/HTML生成您的第一个PDF

Ctrl + F5(或点击开始按钮)来运行您的项目。 Windows窗体应用程序将会出现。

运行 C# PDF 生成器应用程序

在富文本框中输入一些HTML内容。 例如

<h1>My First C# PDF Document</h1>
<p>This PDF was generated using <strong>IronPDF</strong> in a C# application.</p>
<p>IronPDF makes it very easy to convert HTML content, including styles and images, into professional PDF files.</p>
<ul>
    <li>Easy to use</li>
    <li>Accurate rendering</li>
    <li>Feature-rich</li>
</ul>
<h1>My First C# PDF Document</h1>
<p>This PDF was generated using <strong>IronPDF</strong> in a C# application.</p>
<p>IronPDF makes it very easy to convert HTML content, including styles and images, into professional PDF files.</p>
<ul>
    <li>Easy to use</li>
    <li>Accurate rendering</li>
    <li>Feature-rich</li>
</ul>
HTML

在 C# PDF 生成器应用中输入 HTML

点击“从文本生成PDF”按钮。 将出现“另存为”对话框。 选择位置和文件名,然后点击“保存”。

验证PDF输出(来自文本/HTML)

导航到保存 PDF 的位置并打开它。 您应该看到您的HTML内容在PDF文档中准确呈现。

使用 IronPDF C# 从 HTML 字符串生成的输出 PDF 文件

步骤 5:编写 C# 代码从 URL 生成 PDF

从实时网页生成PDF是另一个常见的需求。 IronPDF 让这变得同样简单。 在表单设计器中双击“Generate PDF FROM URL”按钮 (GeneratePDFFromURLButton) 以创建其点击事件处理程序。

添加以下C#代码:

private void GeneratePDFFromURLButton_Click(object sender, EventArgs e)
{
    // IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 

    if (string.IsNullOrWhiteSpace(URL.Text))
    {
        MessageBox.Show("Please enter a valid URL.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }

    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    saveFileDialog1.Title = "Save PDF From URL As";
    saveFileDialog1.DefaultExt = "pdf";
    saveFileDialog1.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    saveFileDialog1.FilterIndex = 1;
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filename = saveFileDialog1.FileName;
        try
        {
            var renderer = new ChromePdfRenderer();
            // RenderUrlAsPdf fetches the content from the URL and converts it to PDF.
            // This is excellent for archiving web pages or creating PDFs from online reports.
            using (var pdfDocument = renderer.RenderUrlAsPdf(URL.Text))
            {
                pdfDocument.SaveAs(filename);
            }
            MessageBox.Show("PDF from URL Generated Successfully at: " + filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error generating PDF from URL: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
private void GeneratePDFFromURLButton_Click(object sender, EventArgs e)
{
    // IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 

    if (string.IsNullOrWhiteSpace(URL.Text))
    {
        MessageBox.Show("Please enter a valid URL.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }

    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    saveFileDialog1.Title = "Save PDF From URL As";
    saveFileDialog1.DefaultExt = "pdf";
    saveFileDialog1.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    saveFileDialog1.FilterIndex = 1;
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filename = saveFileDialog1.FileName;
        try
        {
            var renderer = new ChromePdfRenderer();
            // RenderUrlAsPdf fetches the content from the URL and converts it to PDF.
            // This is excellent for archiving web pages or creating PDFs from online reports.
            using (var pdfDocument = renderer.RenderUrlAsPdf(URL.Text))
            {
                pdfDocument.SaveAs(filename);
            }
            MessageBox.Show("PDF from URL Generated Successfully at: " + filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error generating PDF from URL: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
Private Sub GeneratePDFFromURLButton_Click(ByVal sender As Object, ByVal e As EventArgs)
	' IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 

	If String.IsNullOrWhiteSpace(URL.Text) Then
		MessageBox.Show("Please enter a valid URL.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
		Return
	End If

	Dim saveFileDialog1 As New SaveFileDialog()
	saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
	saveFileDialog1.Title = "Save PDF From URL As"
	saveFileDialog1.DefaultExt = "pdf"
	saveFileDialog1.Filter = "PDF files (*.pdf) *.pdf All files (*.*) *.*"
	saveFileDialog1.FilterIndex = 1
	saveFileDialog1.RestoreDirectory = True

	If saveFileDialog1.ShowDialog() = DialogResult.OK Then
		Dim filename As String = saveFileDialog1.FileName
		Try
			Dim renderer = New ChromePdfRenderer()
			' RenderUrlAsPdf fetches the content from the URL and converts it to PDF.
			' This is excellent for archiving web pages or creating PDFs from online reports.
			Using pdfDocument = renderer.RenderUrlAsPdf(URL.Text)
				pdfDocument.SaveAs(filename)
			End Using
			MessageBox.Show("PDF from URL Generated Successfully at: " & filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
		Catch ex As Exception
			MessageBox.Show("Error generating PDF from URL: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
		End Try
	End If
End Sub
$vbLabelText   $csharpLabel

解释:

  • URL.Text:这会从表单上的TextBox控件获取URL字符串。
  • RenderUrlAsPdf(URL.Text):这个强大的 IronPDF 方法会导航到给定的 URL,渲染其内容(包括 HTML、CSS、JavaScript 和图像),并将其转换为 PDF 文档。
  • 为了增强健壮性,包含了错误处理 (try-catch),因为可能会发生网络问题或无效的URL。

运行项目并从 URL 生成 PDF

再次运行您的项目(Ctrl + F5)。 这次,将完整的URL(例如,https://ironpdf.com)输入到URL文本框中。

输入 URL 到 C# PDF 生成器应用程序中

点击“从 URL 生成 PDF”按钮。 选择保存位置和文件名。

验证PDF输出(来自URL)

打开生成的PDF。 您将看到网页被忠实地转换为PDF文档,并保留了其布局和内容。

使用IronPDF在C#中从URL生成的输出PDF文档

结论:使用 IronPDF 简化您的 C# PDF 生成

正如本教程所演示的,IronPDF 为所有C# PDF 生成需求提供了一个非常强大且简单的解决方案。 无论您是将复杂的 HTML 页面与复杂的 CSS 和 JavaScript 转换、从数据生成动态报告、从实时 URL 创建 PDF,还是需要在您的 .NET 应用程序中进行强大的 PDF 编辑功能,IronPDF 都提供了完成任务所需的工具和性能,以高效地完成工作。

当您生成 PDF C#项目时,您经常面临选择:要么使用具有渲染保真度或功能集限制的免费库,要么使用需要大量样板代码的更复杂的解决方案。 IronPDF 是一个全面且商业支持的.NET PDF 库,它简化了开发,确保高质量输出,并提供了超出基础 PDF 创建的丰富功能集。

准备好体验在 C# 中生成和操作 PDF 的最佳方式了吗?

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
如何从PDF文件中删除密码
下一步 >
C# 以编程方式创建 PDF 文件