在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
生成 PDF 文件是 C# 開發人員常見且通常必不可少的需求。 無論您需要製作發票、詳細的商業報告、轉換網頁內容或管理各種其他商業文件,一個可靠的C# PDF生成器都是至關重要的。 許多開發人員尋找 .NET 函式庫,不僅簡化這些任務,還提供強大的功能,如以高保真度將 HTML 轉換為 PDF、編輯現有的 PDF,或以程式方式從頭開始創建新的 PDF。
如果您正在尋找這樣一個功能強大且易於使用的解決方案,您來對地方了。 本指南專注於IronPDF,這是一個領先的 .NET 程式庫,專門設計用於簡化在 C# 中的 PDF 生成和操作。 我們將引導您了解IronPDF如何解決常見的PDF生成需求,提供實用教程讓您快速上手,並討論為什麼IronPDF在您的開發工具集中脫穎而出。
我們將涵蓋:
在評估C# PDF 程式庫時,開發者通常會優先考量易用性、渲染準確性(尤其是 HTML 到 PDF 的轉換)、全面的功能集和整體效能。 IronPDF 的設計可在以下領域表現出色:
全面的 PDF 功能: IronPDF 不僅僅是一個 PDF 創建工具。 這是一個完整的C# PDF 工具,支持廣泛的操作:
編輯現有的 PDF 文件
合併和分割PDF文件
添加頁眉、頁腳、水印和頁碼
填寫及閱讀 PDF 表單
跨平台相容性: 使用 IronPDF 開發和部署應用程序,適用於 Windows、Linux、macOS、Docker 和 Azure,鎖定 .NET(Core、Standard、Framework)。
現在,讓我們深入了解如何在 C# Windows Forms 應用程式中使用 IronPDF 生成 PDF。
第一步是創建一個 Visual Studio 專案。 在本教程中,我們將使用 Windows Forms App 模板,但 IronPDF 可無縫運作於 Web 應用程序(ASP.NET)、控制台應用程序、WPF 等。
打開 Visual Studio。
按一下「建立新專案」。
從模板中選擇「Windows Forms App (.NET Framework 或 .NET Core)」,然後點擊「下一步」。 以下視窗將會出現。 命名您的專案(例如,MyCSharpPdfGenerator
)。
命名專案
之後,點擊「下一步」。 從下拉選單中選擇您想要的 .NET Framework(IronPDF 支援多種版本)。
選擇 .NET Framework
點擊「建立」按鈕。 專案已完成創建,準備進行下一步。
IronPDF可以通過NuGet輕鬆添加到您的專案中。 這是確保您擁有最新版本和所有必要依賴項的建議方法。
在 Visual Studio 中,依次選擇工具 > NuGet 套件管理員 > 套件管理員主控台。 然後,輸入以下命令並按 Enter:
Install-Package IronPdf
Install-Package IronPdf
在方案總管中右鍵點擊您的專案,然後選擇「管理 NuGet 套件...」
點擊「瀏覽」選項卡並搜尋「IronPdf」。
從搜尋結果中選擇IronPdf
套件並點擊“安裝”。
或者,您可以直接從IronPDF網站下載IronPDF DLL。
下載並將 DLL 解壓縮到合適的位置(例如,您解決方案目錄中的「Libs」資料夾)。
在 Visual Studio 解決方案總管中,右鍵點擊「引用」(針對 .NET Framework 專案)或「依賴項」(針對 .NET Core/5+ 專案),然後選擇「添加引用...」或「添加專案引用...」,再選擇「瀏覽」。
IronPdf.dll
。在本教程中,我們將創建一個基本的用戶界面來觸發 PDF 生成。 如果您正在建立一個網頁或控制台應用程式,您將把IronPDF邏輯直接整合到您的控制器、服務或類別中。
前往 Visual Studio 中的工具箱(檢視 > 工具箱)。 將以下控制項拖放到您的 Form1 設計介面上:
Label
(例如,給您的應用程式命名為 "C# PDF Generator Demo")。RichTextBox
(命名為PdfText
)。TextBox
(命名為URL
)用於輸入 URL。兩個Button
控制項。
將第一個按鈕的文本設置為「從文本生成 PDF」(將其命名為GeneratePDFFromTextButton
)。
GeneratePDFFromURLButton
)。現在,讓我們添加C#邏輯。 在表單設計工具中雙擊 "Generate PDF From Text" 按鈕 (GeneratePDFFromTextButton
)。 這將在您的 Form1.cs
文件中創建一個事件處理程序方法。
首先,在您的Form1.cs
文件的顶部添加IronPDF命名空間:
using IronPdf;
using IronPdf;
Imports IronPdf
然後,實現按鈕的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
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#的開發人員來說是一個顯著的優勢。
按 Ctrl + F5
(或點擊開始按鈕)以執行您的項目。 Windows Form 應用程式將會出現。
在富文本框中輸入一些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>
點擊「從文本生成 PDF」按鈕。 將會顯示另存為對話框。 選擇位置和檔名,然後點擊「儲存」。
導航至您儲存 PDF 的位置並開啟它。 您應該可以在 PDF 文件中準確地查看您的 HTML 內容。
從即時網頁生成 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
說明:
URL.Text
:這將從表單上的TextBox
控制項中獲取 URL 字串。RenderUrlAsPdf(URL.Text)
:這個強大的IronPDF方法會導航到給定的URL,渲染其內容(包括HTML、CSS、JavaScript和圖像),並將其轉換為PDF文件。try-catch
),因為可能會發生網絡問題或無效的URL。再次運行您的專案(Ctrl + F5
)。 這一次,請在 URL 文本框中輸入完整的 URL(例如,https://ironpdf.com
)。
點擊「從 URL 生成 PDF」按鈕。 選擇儲存位置和文件名。
打開生成的 PDF。 您將看到網頁已被忠實地轉換為 PDF 文件,保留了其佈局和內容。
正如本教學所示,IronPDF 為所有您的C# PDF 生成需求提供了一個非常強大且簡單的解決方案。 無論您是要將包含複雜 CSS 和 JavaScript 的 HTML 頁面轉換,從數據生成動態報告,從實時 URL 創建 PDF,還是在您的 .NET 應用程式中需要強大的 PDF 編輯功能,IronPDF 都能提供必要的工具和性能,以高效完成工作。
當您生成 PDF C#專案時,通常會面臨選擇免費資料庫可能在渲染保真度或功能集上有一些限制,或是需要大量樣板代碼的複雜解決方案。 IronPDF 脫穎而出,作為一個全方位、商業支持的.NET PDF 庫,簡化了開發流程,確保高質量輸出,並提供了一套超越基本 PDF 創建的豐富功能。
準備好體驗在 C# 中生成和操作 PDF 的最佳方式嗎?
探索 Iron Suite:以更少的費用獲得更多 .NET 工具(Iron Suite 包含多個 .NET 庫,對於處理其他文件格式或任務來說是極具價值的選擇。)
選擇IronPDF,您就是在為C#專案配備領先的PDF生成和操作引擎,節省寶貴的開發時間,並確保每次都能生成專業品質且像素完美的PDF文件。了解更多關於在C#中將HTML轉換為PDF的詳細指南。