跳過到頁腳內容
使用IRONPDF

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

本文將探討如何使用 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 Visual Studio 2022

  2. 在起始頁點選"建立新專案",或前往"檔案">"新建">"專案"。
  3. 在"建立新專案"對話方塊中,選擇"Windows 窗體應用程式"或"Windows 窗體應用程式 (.NET Framework)",如下圖所示。

    如何在 C# 中儲存 PDF 檔案(入門教學),圖 2:新窗體應用程式 新表格應用程式

  4. 輸入項目名稱並選擇儲存位置。

    如何在 C# 中儲存 PDF 檔案(入門教學),圖 3:專案位置 專案地點

  5. 選擇 .NET Framework。 從下拉式選單中選擇 .NET 7.0。
  6. 點選"創建"按鈕。

    如何在 C# 中保存 PDF 文件(入門教程),圖 4:附加信息 附加資訊

  7. Visual Studio 將為您建立一個新的 C# Windows 窗體應用程式項目,並在專案中新增一個名為"Form1"的預設窗體,如下所示。

    如何在 C# 中儲存 PDF 檔案(入門教學),圖 5:Form1 項目 Form1項目

就是這樣! 現在我們將開始使用設計器建立 Windows 窗體應用程序,新增用於建立和保存 PDF 文件檔案的控制項和功能。

步驟二:設計表單

您可以依照自己的喜好設計表格。 本教學將透過新增兩個標籤、一個富文本框和兩個按鈕來創建一個極簡設計。

如何在 C# 中儲存 PDF 檔案(入門教學),圖 6:為表單新增按鈕 在表單中新增按鈕

步驟 3:安裝 IronPDF

下一步是將 IronPDF 安裝到本項目中,以使用其豐富的功能。

IronPDF 可以透過 Visual Studio 中的 NuGet 套件管理器進行安裝。 您可以依序選擇"工具" > "NuGet 套件管理器" > "套件管理器控制台"來存取 NuGet 套件管理器控制台。

輸入以下指令並按下回車鍵:

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類別的新實例。 這是一個函式庫,它提供了一種使用GoogleChrome瀏覽器引擎將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 窗體項目 運行 Windows Forms 項目

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

如何在 C# 中儲存 PDF 檔案(入門教學),圖 8:儲存對話框 儲存對話框

已產生以下PDF文件。

如何在 C# 中儲存 PDF 文件(入門教學),圖 9:已建立的 PDF 文件 已建立 PDF 文件

IronPDF 提供了一種簡單的方法,可以使用ChromePdfRenderer類和SaveFileDialog對話框將 HTML 內容轉換為 PDF 文件,並將其儲存到使用者選擇的文件路徑。

結論

從 Windows 窗體應用程式儲存 PDF 檔案是一個常見的需求,IronPDF 提供了一種簡單易用且靈活的方法來完成此任務。 本文示範如何在 C# Windows Forms 應用程式中使用 IronPDF 建立、新增內容和儲存檔案。 借助 IronPDF,開發人員只需幾行程式碼即可從其應用程式產生高品質的 PDF 文件。

IronPDF 提供一系列功能,例如HTML 轉 PDF 轉換教學、PDF合併範例程式碼分割 PDF 頁面指南提取文字和圖像方法等等。 IronPDF 可免費用於開發,並根據商業許可提供免費試用,讓開發人員在商業專案中使用,並包含專門的支援和更新。

此外,IronPDF 是Iron Suite的一部分,Iron Suite 是一套 .NET 軟體元件,其中包括以下程式庫:

購買全套 Iron Suite 產品是一種經濟實惠的解決方案,因為您只需支付兩件產品的價格即可獲得全部五件產品。

常見問題解答

如何在 C# Windows Forms 應用程式中儲存 PDF 檔案?

您可以使用 IronPDF 在 C# Windows Forms 應用程式中儲存 PDF 檔案,方法是設定一個具有文字方塊和按鈕等控制項的表單,並實作 Save_Click 方法,以使用 ChromePdfRenderer 類將內容渲染並儲存為 PDF。

使用 C# 設定 Windows Forms 應用程式以儲存 PDF 需要哪些步驟?

若要設定儲存 PDF 的 Windows Forms 應用程式,請在 Visual Studio 中建立新專案,新增必要的控制項,例如標籤和豐富的文字方塊,並透過 NuGet 套件管理員安裝 IronPDF 以利用其 PDF 渲染功能。

如何用 C# 將 HTML 內容轉換成 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法在 C# 中將 HTML 內容轉換為 PDF,該方法允許您接收 HTML 字串並將其直接渲染為 PDF 文件。

Save_Click 方法在 PDF 生成中的作用是什麼?

Save_Click 方法作為應用程式中的事件處理器,負責擷取按鈕的點擊事件,以啟動使用 IronPDF 的渲染類別將文字方塊內容渲染為 PDF 檔案的流程。

如何在 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,包括桌面、網頁和跨平台專案類型。使用 .NET 10 建構可提供更快的執行時效能、存取現代 C# 增強功能,以及與平台功能更緊密的整合等改進,有助於透過 IronPDF 的 RenderHtmlAsPdfSaveAs 方法更有效率地建立和儲存 PDF。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。