在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
生成PDF文档是C#开发人员常见且通常必需的需求。 无论您是负责创建发票、详细的商业报告、转换网页内容还是管理各种其他业务文档,一个可靠的C# PDF生成器都是至关重要的。 许多开发人员寻找.NET库,这些库不仅简化了这些任务,而且提供了强大的功能,比如高保真度地将HTML转换为PDF,编辑现有的PDF,或从头开始以编程方式创建新的PDF。
如果您正在寻找这样一种强大且易于使用的解决方案,那您来对地方了。 本指南重点介绍IronPDF,这是一个领先的.NET库,精心设计以简化C#中的PDF生成和操作。 我们将引导您了解IronPDF如何解决常见的PDF生成需求,提供一个实用的教程帮助您快速入门,并讨论为什么IronPDF脱颖而出,成为您开发工具包中的强大利器。
我们将涵盖:
在评估C# PDF库时,开发人员通常优先考虑易用性、渲染准确性(尤其是HTML到PDF转换)、全面的功能集和整体性能。 IronPDF 在以下领域表现出色:
全面的PDF功能: IronPDF不仅仅是一个PDF创建器。 这是一款完整的C# PDF工具,支持大量操作:
编辑现有 PDF 文档
合并和拆分 PDF
添加页眉、页脚、水印和页码
填写和读取 PDF 表单
跨平台兼容性:使用IronPDF在Windows、Linux、macOS、Docker和Azure上开发和部署应用程序,支持.NET(Core、Standard、Framework)。
现在,让我们深入探讨如何在C# Windows窗体应用程序中使用IronPDF生成PDF。
第一步是创建一个Visual Studio项目。 在本教程中,我们将使用 Windows Forms 应用程序模板,但 IronPDF 可无缝与 Web 应用程序(ASP.NET)、控制台应用程序、WPF 等配合使用。
打开 Visual Studio。
单击 "创建新项目"。
从模板中选择“Windows 窗体应用程序 (.NET Framework 或 .NET Core)”,然后点击“下一步”。 将出现以下窗口。 为您的项目命名(例如,MyCSharpPdfGenerator
)。
命名项目
然后,点击“下一步”。 从下拉菜单中选择您所需的 .NET Framework(IronPDF 支持广泛的范围)。
选择 .NET Framework
点击“创建”按钮。 项目将被创建并准备好进行下一步。
可以通过使用 NuGet 将 IronPDF 轻松添加到您的项目中。 这是确保您拥有最新版本和所有必要依赖项的推荐方法。
在 Visual Studio 中,转到 工具 > NuGet 包管理器 > 包管理器控制台。 然后,输入以下命令并按回车:
Install-Package IronPdf
Install-Package IronPdf
在解决方案资源管理器中右键点击您的项目,并选择“管理 NuGet 包...”
点击“浏览”标签并搜索“IronPdf”。
从搜索结果中选择IronPdf
包,然后点击“安装”。
或者,您可以直接从IronPDF网站下载IronPDF DLL。
下载并将DLL解压缩到合适的位置(例如,您的解决方案目录中的“Libs”文件夹)。
在 Visual Studio 的解决方案资源管理器中,右键点击 ".NET Framework 项目" 的 "References" 或 ".NET Core/5+ 项目" 的 "Dependencies",然后选择 "Add Reference..." 或 "Add Project Reference...",然后点击 "Browse"。
IronPdf.dll
。在本教程中,我们将创建一个基本的用户界面来触发PDF生成。 如果您正在构建一个 Web 或控制台应用程序,您可以将 IronPDF 逻辑直接集成到控制器、服务或类中。
在 Visual Studio 中转到工具箱(查看 > 工具箱)。 将以下控件拖放到您的Form1设计界面:
Label
(例如,将您的应用程序命名为“C# PDF Generator Demo”)。RichTextBox
(命名为PdfText
)用于输入HTML/文本。TextBox
(命名为URL
)。两个Button
控件。
将第一个按钮的文本设置为“Generate PDF From Text”(将其命名为GeneratePDFFromTextButton
)。
GeneratePDFFromURLButton
)。现在,让我们添加C#逻辑。 双击表单设计器中的“Generate PDF From Text”按钮(GeneratePDFFromTextButton
)。 这将在您的Form1.cs
文件中创建一个事件处理程序方法。
首先,在 Form1.cs
文件的顶部添加 IronPDF 命名空间:
using IronPdf;
using IronPdf;
Imports IronPdf
然后,实现按钮的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
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#的开发人员来说是一个重要的优势。
按Ctrl + F5
(或点击开始按钮)来运行您的项目。 Windows窗体应用程序将会出现。
在富文本框中输入一些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>
点击“从文本生成PDF”按钮。 将出现“另存为”对话框。 选择位置和文件名,然后点击“保存”。
导航到保存 PDF 的位置并打开它。 您应该看到您的HTML内容在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
解释:
URL.Text
:这会从表单上的TextBox
控件获取URL字符串。RenderUrlAsPdf(URL.Text)
:这个强大的 IronPDF 方法会导航到给定的 URL,渲染其内容(包括 HTML、CSS、JavaScript 和图像),并将其转换为 PDF 文档。try-catch
),因为可能会发生网络问题或无效的URL。再次运行您的项目(Ctrl + F5
)。 这次,将完整的URL(例如,https://ironpdf.com
)输入到URL文本框中。
点击“从 URL 生成 PDF”按钮。 选择保存位置和文件名。
打开生成的PDF。 您将看到网页被忠实地转换为PDF文档,并保留了其布局和内容。
正如本教程所演示的,IronPDF 为所有C# PDF 生成需求提供了一个非常强大且简单的解决方案。 无论您是将复杂的 HTML 页面与复杂的 CSS 和 JavaScript 转换、从数据生成动态报告、从实时 URL 创建 PDF,还是需要在您的 .NET 应用程序中进行强大的 PDF 编辑功能,IronPDF 都提供了完成任务所需的工具和性能,以高效地完成工作。
当您生成 PDF C#项目时,您经常面临选择:要么使用具有渲染保真度或功能集限制的免费库,要么使用需要大量样板代码的更复杂的解决方案。 IronPDF 是一个全面且商业支持的.NET PDF 库,它简化了开发,确保高质量输出,并提供了超出基础 PDF 创建的丰富功能集。
准备好体验在 C# 中生成和操作 PDF 的最佳方式了吗?
发现 Iron Suite:以更低价格获得更多 .NET 工具(Iron Suite 包含多个 .NET 库,如果您处理其他文档格式或任务,它提供出色的价值。)
选择IronPDF,即为您的C#项目配备了领先的PDF生成和操作引擎,节省宝贵的开发时间,并确保每次生成的PDF文档均具备专业品质和像素级精确度。了解更多关于通过此详细指南在C#中将HTML转换为PDF的信息。