跳過到頁腳內容
使用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. 如果使用者按一下"確定"按鈕,該方法將透過存取 @@--CODE-25965--@@ 的 @@--CODE-25964--@@ 屬性傳回使用者選擇的檔案路徑。
  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 檔案?

您可以在 C# Windows Forms 應用程式中透過 IronPDF 儲存 PDF 檔案,設置帶有文本框和按鈕等控制項的表單,並實現 Save_Click 方法,使用 ChromePdfRenderer 類渲染並儲存內容為 PDF。

設置 Windows Forms 應用程式以使用 C# 儲存 PDF 涉及哪些步驟?

為了設置 Windows Forms 應用程式來儲存 PDF,可以在 Visual Studio 中創建新專案,添加必要的控制項如標籤和富文本框,並透過 NuGet 套件管理器安裝 IronPDF 來利用其 PDF 渲染功能。

如何在 C# 中將 HTML 內容轉換為 PDF?

您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 內容轉換為 PDF,允許您將 HTML 字串直接渲染成 PDF 文檔。

Save_Click 方法在 PDF 生成上下文中的角色是什麼?

Save_Click 方法在應用程式中作為事件處理器,負責捕捉按鈕的點擊事件,以開始將文本框內容渲染為 PDF 檔案的過程,使用 IronPDF 的渲染類。

如何在 C# 應用程式中提示用戶選擇儲存 PDF 的檔案路徑?

在 C# 應用程式中,您可以使用 SaveFileDialog 類提示用戶選擇儲存 PDF 的檔案路徑,它允許您設置一個用於文件選擇的介面並返回選擇的路徑以儲存渲染的 PDF。

IronPDF 提供哪些進階功能來操控 PDF?

IronPDF 提供進階功能,如 HTML 到 PDF 轉換、PDF 合併、拆分 PDF 頁面,以及提取文本和圖像,提供了全面的 PDF 操控工具套裝,適用於 .NET 應用程式。

在商業專案中使用 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 機器人,結合科技與創意的樂趣。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我