使用 IRONPDF

全面指南:使用IronPDF輕鬆生成和操作PDF的C# PDF生成器

生成 PDF 文件是 C# 開發人員常見且通常必不可少的需求。 無論您需要製作發票、詳細的商業報告、轉換網頁內容或管理各種其他商業文件,一個可靠的C# PDF生成器都是至關重要的。 許多開發人員尋找 .NET 函式庫,不僅簡化這些任務,還提供強大的功能,如以高保真度將 HTML 轉換為 PDF、編輯現有的 PDF,或以程式方式從頭開始創建新的 PDF。

如果您正在尋找這樣一個功能強大且易於使用的解決方案,您來對地方了。 本指南專注於IronPDF,這是一個領先的 .NET 程式庫,專門設計用於簡化在 C# 中的 PDF 生成和操作。 我們將引導您了解IronPDF如何解決常見的PDF生成需求,提供實用教程讓您快速上手,並討論為什麼IronPDF在您的開發工具集中脫穎而出。

我們將涵蓋:

  • 了解 C# PDF 生成的概況。
  • 為什麼 IronPDF 是您 C# PDF 任務的絕佳選擇。
  • 在您的 C# 專案中設定 IronPDF(Windows Forms 範例)。
  • 從 HTML 內容和即時 URL 生成 PDF。
  • 使 IronPDF 成為高效且強大的C# PDF 函式庫的主要功能特點。

為什麼選擇IronPDF作為您的C# PDF生成器?

在評估C# PDF 程式庫時,開發者通常會優先考量易用性、渲染準確性(尤其是 HTML 到 PDF 的轉換)、全面的功能集和整體效能。 IronPDF 的設計可在以下領域表現出色:

  • 簡單性和開發者生產力:正如您在本教程中將看到的,IronPDF 能夠讓您用非常少量的 C# 代碼生成和操作 PDF 文檔。 它抽象掉了在其他 PDF 操作方法或更冗长的庫中经常遇到的底层复杂性。
  • 像素完美的 HTML 到 PDF 渲染: IronPDF 的一個突出功能是使用嵌入式 Chrome 渲染引擎。這確保 HTML、CSS 和 JavaScript 以現代網頁瀏覽器中的相同準確性和保真度進行渲染。 這對從網頁內容生成專業外觀的文檔至關重要,這是一個常見的挑戰,一些適用於 C# 的免費 PDF 庫可能無法達到。
  • 全面的 PDF 功能: IronPDF 不僅僅是一個 PDF 創建工具。 這是一個完整的C# PDF 工具,支持廣泛的操作:

    • 編輯現有的 PDF 文件

    • 合併和分割PDF文件

    • 添加頁眉、頁腳、水印和頁碼

    • 填寫及閱讀 PDF 表單

    • 使用密碼和權限來保護文件
  • 數位簽署 PDF
  • 出色的支援和最新的文件:作為商業支持的庫,IronPDF 提供專業的技術支援並維護廣泛且清晰的文件,使開發人員能夠快速且高效地實施解決方案。
  • 跨平台相容性: 使用 IronPDF 開發和部署應用程序,適用於 Windows、Linux、macOS、Docker 和 Azure,鎖定 .NET(Core、Standard、Framework)。

    現在,讓我們深入了解如何在 C# Windows Forms 應用程式中使用 IronPDF 生成 PDF。

步驟 1:為 C# PDF 生成設定您的 Visual Studio 專案

第一步是創建一個 Visual Studio 專案。 在本教程中,我們將使用 Windows Forms App 模板,但 IronPDF 可無縫運作於 Web 應用程序(ASP.NET)、控制台應用程序、WPF 等。

打開 Visual Studio。

打開 Visual Studio C# 專案

按一下「建立新專案」。

在 Visual Studio 中創建新項目以用於 C# PDF 生成器

從模板中選擇「Windows Forms App (.NET Framework 或 .NET Core)」,然後點擊「下一步」。 以下視窗將會出現。 命名您的專案(例如,MyCSharpPdfGenerator)。

