使用 IRONPDF

如何在C#中保存PDF檔案(初學者教程)

已更新 2024年3月10日
分享:

本文將探討如何使用 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**
  2. 在啟動頁面上點擊「新建專案」或前往「檔案」>「新建」>「專案」。

  3. 在「新建專案」對話框中,選擇「Windows Forms 應用程式」或「Windows Forms 應用程式」。 (.NET框架)在「創建一個新專案」下,如下所示。

    在C#中如何保存PDF檔案(初學者教程),圖2:新的表單應用程式

    **New Forms App**
  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 Forms 應用程式,添加控件和功能以創建和保存 PDF 文件。

步驟二:設計表單

您可以根據自己的喜好設計表單。本教程將透過新增兩個標籤、一個富文本框和兩個按鈕來製作一個簡約的設計。

如何在 C# 中保存 PDF 文件 (初學者教程),圖 6:在表單中添加按鈕

在表單中添加按鈕

步驟 3:安裝 IronPDF

下一步是在此專案中安裝 IronPDF 以使用其豐富的功能。

IronPDF 可以使用 Visual Studio 中的 NuGet 套件管理器安裝。您可以透過進入 工具 > NuGet 套件管理器 > 套件管理器主控台 來導航到 NuGet 套件管理器主控台。

輸入以下命令並按下 Enter 鍵:

Install-Package IronPdf

此命令將下載並安裝IronPDF套件到您的項目中。一旦安裝完成,我們即可開始使用IronPDF。

編寫代碼來創建和保存PDF文件

首先,編寫兩個方法:Save_ClickgetFilePathForm1.cs 類中。這些方法一起使用來將文本框的內容保存為PDF文件,使用IronPDF。 ChromePdfRenderer 庫存。我們來逐一了解每個方法的運作方式。

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. 如果文件路徑不為空或null,該方法將繼續保存PDF文件。

  3. 該方法創建了一個新的 ChromePdfRenderer 類實例。這是一個使用Google Chrome瀏覽器引擎將HTML內容轉換為PDF文檔的庫。

  4. 該方法然後使用 RenderHtmlAsPdf ChromePdfRenderer 類的方法將文本框 pdfContent 的 HTML 內容轉換為 PDF 文件。該 PDF 文件被分配到 PdfDocument 變數。

  5. 這個方法將 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
VB   C#

以下是此方法所做工作的逐步說明:

  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 提供了一種簡單的方法,使用 ChromePdfRenderer 類和 SaveFileDialog 對話框將 HTML 內容轉換為 PDF 文件,並將其保存到使用者選擇的檔案路徑中。

結論

從 Windows Forms 應用程式儲存 PDF 文件是一項常見需求,而 IronPDF 提供了一種易於使用且靈活的方法來完成此任務。本文展示了如何在 C# Windows Forms 應用程式中使用 IronPDF 來創建、添加內容和儲存文件。通過 IronPDF,開發人員只需幾行代碼即可從其應用程式生成高品質的 PDF 文件。

IronPDF 提供了一系列功能,例如 HTML 轉換為 PDF,PDF 合併分割, 文字和圖片提取,等等。IronPDF 在開發階段是免費的,並提供一個 商業授權免費試用允許開發人員在商業項目中使用,並包含專門的支持和更新。此外,IronPDF 是 Iron Suite這是一組 .NET 軟體元件的集合,包括用於條碼生成的庫 (IronBarcode)建立、閱讀及操作Excel文件 (IronXL) 處理文本提取 (IronOCR)此外,購買完整的 Iron Suite 是一個具成本效益的解決方案,因為您可以以購買兩個產品的價格獲得全部五個產品。

< 上一頁
如何在C#中將CSHTML轉換為PDF
下一個 >
如何在Blazor中顯示來自字節陣列的PDF

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >