跳至页脚内容
使用IRONPDF

如何在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应用程序的步骤

  1. 如下所示,打开 Visual Studio 2022。

如何在C#中保存PDF文件(初学者教程),图1:Visual Studio 2022 Visual Studio 2022

  1. 在开始页面上点击“创建新项目”或转到“文件”>“新建”>“项目”。
  2. 在“创建新项目”对话框中,如下所示在“创建新项目”下选择“Windows Forms应用程序”或“Windows Forms应用程序(.NET Framework)”。

如何在C#中保存PDF文件(初学者教程),图2:新表单应用程序 新表单应用程序

  1. 输入项目的名称并选择一个保存位置。

如何在C#中保存PDF文件(初学者教程),图3:项目位置 项目位置

  1. 选择.NET Framework。 从下拉菜单中选择.NET 7.0。
  2. 点击创建按钮。

如何在C#中保存PDF文件(初学者教程),图4:附加信息 附加信息

  1. Visual Studio 将为您创建一个新的C# Windows Forms应用程序项目,并在项目中添加一个默认命名为“Form1”的表单,如下所示。

如何在C#中保存PDF文件(初学者教程),图5:Form1项目 Form1项目

就是这样! 现在我们将开始使用设计器构建Windows Forms应用程序,添加用于创建和保存PDF文档文件的控件和功能。

步骤2:设计表单

您可以根据您的喜好设计表单。 本教程将通过添加两个标签、一个富文本框和两个按钮来进行极简设计。

如何在C#中保存PDF文件(初学者教程),图6:向表单添加按钮 向表单添加按钮

步骤3:安装IronPDF

下一步是在此项目中安装IronPDF以使用其丰富的功能。

可以通过Visual Studio中的NuGet包管理器来安装IronPDF。 您可以通过转到工具 > NuGet包管理器 > 包管理器控制台来导航到NuGet包管理器控制台。

输入以下命令并按Enter键:

Install-Package IronPdf

此命令将会下载并安装IronPDF包到你的项目中。 安装后,我们可以开始使用IronPDF。

编写代码以创建和保存PDF文件

要开始流程,请在Form1.cs类中编写两个方法:Save_ClickgetFilePath。 这些方法一起用于使用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
$vbLabelText   $csharpLabel

以下是此方法的分步说明:

  1. 方法调用getFilePath方法以获取将保存PDF文件的文件路径。
  2. 如果文件路径不为空或不为null,则该方法继续保存PDF文件。
  3. 方法创建ChromePdfRenderer类的新实例。 这是一个提供使用Google Chrome浏览器引擎将HTML内容转换为PDF文档的方法。
  4. 方法然后使用ChromePdfRenderer类的RenderHtmlAsPdf方法将文本框pdfContent的HTML内容转换为PDF文档。 此PDF文档被分配给PdfDocument变量
  5. 方法使用PdfDocument类的SaveAs方法将PDF文档保存到指定的文件路径。
  6. 最后,该方法显示一个消息框,以指示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
$vbLabelText   $csharpLabel

以下是此方法的分步说明:

  1. 方法创建SaveFileDialog类的新实例。 该类是Windows Forms库的一部分,并提供了一个对话框,允许用户选择将保存PDF文件的文件路径。
  2. 方法设置SaveFileDialog对象的几个属性以自定义其行为。 InitialDirectory属性设置对话框首次打开所在的目录。 Title属性设置对话框的标题。 CheckPathExists属性指定对话框是否应检查指定的路径是否存在。 DefaultExt属性设置文件类型的默认文件扩展名。 Filter属性设置在对话框中显示的文件类型过滤器。 FilterIndex属性设置要显示的默认过滤器。 最后,RestoreDirectory属性指定对话框在关闭前是否应恢复当前目录。
  3. 方法通过调用ShowDialog方法显示SaveFileDialog。 此方法显示对话框并返回一个DialogResult值,指示用户是点击“确定”按钮还是取消按钮。
  4. 如果用户点击“确定”按钮,该方法通过访问SaveFileDialogFileName属性返回用户选择的文件路径。
  5. 如果用户点击“取消”按钮或关闭对话框,该方法返回一个空字符串。

让我们运行项目并查看输出。 运行项目,以下表单将会打开。

如何在C#中保存PDF文件(初学者教程),图7:运行Windows Forms项目 运行Windows Forms项目

输入您的PDF内容并点击“保存”按钮,如下所示。

如何在C#中保存PDF文件(初学者教程),图8:保存对话框 保存对话框

生成以下PDF。

如何在C#中保存PDF文件(初学者教程),图9:生成的PDF文件 生成的PDF文件

IronPDF提供了一种简单的方法来将HTML内容转换为PDF文档,并使用ChromePdfRenderer类和SaveFileDialog对话框将其保存到用户选择的文件路径。

结论

从 Windows Forms 应用程序中保存 PDF 文件是一种常见需求,IronPDF 提供了一种易于使用且灵活的方法来完成此任务。 本文演示了如何使用IronPDF在C# Windows Forms应用程序中创建、添加内容和保存文件。 通过IronPDF,开发人员可以使用仅仅几行代码从应用程序中生成高质量的PDF文件。

IronPDF offers a range of features such as HTML to PDF Conversion Tutorial, PDF Merging Example Code, Splitting PDF Pages Guide, and Extracting Text and Images How-to, and more. IronPDF is free for development and available under a Commercial License with a Free Trial, which allows developers to use it in commercial projects and includes dedicated support and updates.

此外,IronPDF 是 Iron Suite 的一部分,这是一个包含以下库的.NET软件组件合集:

购买完整的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 的RenderHtmlAsPdfSaveAs方法更高效地创建和保存 PDF 文件。

Curtis Chau
技术作家

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

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