使用IRONPDF

如何在C#中保存PDF文件(初学者教程)

本文将探讨如何使用 IronPDF 从 Windows 窗体应用程序或任何 .NET 应用程序中保存 PDF 文件。

The IronPDF Library 是一个 .NET 库,提供用于在 C# 应用程序中生成和处理 PDF 文件的易用类和方法。 它允许开发人员只需几行代码就能创建、修改和保存 PDF 文件,是 Windows 窗体应用程序的绝佳选择。

步骤 1:创建一个新的 Windows 窗体应用程序

首先,创建一个新的 Visual Studio 项目。 以下是在 Visual Studio 2022 中创建一个新的 C# Windows 窗体应用程序的步骤

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

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

    Visual Studio 2022

  2. 点击开始页面上的 "创建新项目 "或转到 "文件">"新建">"项目"。

  3. 在“创建新项目”对话框中,如下所示,选择“Windows Forms App”或“Windows Forms App (.NET Framework)”来创建新项目。

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

    新的表单应用

  4. 输入项目名称并选择保存位置。

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

    项目位置

  5. 选择 .NET Framework。 从下拉菜单中选择 .NET 7.0。

  6. 点击创建按钮。

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

    附加信息

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

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

    Form1 项目

    就是这样! 现在,我们将开始使用设计器构建 Windows 窗体应用程序,添加创建和保存 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(filePath))
    {
        // 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(filePath))
    {
        // 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(filePath) 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. 如果文件路径不为空或空,该方法将继续保存 PDF 文件。

  3. 该方法创建一个新的ChromePdfRenderer类实例。 这是一个库,提供了一种使用 Google Chrome 浏览器引擎将 HTML 内容转换为 PDF 文档的方法。

  4. 然后,该方法使用 ChromePdfRenderer 类的RenderHtmlAsPdf 方法将文本框 pdfContent 的 HTML 内容转换为 PDF 文档。 此 PDF 文档被分配给 PdfDocument 变量

  5. 该方法使用SaveAs方法将PDF文档保存到指定的文件路径,属于PdfDocument类。

  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 "";
}
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 "";
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

以下是这种方法的具体步骤:

  1. 该方法创建一个新的SaveFileDialog类实例。 该类是 Windows 窗体库的一部分,提供一个对话框,允许用户选择保存 PDF 文件的文件路径。

  2. 该方法设置SaveFileDialog对象的多个属性以自定义其行为。 InitialDirectory 属性设置对话框首次打开时的目录。 Title 属性设置对话框的标题。 CheckPathExists属性指定对话框是否应检查指定的路径是否存在。 DefaultExt属性设置文件类型的默认文件扩展名。 Filter属性设置在对话框中显示的文件类型过滤器。 FilterIndex 属性设置要显示的默认过滤器。 最后,RestoreDirectory 属性指定对话框在关闭之前是否应该恢复当前目录。

  3. 该方法通过调用ShowDialog方法来显示SaveFileDialog。 此方法显示对话框并返回一个DialogResult值,该值指示用户是否点击了“OK”按钮或取消按钮。

  4. 如果用户点击“OK”按钮,该方法通过访问SaveFileDialogFileName属性返回用户选择的文件路径。

  5. 如果用户点击 "取消 "按钮或关闭对话框,该方法将返回空字符串。

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

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

    运行Windows窗体项目

    输入 PDF 内容并点击 "保存 "按钮,如下图所示。

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

    保存对话框

    创建以下 PDF 文件。

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

    创建的PDF文件

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

结论

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

IronPDF 提供了一系列功能,如HTML 转换为 PDF 教程,PDF 合并示例代码拆分 PDF 页指南提取文本和图像操作手册,等等。 IronPDF在开发过程中是免费的,并且可以在商业许可证下使用,提供免费试用,这允许开发人员在商业项目中使用它,并包括专门的支持和更新。 此外,IronPDF 是 Iron Suite 的一部分,该套件是.NET软件组件的集合,包括用于条形码生成的库(IronBarcode)、创建、读取和操作Excel文档(IronXL)、处理文本提取(IronOCR)等功能。 购买全套 Iron Suite 是一种经济高效的解决方案,因为您可以用购买两套产品的价格获得全部五套产品。

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