命名用於 PDF 生成的 C# 專案

命名專案

之後,點擊「下一步」。 從下拉選單中選擇您想要的 .NET Framework(IronPDF 支援多種版本)。

選擇 .NET Framework 用於 IronPDF C# 專案

選擇 .NET Framework

點擊「建立」按鈕。 專案已完成創建,準備進行下一步。

為 C# PDF 生成建立的 Visual Studio 專案

步驟 2:安裝 IronPDF C# 庫 - 生成 PDF 的關鍵

IronPDF可以通過NuGet輕鬆添加到您的專案中。 這是確保您擁有最新版本和所有必要依賴項的建議方法。

選項 1:套件管理控制台(最快)

在 Visual Studio 中,依次選擇工具 > NuGet 套件管理員 > 套件管理員主控台。 然後,輸入以下命令並按 Enter:

Install-Package IronPdf
Install-Package IronPdf
SHELL

選項 2:NuGet 封裝管理器圖形介面

  1. 在方案總管中右鍵點擊您的專案,然後選擇「管理 NuGet 套件...」

  2. 點擊「瀏覽」選項卡並搜尋「IronPdf」。

  3. 從搜尋結果中選擇IronPdf套件並點擊“安裝”。

    通過 NuGet 套件管理器 GUI 安裝 IronPDF C# 庫

選項 3:手動安裝(下載 DLL)

或者,您可以直接從IronPDF網站下載IronPDF DLL

  1. 下載並將 DLL 解壓縮到合適的位置(例如,您解決方案目錄中的「Libs」資料夾)。

  2. 在 Visual Studio 解決方案總管中,右鍵點擊「引用」(針對 .NET Framework 專案)或「依賴項」(針對 .NET Core/5+ 專案),然後選擇「添加引用...」或「添加專案引用...」,再選擇「瀏覽」。

  3. 導航並選擇IronPdf.dll

步驟 3:設計一個簡單的 Windows 表單介面(選擇性)

在本教程中,我們將創建一個基本的用戶界面來觸發 PDF 生成。 如果您正在建立一個網頁或控制台應用程式,您將把IronPDF邏輯直接整合到您的控制器、服務或類別中。

前往 Visual Studio 中的工具箱(檢視 > 工具箱)。 將以下控制項拖放到您的 Form1 設計介面上:

  • 一個 Label(例如,給您的應用程式命名為 "C# PDF Generator Demo")。
  • 一個用於輸入 HTML/文本的RichTextBox(命名為PdfText)。
  • 一個TextBox(命名為URL)用於輸入 URL。
  • 兩個Button控制項。

    • 將第一個按鈕的文本設置為「從文本生成 PDF」(將其命名為GeneratePDFFromTextButton)。

    • 將第二個按鈕的文字設置為「Generate PDF From URL」(命名為GeneratePDFFromURLButton)。

    為 C# PDF 生成器應用程式設計 Windows 窗體

步驟 4:撰寫 C\# 程式碼從文本/HTML 生成 PDF

現在,讓我們添加C#邏輯。 在表單設計工具中雙擊 "Generate PDF From Text" 按鈕 (GeneratePDFFromTextButton)。 這將在您的 Form1.cs 文件中創建一個事件處理程序方法。

首先,在您的Form1.cs文件的顶部添加IronPDF命名空間:

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

然後,實現按鈕的click事件處理器。 這段程式碼將從RichTextBox中擷取文字(可以是純文字或HTML)並轉換成PDF文件。

