使用 IRONPDF

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

本文將探討如何使用 IronPDF 將 PDF 檔案從 Windows Forms 應用程式或任何 .NET 應用程式中儲存。

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 App」或「Windows Forms App (.NET Framework)」下的「建立新專案」。

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

    新表單應用程式

  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 文件檔案。

步驟 2:設計表單

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

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

在表單中添加按鈕

步驟 3:安裝 IronPDF

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

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

輸入以下命令並按 Enter:

Install-Package IronPdf

此命令將在您的專案中下載並安裝 IronPDF 套件。 安裝後,我們可以開始使用IronPDF。

程式碼撰寫以創建和儲存 PDF 文件

首先,在Form1.cs類別中編寫兩個方法:Save_ClickgetFilePath。 這些方法一起使用,將文字框的內容保存為 PDF 檔案,使用 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
$vbLabelText   $csharpLabel

以下是此方法的逐步分解說明:

  1. 這個方法呼叫getFilePath方法,以取得將儲存 PDF 檔案的檔案路徑。

  2. 如果檔案路徑不為空或 null,則該方法繼續保存 PDF 檔案。

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

  4. 該方法然後使用RenderHtmlAsPdf 方法ChromePdfRenderer類將文本框pdfContent的HTML內容轉換為PDF文檔。 這個 PDF 文件被分配給 PdfDocument Variable

  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 "";
}
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 Forms 程式庫的一部分,提供對話框讓使用者選擇將 PDF 文件儲存的檔案路徑。

  2. 該方法設置 SaveFileDialog 物件的幾個屬性以自訂其行為。 InitialDirectory屬性設置對話框首次打開時的目錄。 Title 屬性設置對話框的標題。 CheckPathExists 屬性指定對話方塊是否應檢查指定的路徑是否存在。 DefaultExt屬性設置文件類型的默認文件擴展名。 Filter 屬性設定在對話方塊中顯示的檔案類型篩選。 FilterIndex屬性設定要顯示的預設篩選。 最後,RestoreDirectory屬性指定對話方塊是否應在關閉前恢復當前目錄。

  3. 此方法通过调用 ShowDialog 方法顯示 SaveFileDialog。 此方法顯示對話框並返回一個DialogResult值,以指示使用者是按下「確定」按鈕或取消按鈕。

  4. 如果使用者點擊「確定」按鈕,該方法將透過訪問SaveFileDialogFileName屬性,返回使用者選擇的檔案路徑。

  5. 如果使用者點擊「取消」按鈕或關閉對話框,該方法將返回一個空字串。

    讓我們運行項目來查看輸出。 運行該專案,以下表單將會開啟。

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

    運行 Windows Forms 專案

    輸入您的 PDF 內容,然後按如下所示點擊 "Save" 按鈕。

    如何在 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合併範例代碼分割 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