使用IRONPDF

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

更新 2024年三月10日
分享:

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

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

第 1 步:创建新的 Windows 窗体应用程序

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

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

![如何用 C# 保存 PDF 文件(初级教程),图 1:Visual Studio 2022](/static-assets/pdf/blog/how-to-save-pdf-file-in-csharp/how-to-save-pdf-file-in-csharp-1.webp)

**视觉工作室 2022**

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

3.在 "创建新项目 "对话框中,选择 "Windows 窗体应用程序 "或 "Windows 窗体应用程序"。 (.NET框架)如下图所示,在 "创建新项目 "下点击 "创建"。

![如何用 C# 保存 PDF 文件(初级教程),图 2:新窗体应用程序](/static-assets/pdf/blog/how-to-save-pdf-file-in-csharp/how-to-save-pdf-file-in-csharp-2.webp)

**新表格应用程序**

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

![如何用 C# 保存 PDF 文件(初级教程),图 3:项目位置](/static-assets/pdf/blog/how-to-save-pdf-file-in-csharp/how-to-save-pdf-file-in-csharp-3.webp)

**项目地点**

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

6.单击创建按钮。

![如何用 C# 保存 PDF 文件(初级教程),图 4:其他信息](/static-assets/pdf/blog/how-to-save-pdf-file-in-csharp/how-to-save-pdf-file-in-csharp-4.webp)

**其他信息**

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

![如何用 C# 保存 PDF 文件(初级教程),图 5:Form1 项目](/static-assets/pdf/blog/how-to-save-pdf-file-in-csharp/how-to-save-pdf-file-in-csharp-5.webp)

**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_ClickgetFilePathChromePdfRenderer 图书馆。让我们通过每种方法来了解其工作原理。

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
VB   C#

下面是这种方法的具体操作步骤:

1.该方法调用 getFilePath 方法来获取保存 PDF 文件的文件路径。

2.如果文件路径不为空或空,该方法将继续保存 PDF 文件。

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

4.然后,该方法使用 将Html渲染为Pdf 类的方法将文本框 pdfContent 中的 HTML 内容转换为 PDF 文档。该 PDF 文档被分配给 PDFDocument 变量。

5.该方法使用 保存为 类的方法。

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
VB   C#

下面是这种方法的具体操作步骤:

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

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

3.该方法通过调用其 ShowDialog 方法来显示 SaveFileDialog 。该方法会显示对话框并返回一个 DialogResult 值,该值表示用户是点击了 "确定 "按钮还是点击了 "取消 "按钮。

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

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

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

如何用 C# 保存 PDF 文件(初级教程),图 7:运行 Windows 窗体项目

运行 Windows 窗体项目

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

如何用 C# 保存 PDF 文件(初级教程),图 8:保存对话框

保存对话框

创建的 PDF 文件如下

如何用 C# 保存 PDF 文件(初级教程),图 9:创建的 PDF 文件

创建 PDF 文件

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

结论

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

IronPDF 提供一系列功能,如 HTML 转换为 PDFPDF 合并分拆, 文本和图像提取等等。Iron PDF 可免费用于开发,并可在以下条件下使用 商业许可免费试用,允许开发人员在商业项目中使用它,并包括专门的支持和更新。此外,IronPDF 还是 Iron Suite这是一个 .NET 软件组件包,其中包括条形码生成库 (IronBarcode)创建、阅读和操作 Excel 文档 (IronXL) 处理文本提取 (IronOCR)等等。购买全套 Iron Suite 是一个经济实惠的解决方案,因为您只需支付两套产品的价格,即可获得全部五套产品。

< 前一页
如何在C#中将CSHTML转换为PDF
下一步 >
如何在Blazor中显示字节数组中的PDF

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >