跳過到頁腳內容
使用IRONPDF

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

本文將探討如何使用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 App"或"Windows Forms App (.NET Framework)",如下所示。

    如何在C#中保存PDF檔案(初學者教程),圖2:新Forms應用程式 新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檔案

要開始流程,請在getFilePath。 這些方法用於將文本框的內容作為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(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!");
    }
}
$vbLabelText   $csharpLabel

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

  1. 方法調用getFilePath方法以獲取保存PDF檔案的文件路徑。
  2. 如果文件路徑不為空或空值,則方法繼續保存PDF檔案。
  3. 方法創建一個新的ChromePdfRenderer類別實例。 這是一個庫,提供將HTML內容轉換為PDF文檔的方法,使用Google Chrome瀏覽器引擎。
  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;
}
$vbLabelText   $csharpLabel

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

  1. 方法創建一個新的SaveFileDialog類實例。 該類是Windows Forms程式庫的一部分,提供一個對話框,允許用戶選擇保存PDF檔案的文件路徑。
  2. 方法設置SaveFileDialog對象的幾個屬性以自定義其行為。 InitialDirectory屬性設定對話框首次打開的目錄。 Title屬性設定對話框的標題。 CheckPathExists屬性指定對話框是否應檢查指定的路徑是否存在。 DefaultExt屬性設定文件類型的默認文件擴展名。 Filter屬性設置對話框中顯示的文件類型篩選器。 FilterIndex屬性設置要顯示的默認篩選器。 最後,RestoreDirectory屬性指定對話框在關閉前是否應恢復當前目錄。
  3. 方法通過調用其SaveFileDialog。 此方法顯示對話框,並返回一個DialogResult值,表示用戶點擊"OK"按鈕或取消按鈕。
  4. 如果用戶點擊"OK"按鈕,則方法通過訪問FileName屬性來返回用戶選擇的文件路徑。
  5. 如果用戶點擊"取消"按鈕或關閉對話框,方法返回空字串。

讓我們運行專案並查看輸出。 運行專案,將開啟以下表單。

如何在C#中保存PDF檔案(初學者教程),圖7:運行Windows Forms專案 運行Windows Forms專案

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

如何在C#中保存PDF檔案(初學者教程),圖8:保存對話框 保存對話框

創建以下PDF。

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

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

結論

從Windows Forms應用程式保存PDF檔案是一個常見需求,IronPDF提供了一種簡單易用且靈活的方法來完成此任務。 本文展示了如何使用IronPDF在C# Windows Forms應用程式中創建、添加內容和保存文件。 使用IronPDF,開發者可以僅用幾行代碼從其應用程式中生成高品質的PDF檔案。

IronPDF提供了一系列功能,如HTML到PDF轉換教程,PDF 合併示例代碼分割PDF頁面指南,以及提取文本和圖像的指南,等等。 IronPDF在開發過程中免費提供,並可在商業許可證下與免費試用一起使用,允許開發者在商業專案中使用它,並包含專用支援和更新。

此外,IronPDF是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 機器人,結合科技與創意的樂趣。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me