跳過到頁腳內容
使用IRONPDF

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

本文將探討如何使用IronPDF從Windows Forms應用程式或任何.NET應用程式保存PDF文件。

The IronPDF Library是.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

  1. 在啟動頁面上點擊“創建新專案”,或前往“文件”>“新建”>“專案”。
  2. 在“創建新專案”對話框中,選擇“Windows Forms App”或“Windows Forms App (.NET Framework)”,如圖所示。

如何用C#保存PDF文件(初學者教程),圖2:新Forms應用程式 新Forms應用程式

  1. 為您的專案輸入名稱並選擇儲存位置。

如何用C#保存PDF文件(初學者教程), 圖3:專案位置 專案位置

  1. 選擇.NET Framework。 從下拉菜單中選擇.NET 7.0。
  2. 點擊創建按鈕。

如何用C#保存PDF文件(初學者教程),圖4:附加信息 附加信息

  1. Visual Studio將為您創建一個新的C# Windows Forms應用程式專案,並默認添加一個名為“Form1”的表單到專案中,如下圖所示。

如何用C#保存PDF文件(初學者教程),圖5:Form1專案 Form1專案

完成了! 現在我們將開始使用設計器構建Windows Forms應用程式,添加控件和功能以創建和保存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(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類的新實例。 這是個提供將HTML內容轉換成PDF文檔的庫,使用Google Chrome瀏覽器引擎。
  4. 方法然後使用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 Forms專案 運行Windows Forms專案

輸入您的PDF內容並點擊“Save”按鈕,如下圖所示。

如何用C#保存PDF文件(初學者教程),圖8:保存對話框 保存對話框

創建了如下PDF文件。

如何用C#保存PDF文件(初學者教程),圖9:創建的PDF文件 創建的PDF文件

IronPDF提供了一種簡便的方法,將HTML內容轉換為PDF文檔並用ChromePdfRenderer類SaveFileDialog對話框將其保存到用戶選擇的文件路徑。

結論

從Windows Forms應用程式中保存PDF文件是常見需求,IronPDF提供了一個易於使用並且靈活的方法來完成這項任務。 這篇文章演示了如何使用IronPDF在C# Windows Forms應用程式中創建、添加內容和保存文件。 使用IronPDF,開發人員可以僅用幾行代碼從他們的應用程式生成高質量的PDF文件。

IronPDF offers a range of features such as HTML to PDF Conversion Tutorial, PDF Merging Example Code, Splitting PDF Pages Guide, and Extracting Text and Images How-to, and more. IronPDF is free for development and available under a Commercial License with a Free Trial, which allows developers to use it in commercial projects and includes dedicated support and updates.

此外,IronPDF是Iron Suite的一部分,這是一個.NET軟件組件組合,包含以下庫:

購買完整的Iron Suite是一個具成本效益的方案,因為您可以以兩個產品的價格獲得全部五個產品。

常見問題解答

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

您可以使用 IronPDF 在 C# Windows 窗體應用程式中儲存 PDF 文件,方法是設定一個包含文字方塊和按鈕等控制項的窗體,並實作Save_Click方法,使用ChromePdfRenderer類別將內容渲染並儲存為 PDF。

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

若要設定用於儲存 PDF 的 Windows 窗體應用程序,請在 Visual Studio 中建立新項目,請新增必要的控制項(例如標籤和富文本框),並透過 NuGet 套件管理器安裝 IronPDF 以利用其 PDF 渲染功能。

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

您可以使用 IronPDF 的RenderHtmlAsPdf方法將 HTML 內容轉換為 C# 中的 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,包括桌面、Web 和跨平台專案類型。使用 .NET 10 建置可帶來許多改進,例如更快的執行時間效能、對現代 C# 增強功能的存取以及與平台功能的更緊密整合,這些改進有助於透過 IronPDF 的RenderHtmlAsPdfSaveAs方法更有效率地建立和保存 PDF 檔案。

Curtis Chau
技術作家

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

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