如何在C#中保存PDF文件(初学者教程)
本文将探讨如何使用IronPDF从Windows Forms应用程序或任何.NET应用程序保存PDF文件。
IronPDF库 是一个.NET库,提供了易于使用的类和方法,用于在C#应用程序中生成和处理PDF文件。 它允许开发人员仅用几行代码就可以创建、修改和保存PDF文件,是Windows Forms应用程序的绝佳选择。
步骤1:创建一个新的Windows Forms应用程序
首先,创建一个新的Visual Studio项目。 以下是在Visual Studio 2022中创建新的C# Windows Forms应用程序的步骤
- 如下所示,打开 Visual Studio 2022。
Visual Studio 2022
- 在开始页面上点击"创建新项目"或转到"文件">"新建">"项目"。
- 在"创建新项目"对话框中,如下所示在"创建新项目"下选择"Windows Forms应用程序"或"Windows Forms应用程序(.NET Framework)"。
新表单应用程序
- 输入项目的名称并选择一个保存位置。
项目位置
- 选择.NET Framework。 从下拉菜单中选择.NET 7.0。
- 点击创建按钮。
附加信息
- Visual Studio 将为您创建一个新的C# Windows Forms应用程序项目,并在项目中添加一个默认命名为"Form1"的表单,如下所示。
Form1项目
就是这样! 现在我们将开始使用设计器构建Windows Forms应用程序,添加用于创建和保存PDF文档文件的控件和功能。
步骤2:设计表单
您可以根据您的喜好设计表单。 本教程将通过添加两个标签、一个富文本框和两个按钮来进行极简设计。
向表单添加按钮
步骤3:安装IronPDF
下一步是在此项目中安装IronPDF以使用其丰富的功能。
可以通过Visual Studio中的NuGet包管理器来安装IronPDF。 您可以通过转到工具 > NuGet包管理器 > 包管理器控制台来导航到NuGet包管理器控制台。
键入以下命令并按Enter键:
Install-Package IronPdf
此命令将会下载并安装IronPDF包到你的项目中。 安装后,我们可以开始使用IronPDF。
编写代码以创建和保存PDF文件
要开始流程,请在Form1.cs类中编写两个方法:Save_Click和getFilePath。 这些方法一起用于使用ChromePdfRenderer类库将文本框的内容保存为PDF文件。 让我们逐步了解每个方法是如何工作的。
Save_Click 方法(创建PDF文档)
以下方法是按钮点击事件的事件处理程序。 此方法的目的是将文本框的内容另存为PDF文件。
private void Save_Click(object sender, EventArgs e)
{
// Get the file path to save the PDF file.
string filename = getFilePath();
// If the file path is not empty or null, proceed with saving the PDF file.
if (!String.IsNullOrEmpty(filename))
{
// Create a new instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();
// Render the file contents of the text box as a PDF document using the ChromePdfRenderer.
var pdfDocument = renderer.RenderHtmlAsPdf(pdfContent.Text);
// Save the PDF document to the specified file path using the SaveAs method.
pdfDocument.SaveAs(filename);
// Show a message box to indicate that the PDF file has been saved successfully.
MessageBox.Show("PDF has been saved Successfully!");
}
}private void Save_Click(object sender, EventArgs e)
{
// Get the file path to save the PDF file.
string filename = getFilePath();
// If the file path is not empty or null, proceed with saving the PDF file.
if (!String.IsNullOrEmpty(filename))
{
// Create a new instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();
// Render the file contents of the text box as a PDF document using the ChromePdfRenderer.
var pdfDocument = renderer.RenderHtmlAsPdf(pdfContent.Text);
// Save the PDF document to the specified file path using the SaveAs method.
pdfDocument.SaveAs(filename);
// Show a message box to indicate that the PDF file has been saved successfully.
MessageBox.Show("PDF has been saved Successfully!");
}
}Private Sub Save_Click(ByVal sender As Object, ByVal e As EventArgs)
' Get the file path to save the PDF file.
Dim filename As String = getFilePath()
' If the file path is not empty or null, proceed with saving the PDF file.
If Not String.IsNullOrEmpty(filename) Then
' Create a new instance of the ChromePdfRenderer class.
Dim renderer = New ChromePdfRenderer()
' Render the file contents of the text box as a PDF document using the ChromePdfRenderer.
Dim pdfDocument = renderer.RenderHtmlAsPdf(pdfContent.Text)
' Save the PDF document to the specified file path using the SaveAs method.
pdfDocument.SaveAs(filename)
' Show a message box to indicate that the PDF file has been saved successfully.
MessageBox.Show("PDF has been saved Successfully!")
End If
End Sub以下是此方法的分步说明:
- 方法调用
getFilePath方法以获取将保存PDF文件的文件路径。 - 如果文件路径不为空或不为null,则该方法继续保存PDF文件。
- 方法创建
ChromePdfRenderer类的新实例。 这是一个提供使用Google Chrome浏览器引擎将HTML内容转换为PDF文档的方法。 - 方法然后使用
ChromePdfRenderer类的RenderHtmlAsPdf方法将文本框pdfContent的HTML内容转换为PDF文档。 此PDF文档被分配给PdfDocument变量。 - 方法使用
PdfDocument类的SaveAs方法将PDF文档保存到指定的文件路径。 - 最后,该方法显示一个消息框,以指示PDF文件已成功保存。
getFilePath 方法(保存PDF文件)
此方法用于显示SaveFileDialog以让用户选择将保存PDF文件的文件路径。
public string getFilePath()
{
// Create a new instance of the SaveFileDialog class.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
// Set the initial directory where the SaveFileDialog will open.
saveFileDialog1.InitialDirectory = @"D:\";
// Set the title of the SaveFileDialog.
saveFileDialog1.Title = "Save the PDF Files";
// Set the SaveFileDialog to check if the specified path exists.
saveFileDialog1.CheckPathExists = true;
// Set the default extension for the file type.
saveFileDialog1.DefaultExt = ".pdf";
// Set the filter to display only PDF files or all files.
saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
// Set the filter index to display the PDF filter as the default.
saveFileDialog1.FilterIndex = 2;
// Set the RestoreDirectory property to true so that the SaveFileDialog
// restores the current directory before closing.
saveFileDialog1.RestoreDirectory = true;
// Show the SaveFileDialog and get the result.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// If the user clicked the OK button in the SaveFileDialog, return the selected file path.
return saveFileDialog1.FileName;
}
// If the user did not click the OK button, return an empty string.
return String.Empty;
}public string getFilePath()
{
// Create a new instance of the SaveFileDialog class.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
// Set the initial directory where the SaveFileDialog will open.
saveFileDialog1.InitialDirectory = @"D:\";
// Set the title of the SaveFileDialog.
saveFileDialog1.Title = "Save the PDF Files";
// Set the SaveFileDialog to check if the specified path exists.
saveFileDialog1.CheckPathExists = true;
// Set the default extension for the file type.
saveFileDialog1.DefaultExt = ".pdf";
// Set the filter to display only PDF files or all files.
saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*";
// Set the filter index to display the PDF filter as the default.
saveFileDialog1.FilterIndex = 2;
// Set the RestoreDirectory property to true so that the SaveFileDialog
// restores the current directory before closing.
saveFileDialog1.RestoreDirectory = true;
// Show the SaveFileDialog and get the result.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// If the user clicked the OK button in the SaveFileDialog, return the selected file path.
return saveFileDialog1.FileName;
}
// If the user did not click the OK button, return an empty string.
return String.Empty;
}Public Function getFilePath() As String
' Create a new instance of the SaveFileDialog class.
Dim saveFileDialog1 As New SaveFileDialog()
' Set the initial directory where the SaveFileDialog will open.
saveFileDialog1.InitialDirectory = "D:\"
' Set the title of the SaveFileDialog.
saveFileDialog1.Title = "Save the PDF Files"
' Set the SaveFileDialog to check if the specified path exists.
saveFileDialog1.CheckPathExists = True
' Set the default extension for the file type.
saveFileDialog1.DefaultExt = ".pdf"
' Set the filter to display only PDF files or all files.
saveFileDialog1.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"
' Set the filter index to display the PDF filter as the default.
saveFileDialog1.FilterIndex = 2
' Set the RestoreDirectory property to true so that the SaveFileDialog
' restores the current directory before closing.
saveFileDialog1.RestoreDirectory = True
' Show the SaveFileDialog and get the result.
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
' If the user clicked the OK button in the SaveFileDialog, return the selected file path.
Return saveFileDialog1.FileName
End If
' If the user did not click the OK button, return an empty string.
Return String.Empty
End Function以下是此方法的分步说明:
- 方法创建
SaveFileDialog类的新实例。 该类是Windows Forms库的一部分,并提供了一个对话框,允许用户选择将保存PDF文件的文件路径。 - 方法设置
SaveFileDialog对象的几个属性以自定义其行为。InitialDirectory属性设置对话框首次打开所在的目录。Title属性设置对话框的标题。CheckPathExists属性指定对话框是否应检查指定的路径是否存在。DefaultExt属性设置文件类型的默认文件扩展名。Filter属性设置在对话框中显示的文件类型过滤器。FilterIndex属性设置要显示的默认过滤器。 最后,RestoreDirectory属性指定对话框在关闭前是否应恢复当前目录。 - 方法通过调用
ShowDialog方法显示SaveFileDialog。 此方法显示对话框并返回一个DialogResult值,指示用户是点击"确定"按钮还是取消按钮。 - 如果用户点击"确定"按钮,该方法通过访问
SaveFileDialog的FileName属性返回用户选择的文件路径。 - 如果用户点击"取消"按钮或关闭对话框,该方法返回一个空字符串。
让我们运行项目并查看输出。 运行项目,以下表单将会打开。
运行Windows Forms项目
输入您的PDF内容并点击"保存"按钮,如下所示。
保存对话框
生成以下PDF。
生成的PDF文件
IronPDF提供了一种简单的方法来将HTML内容转换为PDF文档,并使用ChromePdfRenderer类和SaveFileDialog对话框将其保存到用户选择的文件路径。
结论
从 Windows Forms 应用程序中保存 PDF 文件是一种常见需求,IronPDF 提供了一种易于使用且灵活的方法来完成此任务。 本文演示了如何使用IronPDF在C# Windows Forms应用程序中创建、添加内容和保存文件。 通过IronPDF,开发人员可以使用仅仅几行代码从应用程序中生成高质量的PDF文件。
IronPDF提供了多种功能,例如HTML到PDF转换教程,PDF合并示例代码,拆分PDF页面指南,以及提取文本和图像操作方法等。 IronPDF供开发使用,并以商业许可证与免费试用的形式提供,允许开发人员在商业项目中使用并包括专门的支持与更新。
此外,IronPDF 是 Iron Suite 的一部分,这是一个包含以下库的.NET软件组件合集:
- 条码生成 (IronBarcode),
- Excel 管理 (IronXL),
- 文本提取 (IronOCR)
[购买完整的Iron Suite](Iron Suite)是一个经济有效的解决方案,因为您可以用两款产品的价格购买到五款产品。
常见问题解答
如何在C# Windows Forms应用程序中保存PDF文件?
您可以通过在表单中设置文本框和按钮等控件,并实现Save_Click方法,使用IronPDF在C# Windows Forms应用程序中将内容呈现并保存为PDF,使用ChromePdfRenderer类。
在设置Windows Forms应用程序以使用C#保存PDF中涉及哪些步骤?
要设置用于保存PDF的Windows Forms应用程序,可以在Visual Studio中创建一个新项目,添加必要的控件,如标签和富文本框,并通过NuGet包管理器安装IronPDF以利用其PDF呈现功能。
如何在 C# 中将 HTML 内容转换为 PDF?
您可以通过使用IronPDF的RenderHtmlAsPdf方法将HTML内容转换为C#中的PDF,该方法允许您将HTML字符串直接呈现到PDF文档。
在PDF生成的上下文中,Save_Click方法的作用是什么?
在应用程序中,Save_Click方法充当事件处理程序,负责捕获按钮的点击事件,以启动将文本框内容呈现为PDF文件的过程,使用IronPDF的渲染类。
如何在C#应用程序中提示用户选择文件路径以保存PDF?
在C#应用程序中,可以使用SaveFileDialog类提示用户选择文件路径以保存PDF,该类允许设置文件选择接口并返回选择的路径以保存呈现的PDF。
IronPDF在PDF操作中提供了哪些高级功能?
IronPDF提供了高级功能,如HTML到PDF转换,PDF合并,拆分PDF页面,以及提取文本和图像,为.NET应用程序中的PDF操作提供全面的工具套件。
在商业项目中使用IronPDF进行PDF生成是否需要费用?
IronPDF在开发过程中可以通过试用许可证免费使用。然而,对于商业项目,需要购买商业许可证,其中包含专属支持和定期更新等好处。
Iron Suite是什么,对开发者有什么好处?
Iron Suite是一个.NET库集合,包括条形码生成、Excel文档操作和PDF处理工具。它为需要多种功能的开发人员提供了一种经济实惠的解决方案。
IronPDF 是否兼容 .NET 10?如果兼容,这对 C# 中的 PDF 保存有什么好处?
是的——IronPDF 完全支持 .NET 10,包括桌面、Web 和跨平台项目类型。使用 .NET 10 构建可带来诸多改进,例如更快的运行时性能、对现代 C# 增强功能的访问以及与平台功能的更紧密集成,这些改进有助于通过 IronPDF 的RenderHtmlAsPdf和SaveAs方法更高效地创建和保存 PDF 文件。






