在C# .NET中程式庫中製作PDF
使用 IronPDF 的 .NET 函式庫,僅需一行程式碼即可在 C# 中建立 PDF 檔案。此函式庫透過內建的渲染功能與簡易的 Visual Studio 整合,能簡化從 HTML 字串、URL 或表單生成 PDF 的流程。
只要有正確的指引,使用 C# .NET 函式庫製作 PDF 既簡單又高效。 透過 IronPDF,您可以根據應用程式的需求,以簡便的方式建立和編輯 PDF 檔案。 本教學範例展示如何在專案中有效使用該軟體,只需單擊一個按鈕即可建立 PDF!
步驟 1
如何安裝 C# PDF 函式庫 .NET?
進入圖書館主要有兩種方式:
- Download and unpack the [IronPDF Package](https://ironpdf.com/packages/IronPdf.zip) DLL file
- Navigate to [NuGet](https://www.nuget.org/packages/IronPdf) and install the package via Visual Studio.
對於初學 .NET PDF 生成的開發者而言,NuGet 套件管理員提供了最簡便的安裝方式。 它會自動處理依賴項,並確保您使用的是最新的穩定版本。 安裝概覽針對各種開發環境提供了詳細的指引。
我應該選擇哪種安裝方式?
# Use the NuGet package manager to install IronPDF
nuget install IronPdf
# Use the NuGet package manager to install IronPDF
nuget install IronPdf
對於大多數開發者而言,尤其是剛接觸 .NET 開發的新手,建議採用 NuGet 作為主要解決方案。 它能與 Visual Studio 及其他 整合開發環境 (IDE) 無縫整合,使其成為使用 C# 建立 PDF 檔案的理想選擇。 套件管理員會自動處理所有複雜的設定,包括:
哪些是常見的安裝問題?
開發人員在安裝 IronPDF 時,有時會遇到一些常見的挑戰。 故障排除指南涵蓋了大多數情況,但以下是其中最常見的幾種:
為何選擇 NuGet 而非手動安裝?
對於正在學習 HTML 轉 PDF 的開發者而言,NuGet 具備以下幾項優勢:
- 自動更新:自動取得安全性修補程式與新功能
- 版本控制:必要時可輕鬆回滾至先前版本
- 團隊協作:所有開發人員皆使用相同的套件版本
- 建置伺服器相容性:可與 CI/CD 管道無縫整合
- 套件還原:建置時會自動下載缺失的套件
NuGet 套件的文件提供了針對特定情境(例如 Azure 部署或 Docker 容器)的高階設定選項。
操作指南
如何使用 PDF .NET 函式庫?
既然已備妥這些軟體,我們便能生成 PDF 檔案、調整設定、加入自訂文字與圖片,並對 PDF 進行編輯以符合專案需求。 IronPDF 提供全面的功能,可建立新的 PDF 檔案、編輯現有檔案,甚至將各種格式(例如圖片轉為 PDF 或 XML 轉為 PDF)進行轉換。
ChromePdfRenderer 的作用是什麼?
在以下程式碼中,我們使用 C# 表單來示範如何透過 C# .NET 函式庫建立 PDF 檔案。 在這個例子中,我們可以使用 TextBox 來編寫我們自己的文本,然後點擊一個按鈕即可產生 PDF。 類別 ChromePdfRenderer 提供了一種最簡單的方法,可以從不同的來源產生 PDF 文件,包括HTML 字串、網頁 URL或另一個渲染器下的 doc 文件。
ChromePdfRenderer 是 IronPDF 渲染引擎的核心。它採用與 Google Chrome 相同的技術,確保您的 PDF 文件在渲染後的外觀與在現代網頁瀏覽器中的顯示效果完全一致。 這意味著需全面支援:
如何處理 PDF 生成過程中的錯誤?
錯誤處理對於可靠的 PDF 生成至關重要。 IronPDF 提供詳盡的例外處理機制,有助於快速識別問題。 以下是一種具備錯誤處理功能的穩健 PDF 生成方法:
using IronPdf;
using System;
using System.IO;
public class PdfGenerator
{
public static bool CreatePdfSafely(string htmlContent, string outputPath)
{
try
{
var renderer = new ChromePdfRenderer();
// Configure rendering options for better results
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
renderer.RenderingOptions.MarginTop = 20;
renderer.RenderingOptions.MarginBottom = 20;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Generate the PDF
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Ensure directory exists
string directory = Path.GetDirectoryName(outputPath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// Save the PDF
pdf.SaveAs(outputPath);
return true;
}
catch (Exception ex)
{
// Log the error (you can use your preferred logging framework)
Console.WriteLine($"PDF generation failed: {ex.Message}");
return false;
}
}
}
using IronPdf;
using System;
using System.IO;
public class PdfGenerator
{
public static bool CreatePdfSafely(string htmlContent, string outputPath)
{
try
{
var renderer = new ChromePdfRenderer();
// Configure rendering options for better results
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
renderer.RenderingOptions.MarginTop = 20;
renderer.RenderingOptions.MarginBottom = 20;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
// Generate the PDF
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
// Ensure directory exists
string directory = Path.GetDirectoryName(outputPath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
// Save the PDF
pdf.SaveAs(outputPath);
return true;
}
catch (Exception ex)
{
// Log the error (you can use your preferred logging framework)
Console.WriteLine($"PDF generation failed: {ex.Message}");
return false;
}
}
}
Imports IronPdf
Imports System
Imports System.IO
Public Class PdfGenerator
Public Shared Function CreatePdfSafely(htmlContent As String, outputPath As String) As Boolean
Try
Dim renderer As New ChromePdfRenderer()
' Configure rendering options for better results
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait
renderer.RenderingOptions.MarginTop = 20
renderer.RenderingOptions.MarginBottom = 20
renderer.RenderingOptions.PrintHtmlBackgrounds = True
' Generate the PDF
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
' Ensure directory exists
Dim directory As String = Path.GetDirectoryName(outputPath)
If Not Directory.Exists(directory) Then
Directory.CreateDirectory(directory)
End If
' Save the PDF
pdf.SaveAs(outputPath)
Return True
Catch ex As Exception
' Log the error (you can use your preferred logging framework)
Console.WriteLine($"PDF generation failed: {ex.Message}")
Return False
End Try
End Function
End Class
何時該使用 HTML 渲染,何時該直接建立 PDF?
了解何時該使用 HTML 渲染,何時該直接建立 PDF,有助於您選擇正確的方法。 IronPDF 在 HTML 渲染方面表現出色,因為它提供:
HTML 渲染優勢:
- 運用現有的網頁開發技能
- 使用常見的 CSS 進行樣式設定
- 透過視口設定輕鬆實現響應式設計
- 支援 JavaScript 的動態內容
- 快速原型製作與迭代
請在以下情況使用 HTML 渲染:
直接操作 PDF 更適合用於:
- 為現有 PDF 檔案添加註解
- 合併或分割 PDF 檔案
- 套用數位簽章
- 添加浮水印
- 擷取文字與圖片
// C# Program to create PDF from TextBox input using IronPDF
using IronPdf;
using System.Windows.Forms;
namespace readpdf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Event handler for the button click
private void button1_Click(object sender, System.EventArgs e)
{
// Create a ChromePdfRenderer object to convert HTML to PDF
var HtmlLine = new ChromePdfRenderer();
// Retrieve the text from the TextBox
string text = textBox1.Text;
// Render the HTML as a PDF, wrapping the text in an <h1> tag
using var pdf = HtmlLine.RenderHtmlAsPdf("<h1>" + text + "</h1>");
// Save the PDF to a file called "custom.pdf"
pdf.SaveAs("custom.pdf");
// Show a confirmation message to the user
MessageBox.Show("Done!");
}
}
}
// C# Program to create PDF from TextBox input using IronPDF
using IronPdf;
using System.Windows.Forms;
namespace readpdf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Event handler for the button click
private void button1_Click(object sender, System.EventArgs e)
{
// Create a ChromePdfRenderer object to convert HTML to PDF
var HtmlLine = new ChromePdfRenderer();
// Retrieve the text from the TextBox
string text = textBox1.Text;
// Render the HTML as a PDF, wrapping the text in an <h1> tag
using var pdf = HtmlLine.RenderHtmlAsPdf("<h1>" + text + "</h1>");
// Save the PDF to a file called "custom.pdf"
pdf.SaveAs("custom.pdf");
// Show a confirmation message to the user
MessageBox.Show("Done!");
}
}
}
' C# Program to create PDF from TextBox input using IronPDF
Imports IronPdf
Imports System.Windows.Forms
Namespace readpdf
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
' Event handler for the button click
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Create a ChromePdfRenderer object to convert HTML to PDF
Dim HtmlLine = New ChromePdfRenderer()
' Retrieve the text from the TextBox
'INSTANT VB NOTE: The variable text was renamed since Visual Basic does not handle local variables named the same as class members well:
Dim text_Conflict As String = textBox1.Text
' Render the HTML as a PDF, wrapping the text in an <h1> tag
Dim pdf = HtmlLine.RenderHtmlAsPdf("<h1>" & text_Conflict & "</h1>")
' Save the PDF to a file called "custom.pdf"
pdf.SaveAs("custom.pdf")
' Show a confirmation message to the user
MessageBox.Show("Done!")
End Sub
End Class
End Namespace
如何將 C# 表單轉換為 PDF?
我們使用 C# Windows Forms 應用程式,向您展示搭配自訂文字的完美輸出效果。 只需按一下,TextBox 中的文字即可轉換為自訂 PDF。 這僅需一行程式碼即可實現,且易於理解。 若需處理更複雜的場景,您可探索 MVC 應用程式的 CSHTML 轉 PDF 功能,或現代網頁應用程式的 Blazor PDF 生成功能。
為什麼這種單擊方法有效?
單擊式方法之所以能有效運作,是因為 IronPDF 會在內部處理所有複雜的渲染工作。 當您呼叫 RenderHtmlAsPdf() 時,IronPDF:
- 初始化 Chrome 引擎:採用與 Chrome 瀏覽器相同的渲染引擎
- 處理 HTML:解析您的 HTML 字串並套用任何內嵌樣式
- 渲染為 PDF:將渲染後的內容轉換為 PDF 格式
- 優化輸出:進行壓縮與優化
這種簡易性使 IronPDF 成為需要快速產出成果的快速開發情境中的完美選擇。 該函式庫會自動處理字型管理、圖片嵌入,甚至 JavaScript 執行。
我可以匯出哪些檔案格式?
雖然 PDF 是主要的輸出格式,但 IronPDF 支援多種匯出與轉換選項:
- PDF 轉圖像:將 PDF 轉換為 PNG、JPEG 或 TIFF
- PDF 轉 HTML:將 PDF 檔案匯出為 HTML 格式
- 符合 PDF/A 標準:建立用於長期儲存的歸檔 PDF 檔案
- PDF/UA:為身心障礙使用者生成無障礙 PDF 檔案
- Memory Streams:將資料匯出至記憶體,適用於網頁應用程式
此外,IronPDF 支援從多種來源匯入檔案:
如何自訂 PDF 輸出?
IronPDF 透過 RenderingOptions 類別提供廣泛的自訂選項。 以下是一個展示常見客製化設定的範例:
using IronPdf;
// Create renderer with custom settings
var renderer = new ChromePdfRenderer();
// Page setup options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Margins (in millimeters)
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Header and footer configuration
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
Height = 15,
HtmlFragment = "<div style='text-align: center;'>{page} of {total-pages}</div>",
DrawDividerLine = true
};
// Additional options
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.GrayScale = false;
renderer.RenderingOptions.Zoom = 100;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Apply custom CSS for print
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Generate PDF with all customizations
var pdf = renderer.RenderHtmlAsPdf("<h1>Customized PDF Output</h1>");
pdf.SaveAs("customized.pdf");
using IronPdf;
// Create renderer with custom settings
var renderer = new ChromePdfRenderer();
// Page setup options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
// Margins (in millimeters)
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
// Header and footer configuration
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
Height = 15,
HtmlFragment = "<div style='text-align: center;'>{page} of {total-pages}</div>",
DrawDividerLine = true
};
// Additional options
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.GrayScale = false;
renderer.RenderingOptions.Zoom = 100;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;
// Apply custom CSS for print
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Generate PDF with all customizations
var pdf = renderer.RenderHtmlAsPdf("<h1>Customized PDF Output</h1>");
pdf.SaveAs("customized.pdf");
Imports IronPdf
' Create renderer with custom settings
Dim renderer = New ChromePdfRenderer()
' Page setup options
renderer.RenderingOptions.PaperSize = PdfPaperSize.A4
renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait
' Margins (in millimeters)
renderer.RenderingOptions.MarginTop = 25
renderer.RenderingOptions.MarginBottom = 25
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
' Header and footer configuration
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
.Height = 15,
.HtmlFragment = "<div style='text-align: center;'>{page} of {total-pages}</div>",
.DrawDividerLine = True
}
' Additional options
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.GrayScale = False
renderer.RenderingOptions.Zoom = 100
renderer.RenderingOptions.CreatePdfFormsFromHtml = True
' Apply custom CSS for print
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
' Generate PDF with all customizations
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Customized PDF Output</h1>")
pdf.SaveAs("customized.pdf")
如需更進階的客製化功能,請探索: -自訂紙張尺寸 -頁首和頁尾 背景和前景 頁碼 水印
圖書館快速訪問
分享 API 參考
Read through and share the API Reference for all the functionality you need to work with PDFs in your .NET project. The comprehensive documentation covers everything from basic [PDF creation](https://ironpdf.com/tutorials/csharp-create-pdf-complete-tutorial/) to advanced features like [digital signatures](https://ironpdf.com/tutorials/csharp-pdf-security-complete-tutorial/) and [form handling](https://ironpdf.com/how-to/edit-forms/).
IronPDF 的 API 參考常見問題解答
如何在我的 C# 項目中安裝 PDF 庫?
您可以通過直接下載套件 DLL 文件或使用 NuGet 通過 Visual Studio 安裝來安裝 PDF 庫,例如 IronPDF。
如何使用 PDF 庫從 C# 創建 PDF?
使用 PDF 庫(如 IronPDF),您可以利用 ChromePdfRenderer 類通過 HTML 字符串或 URL 轉換為 PDF,僅需少量代碼。
我可以使用 PDF 庫將 C# 表單轉換為 PDF 嗎?
是的,通過使用 IronPDF,您可以將 C# 表單轉換為 PDF。這需要捕獲表單的數據並使用該庫的渲染功能將其呈現為 PDF。
生成 PDF 的最簡單方法是什麼?
使用 IronPDF 生成 PDF 的最簡單方法是使用 ChromePdfRenderer 對象直接將 HTML 內容呈現為 PDF。
如何使用 PDF 庫將自定義文本和圖片添加到 PDF?
您可以通過在將其渲染為 PDF 之前操縱 HTML 內容來添加自定義文本和圖片,利用 IronPDF 的功能。
是否可以使用 PDF 庫編輯現有 PDF?
是的,IronPDF 提供了操作和編輯現有 PDF 的功能,允許您根據需要更新內容。
如何使用 PDF 庫直接將 URL 轉換為 PDF?
IronPDF 允許您使用 ChromePdfRenderer 對象簡化過程,直接將網頁 URL 轉換為 PDF。
.NET PDF 庫的主要功能是什麼?
像 IronPDF 這樣的 PDF 庫提供 PDF 創建、編輯、從 HTML 轉換以及添加自定義文本和圖像等功能,是 .NET 開發人員的多功能工具。
是否可以使用 PDF 庫自定義 PDF 設置?
是的,IronPDF 允許您自定義各種 PDF 設置,包括頁面大小、方向和邊距,以滿足您的特定項目需求。
如何在 C# 中使用 PDF 庫進行問題排查?
有關故障排除信息,您可以查看 IronPDF 提供的文檔和資源,或查閱社群論壇以獲得常見問題的解決方案。
IronPDF與.NET 10兼容嗎,.NET 10帶來什麼好處?
是的,IronPDF完全兼容.NET 10。它支持.NET 10中引入的運行時和語言增強功能,包括改進的內存使用、陣列接口方法的去虛化性能改進以及PDF生成和處理的減少開銷。