private void GeneratePDFFromTextButton_Click(object sender, EventArgs e)
{
    // It's recommended to set your license key once at application startup.
    // IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 
    // If no key is set, IronPDF will watermark PDFs after a trial period.

    // Use SaveFileDialog to let the user choose where to save the PDF
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Default to My Documents
    saveFileDialog1.Title = "Save PDF File As";
    saveFileDialog1.DefaultExt = "pdf";
    saveFileDialog1.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    saveFileDialog1.FilterIndex = 1; // Start with PDF files selected
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filename = saveFileDialog1.FileName;

        // The core of PDF generation from HTML/Text using IronPDF
        // IronPDF's ChromePdfRenderer accurately renders HTML, CSS, and JavaScript.
        var renderer = new ChromePdfRenderer();

        // The RenderHtmlAsPdf method converts an HTML string to a PDF document.
        // This is incredibly powerful for generating dynamic reports, invoices, tickets, etc.
        // from HTML templates.
        using (var pdfDocument = renderer.RenderHtmlAsPdf(PdfText.Text))
        {
            pdfDocument.SaveAs(filename);
        }

        MessageBox.Show("PDF Generated Successfully at: " + filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
private void GeneratePDFFromTextButton_Click(object sender, EventArgs e)
{
    // It's recommended to set your license key once at application startup.
    // IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 
    // If no key is set, IronPDF will watermark PDFs after a trial period.

    // Use SaveFileDialog to let the user choose where to save the PDF
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Default to My Documents
    saveFileDialog1.Title = "Save PDF File As";
    saveFileDialog1.DefaultExt = "pdf";
    saveFileDialog1.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    saveFileDialog1.FilterIndex = 1; // Start with PDF files selected
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filename = saveFileDialog1.FileName;

        // The core of PDF generation from HTML/Text using IronPDF
        // IronPDF's ChromePdfRenderer accurately renders HTML, CSS, and JavaScript.
        var renderer = new ChromePdfRenderer();

        // The RenderHtmlAsPdf method converts an HTML string to a PDF document.
        // This is incredibly powerful for generating dynamic reports, invoices, tickets, etc.
        // from HTML templates.
        using (var pdfDocument = renderer.RenderHtmlAsPdf(PdfText.Text))
        {
            pdfDocument.SaveAs(filename);
        }

        MessageBox.Show("PDF Generated Successfully at: " + filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}
Private Sub GeneratePDFFromTextButton_Click(ByVal sender As Object, ByVal e As EventArgs)
	' It's recommended to set your license key once at application startup.
	' IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 
	' If no key is set, IronPDF will watermark PDFs after a trial period.

	' Use SaveFileDialog to let the user choose where to save the PDF
	Dim saveFileDialog1 As New SaveFileDialog()
	saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Default to My Documents
	saveFileDialog1.Title = "Save PDF File As"
	saveFileDialog1.DefaultExt = "pdf"
	saveFileDialog1.Filter = "PDF files (*.pdf) *.pdf All files (*.*) *.*"
	saveFileDialog1.FilterIndex = 1 ' Start with PDF files selected
	saveFileDialog1.RestoreDirectory = True

	If saveFileDialog1.ShowDialog() = DialogResult.OK Then
		Dim filename As String = saveFileDialog1.FileName

		' The core of PDF generation from HTML/Text using IronPDF
		' IronPDF's ChromePdfRenderer accurately renders HTML, CSS, and JavaScript.
		Dim renderer = New ChromePdfRenderer()

		' The RenderHtmlAsPdf method converts an HTML string to a PDF document.
		' This is incredibly powerful for generating dynamic reports, invoices, tickets, etc.
		' from HTML templates.
		Using pdfDocument = renderer.RenderHtmlAsPdf(PdfText.Text)
			pdfDocument.SaveAs(filename)
		End Using

		MessageBox.Show("PDF Generated Successfully at: " & filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
	End If
End Sub
$vbLabelText   $csharpLabel

C# PDF 生成代碼的說明:

  • IronPdf.License.LicenseKey:設置您的IronPDF許可證密鑰是一個好的做法。 如果您有一個,請取消註釋該行並將"YourLicenseKey..."替換為您的實際密鑰。 IronPDF 在沒有授權密鑰的情況下也可以運行,但在試用期結束後,文件會有浮水印。
  • SaveFileDialog:這提供了一個標準的 Windows 對話框,讓使用者選擇 PDF 的保存位置和檔名。
  • ChromePdfRenderer:這是IronPDF將HTML轉換為PDF功能的核心。 它使用嵌入式Chromium引擎以確保最高的保真度。
  • RenderHtmlAsPdf(PdfText.Text):這個單一方法調用會將來自您的RichTextBox(可以是富HTML格式)的字串內容轉換為PDF文檔物件。
  • SaveAs(filename):此方法將生成的 PDF 文件保存到使用者指定的路徑。
  • 使用using語句處理pdfDocument可以確保資源被正確管理。

    注意,IronPDF 將潛在的複雜任務(如 HTML 到 PDF 的轉換)簡化為幾行關鍵代碼。 這對需要快速且可靠地生成 PDF C#的開發人員來說是一個顯著的優勢。

執行專案並從文字/HTML生成您的第一個 PDF

Ctrl + F5(或點擊開始按鈕)以執行您的項目。 Windows Form 應用程式將會出現。

運行 C\# PDF 生成器應用程式

在富文本框中輸入一些HTML內容。 例如:

<h1>My First C# PDF Document</h1>
<p>This PDF was generated using <strong>IronPDF</strong> in a C# application.</p>
<p>IronPDF makes it very easy to convert HTML content, including styles and images, into professional PDF files.</p>
<ul>
    <li>Easy to use</li>
    <li>Accurate rendering</li>
    <li>Feature-rich</li>
</ul>
<h1>My First C# PDF Document</h1>
<p>This PDF was generated using <strong>IronPDF</strong> in a C# application.</p>
<p>IronPDF makes it very easy to convert HTML content, including styles and images, into professional PDF files.</p>
<ul>
    <li>Easy to use</li>
    <li>Accurate rendering</li>
    <li>Feature-rich</li>
</ul>
HTML

在 C# PDF 產生器應用程式中輸入 HTML

點擊「從文本生成 PDF」按鈕。 將會顯示另存為對話框。 選擇位置和檔名,然後點擊「儲存」。

驗證 PDF 輸出(來自文本/HTML)

導航至您儲存 PDF 的位置並開啟它。 您應該可以在 PDF 文件中準確地查看您的 HTML 內容。

使用 IronPDF C# 從 HTML 字串生成的輸出 PDF 文件

步骤 5:编写 C# 代码从 URL 生成 PDF

從即時網頁生成 PDF 是另一個常見的需求。 IronPDF 讓這變得同樣簡單。 在表單設計器中雙擊「Generate PDF FROM URL」按鈕(GeneratePDFFromURLButton)以創建其點擊事件處理程序。

添加以下 C# 代碼:

private void GeneratePDFFromURLButton_Click(object sender, EventArgs e)
{
    // IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 

    if (string.IsNullOrWhiteSpace(URL.Text))
    {
        MessageBox.Show("Please enter a valid URL.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }

    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    saveFileDialog1.Title = "Save PDF From URL As";
    saveFileDialog1.DefaultExt = "pdf";
    saveFileDialog1.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    saveFileDialog1.FilterIndex = 1;
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filename = saveFileDialog1.FileName;
        try
        {
            var renderer = new ChromePdfRenderer();
            // RenderUrlAsPdf fetches the content from the URL and converts it to PDF.
            // This is excellent for archiving web pages or creating PDFs from online reports.
            using (var pdfDocument = renderer.RenderUrlAsPdf(URL.Text))
            {
                pdfDocument.SaveAs(filename);
            }
            MessageBox.Show("PDF from URL Generated Successfully at: " + filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error generating PDF from URL: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
private void GeneratePDFFromURLButton_Click(object sender, EventArgs e)
{
    // IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 

    if (string.IsNullOrWhiteSpace(URL.Text))
    {
        MessageBox.Show("Please enter a valid URL.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }

    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    saveFileDialog1.Title = "Save PDF From URL As";
    saveFileDialog1.DefaultExt = "pdf";
    saveFileDialog1.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    saveFileDialog1.FilterIndex = 1;
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filename = saveFileDialog1.FileName;
        try
        {
            var renderer = new ChromePdfRenderer();
            // RenderUrlAsPdf fetches the content from the URL and converts it to PDF.
            // This is excellent for archiving web pages or creating PDFs from online reports.
            using (var pdfDocument = renderer.RenderUrlAsPdf(URL.Text))
            {
                pdfDocument.SaveAs(filename);
            }
            MessageBox.Show("PDF from URL Generated Successfully at: " + filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error generating PDF from URL: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
Private Sub GeneratePDFFromURLButton_Click(ByVal sender As Object, ByVal e As EventArgs)
	' IronPdf.License.LicenseKey = "YourLicenseKey-GetYourKeyFromIronPdf.com"; 

	If String.IsNullOrWhiteSpace(URL.Text) Then
		MessageBox.Show("Please enter a valid URL.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
		Return
	End If

	Dim saveFileDialog1 As New SaveFileDialog()
	saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
	saveFileDialog1.Title = "Save PDF From URL As"
	saveFileDialog1.DefaultExt = "pdf"
	saveFileDialog1.Filter = "PDF files (*.pdf) *.pdf All files (*.*) *.*"
	saveFileDialog1.FilterIndex = 1
	saveFileDialog1.RestoreDirectory = True

	If saveFileDialog1.ShowDialog() = DialogResult.OK Then
		Dim filename As String = saveFileDialog1.FileName
		Try
			Dim renderer = New ChromePdfRenderer()
			' RenderUrlAsPdf fetches the content from the URL and converts it to PDF.
			' This is excellent for archiving web pages or creating PDFs from online reports.
			Using pdfDocument = renderer.RenderUrlAsPdf(URL.Text)
				pdfDocument.SaveAs(filename)
			End Using
			MessageBox.Show("PDF from URL Generated Successfully at: " & filename, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
		Catch ex As Exception
			MessageBox.Show("Error generating PDF from URL: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
		End Try
	End If
End Sub
$vbLabelText   $csharpLabel

說明:

  • URL.Text:這將從表單上的TextBox控制項中獲取 URL 字串。
  • RenderUrlAsPdf(URL.Text):這個強大的IronPDF方法會導航到給定的URL,渲染其內容(包括HTML、CSS、JavaScript和圖像),並將其轉換為PDF文件。
  • 為了提升穩定性,包含了錯誤處理(try-catch),因為可能會發生網絡問題或無效的URL。

運行專案並從 URL 生成 PDF

再次運行您的專案(Ctrl + F5)。 這一次,請在 URL 文本框中輸入完整的 URL(例如,https://ironpdf.com)。

在 C# PDF 生成器應用程式中輸入 URL

點擊「從 URL 生成 PDF」按鈕。 選擇儲存位置和文件名。

驗證 PDF 輸出(來自 URL)

打開生成的 PDF。 您將看到網頁已被忠實地轉換為 PDF 文件,保留了其佈局和內容。

使用 IronPDF 在 C# 中從 URL 生成的輸出 PDF 文件

結論:使用 IronPDF 簡化您的 C# PDF 生成

正如本教學所示,IronPDF 為所有您的C# PDF 生成需求提供了一個非常強大且簡單的解決方案。 無論您是要將包含複雜 CSS 和 JavaScript 的 HTML 頁面轉換,從數據生成動態報告,從實時 URL 創建 PDF,還是在您的 .NET 應用程式中需要強大的 PDF 編輯功能,IronPDF 都能提供必要的工具和性能,以高效完成工作。

當您生成 PDF C#專案時,通常會面臨選擇免費資料庫可能在渲染保真度或功能集上有一些限制,或是需要大量樣板代碼的複雜解決方案。 IronPDF 脫穎而出,作為一個全方位、商業支持的.NET PDF 庫,簡化了開發流程,確保高質量輸出,並提供了一套超越基本 PDF 創建的豐富功能。

準備好體驗在 C# 中生成和操作 PDF 的最佳方式嗎?

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
如何移除 PDF 檔案的密碼
下一個 >
C# 編程生成 PDF 文件
OSZAR »