使用IronPDF在C#中生成PDF
IronPDF 讓 C# 開發人員能夠使用簡單的 Windows Forms 應用程序,只需 5 個步驟即可將 HTML 轉換為 PDF,只需要安裝 NuGet 套件和幾行程式碼即可將 HTML 渲染為專業的 PDF 文件。
C# 開發人員可以使用 IronPDF 從 HTML 產生 PDF。 本文將使用基於 .NET Framework 建立的 C# Windows Forms 應用程式來示範這個過程。
請依照下列步驟在 Visual Studio 2019 中建立專案。
如何建立用於產生 PDF 的 Visual Studio 專案?
首先,開啟Visual Studio 2019 。
Visual Studio 2019 啟動視窗顯示複製儲存庫、開啟專案或解決方案、開啟本機資料夾或建立新專案的選項
點擊"建立新項目"。
現在,從範本中選擇"Windows 窗體應用程式",然後按"下一步"。 將出現以下視窗:
Visual Studio"建立新專案"對話方塊顯示了適用於 Windows、Linux 和 macOS 的 .NET Core Windows 窗體應用程式範本選擇。
輸入項目名稱"使用 IronPDF 建立 PDF"。
Visual Studio 新專案設定視窗顯示專案名稱為"使用 IronPDF 建立 PDF",已選擇 Windows 表單應用程式 (.NET Framework),框架版本為 4.7.2。
點擊"創建"按鈕。 項目將按如下所示建立。
Visual Studio IDE 的設計檢視中顯示空白的 Windows 窗體,解決方案資源管理器中顯示一個名為"使用 IronPDF 建立 PDF"的新專案。
為什麼本教學要使用 Windows 窗體?
Windows Forms 為學習C# 中 PDF 產生的初學者提供了一個簡單的視覺化環境。 它提供了一個拖放式設計器,無需豐富的 HTML 或 Web 開發知識即可輕鬆建立使用者介面。 Windows Forms 中的事件驅動程式設計模型與初級開發人員對應用程式流程的思考方式非常契合,因此非常適合示範IronPDF 的核心 HTML 轉 PDF 功能。
對於生產應用,您可以考慮使用ASP.NET Core 進行基於 Web 的 PDF 生成,或使用控制台應用程式進行批次處理。 然而,對於需要在開發過程中快速獲得視覺回饋的內部工具、桌面實用程式和學習環境而言,Windows Forms 仍然是一個絕佳的選擇。
哪個版本的 Visual Studio 最適合?
Visual Studio 2019 或更高版本為IronPDF 開發提供了最佳體驗。 這些版本改進了 NuGet 套件管理,更好地支援現代 C# 功能,並增強了偵錯功能,有助於排查 PDF 生成問題。
雖然 Visual Studio 2022 提供了最新的功能和效能改進,但 Visual Studio 2019 仍然被廣泛使用並獲得全面支援。 這兩個版本都能與IronPDF 的 NuGet 套件無縫協作。 對於使用 Visual Studio Code 的開發人員來說,您仍然可以使用 IronPDF,但您需要使用命令列介面進行套件管理,並且會錯過本教學中展示的一些視覺化設計功能。
我可以使用 .NET Core 來取代 .NET Framework 嗎?
絕對地! IronPDF 完全支援.NET Core、.NET 5、.NET 6 和 .NET 7+ 。 事實上,使用 .NET Core 或更新版本具有許多優勢,包括跨平台相容性、更好的效能以及對最新 C# 語言特性的存取。
要使用 .NET Core,只需在建立專案時選擇相應的目標框架。 本教程中的程式碼範例在所有支援的框架中都能正常運作。 為了提高部署靈活性, .NET Core 應用程式除了在 Windows 上運行外,還可以在 Linux 和 macOS 上運行,使其成為雲端部署和容器化環境的理想選擇。
如何使用 NuGet 套件管理器安裝 IronPDF?
- 首先,點擊選單列上的"工具"按鈕。 將會打開一個選單。 現在點選 NuGet 套件管理器選項。
- 將開啟另一個子選單。 現在點選名為"軟體包管理器控制台"的選項。
Visual Studio 顯示"工具"功能表已展開,其中包含 NuGet 套件管理器子選單,並反白顯示"套件管理器控制台"選項。
命令列下方會彈出一個新視窗。在該視窗中,輸入安裝 IronPdf 軟體包的命令。
Install-Package IronPdf
Visual Studio 2019 IDE 顯示套件管理器控制台,其中包含可執行的 IronPDF 安裝指令。
輸入指令後按回車鍵。 請確保您的電腦/筆記型電腦已連接到網路。 IronPdf 套件將自動新增至您現有的專案中。
Visual Studio 2019 IDE 顯示 IronPDF 庫文檔,其中包含 HTML 轉 PDF 的 C# 程式碼範例,同時程式包管理器控制台顯示 IronPDF 安裝成功。
上面的螢幕截圖顯示軟體包已成功添加到您的專案中。
安裝 IronPDF 還有哪些方法?
除了軟體包管理器控制台之外,您還可以透過以下幾種方式安裝 IronPDF :
- NuGet 套件管理器 UI :右鍵點擊您的項目,選擇"管理 NuGet 套件",搜尋"IronPDF",然後按一下"安裝"。 非常適合喜歡圖形使用者介面的初學者。
2.在 .csproj 檔案中:對於現代 .NET 項目,您可以直接將 IronPDF 新增至專案檔:
<PackageReference Include="IronPdf" Version="*" />
<PackageReference Include="IronPdf" Version="*" />
- dotnet CLI :適用於喜歡命令列工具或使用Visual Studio Code 的開發人員:
dotnet add package IronPdfdotnet add package IronPdfSHELL
4.手動下載:您可以直接從IronPDF 網站下載 DLL 並將其新增為引用,但這種方法會使更新變得更加困難。
為什麼安裝過程中需要連接網路?
NuGet 需要網路連線才能從 NuGet.org 儲存庫下載 IronPDF 及其相依性。 該軟體包包含 IronPDF 核心庫和 HTML 轉 PDF 所需的Chrome 渲染引擎二進位。
對於離線安裝,您可以:
- 建立本機 NuGet 套件快取
- 使用適用於 Windows 的 IronPDF 安裝程序
- 在連接的電腦上下載軟體包並手動傳輸
請注意, IronPDF 的渲染引擎需要額外的執行時間元件,這些元件可能會在首次使用時下載,因此初始 PDF 產生也受益於網路連線。
如何確認安裝是否成功?
安裝完成後,請檢查以下指標來驗證 IronPDF 是否正常運作:
1.引用節點:在解決方案資源管理器中,展開"引用"節點。 你應該能在專案參考文獻中看到"IronPdf"。
2.支援 IntelliSense :在 C# 檔案頂部輸入 using IronPdf;。 IntelliSense 應該能夠正確辨識命名空間。
3.簡單測試程式碼:新增以下基本測試以驗證功能:
using IronPdf;
// Quick verification test
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Test</h1>");
// If no exceptions occur, IronPDF is installed correctly
using IronPdf;
// Quick verification test
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Test</h1>");
// If no exceptions occur, IronPDF is installed correctly
Imports IronPdf
' Quick verification test
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Test</h1>")
' If no exceptions occur, IronPDF is installed correctly
4.軟體套件管理器:在軟體套件管理器控制台中執行 Get-Package IronPdf 以查看版本資訊。
如何設計PDF生成使用者介面?
現在新增一個標籤,並將文字設定為"使用 IronPDF 從 HTML 建立 PDF"。
Visual Studio IDE 顯示了一個 Windows 窗體應用程序,其窗體設計器中顯示了一個標籤,內容為"使用 Iron PDF 從 HTML 建立 PDF"。
接下來,從工具箱中新增一個富文本框和一個按鈕。 將按鈕文字設定為"轉換"。
! Windows 窗體應用程式介面,顯示文字輸入區域和"轉換"按鈕,用於使用 IronPDF 從 HTML 建立 PDF。
為什麼使用 RichTextBox 而不是常規的 TextBox?
在 PDF 生成場景中,使用 HTML 輸入具有以下幾個優勢:
1.多行支援:HTML 通常跨越多行,而 RichTextBox 可以自然地處理這種情況,而 TextBox 需要設定 Multiline = true。
2.格式保留:雖然我們輸入的是純 HTML,但 RichTextBox 會保留縮排和換行符等格式,使 HTML 在開發過程中更容易閱讀。
3.更大的容量:RichTextBox 可以處理更多的文本,這在處理完整的 HTML 文件而不是程式碼片段時非常有用。
4.語法高亮潛力:雖然在這個基本範例中沒有實現,但可以擴展為 HTML 提供語法高亮,從而改善開發人員的體驗。
對於生產應用,可以考慮使用專用的 HTML 編輯器控製或與外部編輯器集成,以獲得更好的使用者體驗。
還有哪些控制項可以增強使用者介面?
為了創建更強大的 PDF 生成應用程序,請考慮添加以下控制項:
-
WebBrowser控制:在轉換前顯示 HTML 預覽,幫助使用者查看 PDF 的最終效果。這模擬了IronPDF 的 Chrome 渲染引擎。 -
ProgressBar: 顯示大型文件或批次操作的轉換進度。 -
ComboBox用於範本:為發票或報表等常見文件類型提供預先定義的 HTML 範本。 -
PropertyGrid: 允許使用者修改PDF 渲染設置,例如頁面大小、邊距和方向。 TabControl: 將 HTML、預覽和PDF 的輸入設定分別放在不同的標籤頁中。
新增狀態回授條的範例:
// Add to your form
StatusStrip statusStrip = new StatusStrip();
ToolStripStatusLabel statusLabel = new ToolStripStatusLabel("Ready");
statusStrip.Items.Add(statusLabel);
this.Controls.Add(statusStrip);
// Add to your form
StatusStrip statusStrip = new StatusStrip();
ToolStripStatusLabel statusLabel = new ToolStripStatusLabel("Ready");
statusStrip.Items.Add(statusLabel);
this.Controls.Add(statusStrip);
' Add to your form
Dim statusStrip As New StatusStrip()
Dim statusLabel As New ToolStripStatusLabel("Ready")
statusStrip.Items.Add(statusLabel)
Me.Controls.Add(statusStrip)
為了達到最佳實踐,我應該如何命名我的控制項?
遵循一致的命名規則可以提高程式碼的可讀性和可維護性。 以下是產生 PDF 表單的建議做法:
1.使用描述性前綴:
txtHtml用於 HTML 輸入RichTextBoxbtnConvert用於轉換按鈕lblTitle用於標題標籤
2.保持一致:選擇駝峰命名法或 PascalCase,並在整個專案中堅持使用。
3.避免使用預設名稱:將 richTextBox1 替換為有意義的名稱,例如 rtbHtmlInput。
4.將相關控制項分組:對於複雜的表單,使用前綴來將功能分組:
pdfPageSize,pdfOrientation用於 PDF 特定設置htmlTemplate,htmlPreview用於 HTML 相關控制項
5.考慮輔助功能:設定 Name 屬性以支援螢幕閱讀器,設定 AccessibleName 屬性以提高可用性。
良好的命名可以使你的程式碼具有自文檔性,並有助於實現諸如表單資料提取之類的功能。
如何編寫程式碼將HTML轉換為PDF?
雙擊"轉換"按鈕。 將開啟一個包含轉換按鈕點擊事件的程式碼視窗。
在 .cs 檔案的頂部新增導入 IronPDF 庫的程式碼。
首先,新增以下程式碼以使用 IronPDF 庫方法。
using IronPdf;
using IronPdf;
Imports IronPdf
以下是 btnConvert_Click 事件的初始代碼,目前為空:
private void btnConvert_Click(object sender, EventArgs e)
{
}
private void btnConvert_Click(object sender, EventArgs e)
{
}
Private Sub btnConvert_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub
現在在按鈕點擊事件中編寫以下程式碼:
private void btnConvert_Click(object sender, EventArgs e)
{
// Declare an HtmlToPdf object
var HtmlLine = new HtmlToPdf();
// Get HTML text from the user
string strHtml = txtHtml.Text;
// Create SaveFileDialog to choose the save path for the PDF file
SaveFileDialog saveFileDialog = new SaveFileDialog
{
InitialDirectory = @"D:\",
Title = "Save PDF",
CheckPathExists = true,
DefaultExt = "pdf",
Filter = "pdf files (*.pdf)|*.pdf",
FilterIndex = 2,
RestoreDirectory = true
};
// If the user presses Save
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
// Get the file path from the user
string filePath = saveFileDialog.FileName;
// Convert HTML to PDF and save at the specified path
using var PDF = HtmlLine.RenderHtmlAsPdf(strHtml);
PDF.SaveAs(filePath);
// Clear the TextBox and show a message confirming the successful creation
txtHtml.Text = "";
MessageBox.Show("File created successfully.");
}
}
private void btnConvert_Click(object sender, EventArgs e)
{
// Declare an HtmlToPdf object
var HtmlLine = new HtmlToPdf();
// Get HTML text from the user
string strHtml = txtHtml.Text;
// Create SaveFileDialog to choose the save path for the PDF file
SaveFileDialog saveFileDialog = new SaveFileDialog
{
InitialDirectory = @"D:\",
Title = "Save PDF",
CheckPathExists = true,
DefaultExt = "pdf",
Filter = "pdf files (*.pdf)|*.pdf",
FilterIndex = 2,
RestoreDirectory = true
};
// If the user presses Save
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
// Get the file path from the user
string filePath = saveFileDialog.FileName;
// Convert HTML to PDF and save at the specified path
using var PDF = HtmlLine.RenderHtmlAsPdf(strHtml);
PDF.SaveAs(filePath);
// Clear the TextBox and show a message confirming the successful creation
txtHtml.Text = "";
MessageBox.Show("File created successfully.");
}
}
Private Sub btnConvert_Click(ByVal sender As Object, ByVal e As EventArgs)
' Declare an HtmlToPdf object
Dim HtmlLine = New HtmlToPdf()
' Get HTML text from the user
Dim strHtml As String = txtHtml.Text
' Create SaveFileDialog to choose the save path for the PDF file
Dim saveFileDialog As New SaveFileDialog With {
.InitialDirectory = "D:\",
.Title = "Save PDF",
.CheckPathExists = True,
.DefaultExt = "pdf",
.Filter = "pdf files (*.pdf)|*.pdf",
.FilterIndex = 2,
.RestoreDirectory = True
}
' If the user presses Save
If saveFileDialog.ShowDialog() = DialogResult.OK Then
' Get the file path from the user
Dim filePath As String = saveFileDialog.FileName
' Convert HTML to PDF and save at the specified path
Dim PDF = HtmlLine.RenderHtmlAsPdf(strHtml)
PDF.SaveAs(filePath)
' Clear the TextBox and show a message confirming the successful creation
txtHtml.Text = ""
MessageBox.Show("File created successfully.")
End If
End Sub
解釋:
- 建立一個
HtmlToPdf對象,以利用 IronPDF 的轉換功能。 - HTML 輸入是從文字方塊中取得的。
- 使用
SaveFileDialog提示使用者指定產生的 PDF 應儲存到哪裡。 - 如果使用者選擇檔案位置並按下"儲存"按鈕,則會取得檔案路徑。
然後使用
RenderHtmlAsPdf將 HTML 輸入渲染成 PDF,並儲存到選定的路徑。 - 儲存後,文字方塊將被清空,並顯示一個訊息方塊以確認 PDF 建立。
我應該在這段程式碼中加入哪些錯誤處理機制?
強大的錯誤處理能力對於生產環境中的 PDF 產生應用至關重要。 以下是增強版,增加了全面的錯誤處理功能:
private void btnConvert_Click(object sender, EventArgs e)
{
try
{
// Validate input
if (string.IsNullOrWhiteSpace(txtHtml.Text))
{
MessageBox.Show("Please enter HTML content.", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
var renderer = new ChromePdfRenderer();
string strHtml = txtHtml.Text;
SaveFileDialog saveFileDialog = new SaveFileDialog
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Title = "Save PDF",
CheckPathExists = true,
DefaultExt = "pdf",
Filter = "pdf files (*.pdf)|*.pdf",
FilterIndex = 1,
RestoreDirectory = true
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
// Show progress cursor
Cursor.Current = Cursors.WaitCursor;
using var pdf = renderer.RenderHtmlAsPdf(strHtml);
pdf.SaveAs(saveFileDialog.FileName);
txtHtml.Text = "";
MessageBox.Show("PDF created successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (IronPdf.Exceptions.IronPdfProductException ex)
{
// Handle licensing issues
MessageBox.Show($"Licensing error: {ex.Message}", "License Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// Log the full exception for debugging
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
private void btnConvert_Click(object sender, EventArgs e)
{
try
{
// Validate input
if (string.IsNullOrWhiteSpace(txtHtml.Text))
{
MessageBox.Show("Please enter HTML content.", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
var renderer = new ChromePdfRenderer();
string strHtml = txtHtml.Text;
SaveFileDialog saveFileDialog = new SaveFileDialog
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Title = "Save PDF",
CheckPathExists = true,
DefaultExt = "pdf",
Filter = "pdf files (*.pdf)|*.pdf",
FilterIndex = 1,
RestoreDirectory = true
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
// Show progress cursor
Cursor.Current = Cursors.WaitCursor;
using var pdf = renderer.RenderHtmlAsPdf(strHtml);
pdf.SaveAs(saveFileDialog.FileName);
txtHtml.Text = "";
MessageBox.Show("PDF created successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (IronPdf.Exceptions.IronPdfProductException ex)
{
// Handle licensing issues
MessageBox.Show($"Licensing error: {ex.Message}", "License Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// Log the full exception for debugging
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
Try
' Validate input
If String.IsNullOrWhiteSpace(txtHtml.Text) Then
MessageBox.Show("Please enter HTML content.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Dim renderer As New ChromePdfRenderer()
Dim strHtml As String = txtHtml.Text
Dim saveFileDialog As New SaveFileDialog With {
.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
.Title = "Save PDF",
.CheckPathExists = True,
.DefaultExt = "pdf",
.Filter = "pdf files (*.pdf)|*.pdf",
.FilterIndex = 1,
.RestoreDirectory = True
}
If saveFileDialog.ShowDialog() = DialogResult.OK Then
Try
' Show progress cursor
Cursor.Current = Cursors.WaitCursor
Using pdf = renderer.RenderHtmlAsPdf(strHtml)
pdf.SaveAs(saveFileDialog.FileName)
End Using
txtHtml.Text = ""
MessageBox.Show("PDF created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As IronPdf.Exceptions.IronPdfProductException
' Handle licensing issues
MessageBox.Show($"Licensing error: {ex.Message}", "License Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
Cursor.Current = Cursors.Default
End Try
End If
Catch ex As Exception
MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
' Log the full exception for debugging
System.Diagnostics.Debug.WriteLine(ex.ToString())
End Try
End Sub
主要錯誤處理改善:
- 處理前進行輸入驗證
- 針對IronPDF 許可例外情況的具體處理
- 透過遊標變化指示進度
- 正確的異常日誌記錄,方便調試
- 使用者友善的錯誤訊息
如何自訂PDF設置,例如頁面大小?
IronPDF 透過ChromePdfRenderOptions類別提供廣泛的自訂功能。 以下是如何實現常見自訂設定:
private void ConvertWithCustomSettings()
{
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions = new ChromePdfRenderOptions
{
// Page setup
PaperSize = PdfPaperSize.A4,
PaperOrientation = PdfPaperOrientation.Portrait,
MarginTop = 25, // millimeters
MarginBottom = 25,
MarginLeft = 20,
MarginRight = 20,
// Rendering behavior
EnableJavaScript = true,
RenderDelay = 500, // milliseconds
CreatePdfFormsFromHtml = true,
// Headers and footers
TextHeader = new TextHeaderFooter
{
CenterText = "My Document",
FontSize = 12,
DrawDividerLine = true
},
TextFooter = new TextHeaderFooter
{
RightText = "Page {page} of {total-pages}",
FontSize = 10
}
};
// Apply custom CSS for print
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Generate PDF with custom settings
var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);
pdf.SaveAs("custom-output.pdf");
}
private void ConvertWithCustomSettings()
{
var renderer = new ChromePdfRenderer();
// Configure rendering options
renderer.RenderingOptions = new ChromePdfRenderOptions
{
// Page setup
PaperSize = PdfPaperSize.A4,
PaperOrientation = PdfPaperOrientation.Portrait,
MarginTop = 25, // millimeters
MarginBottom = 25,
MarginLeft = 20,
MarginRight = 20,
// Rendering behavior
EnableJavaScript = true,
RenderDelay = 500, // milliseconds
CreatePdfFormsFromHtml = true,
// Headers and footers
TextHeader = new TextHeaderFooter
{
CenterText = "My Document",
FontSize = 12,
DrawDividerLine = true
},
TextFooter = new TextHeaderFooter
{
RightText = "Page {page} of {total-pages}",
FontSize = 10
}
};
// Apply custom CSS for print
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
// Generate PDF with custom settings
var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);
pdf.SaveAs("custom-output.pdf");
}
Private Sub ConvertWithCustomSettings()
Dim renderer = New ChromePdfRenderer()
' Configure rendering options
renderer.RenderingOptions = New ChromePdfRenderOptions With {
' Page setup
.PaperSize = PdfPaperSize.A4,
.PaperOrientation = PdfPaperOrientation.Portrait,
.MarginTop = 25, ' millimeters
.MarginBottom = 25,
.MarginLeft = 20,
.MarginRight = 20,
' Rendering behavior
.EnableJavaScript = True,
.RenderDelay = 500, ' milliseconds
.CreatePdfFormsFromHtml = True,
' Headers and footers
.TextHeader = New TextHeaderFooter With {
.CenterText = "My Document",
.FontSize = 12,
.DrawDividerLine = True
},
.TextFooter = New TextHeaderFooter With {
.RightText = "Page {page} of {total-pages}",
.FontSize = 10
}
}
' Apply custom CSS for print
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print
' Generate PDF with custom settings
Dim pdf = renderer.RenderHtmlAsPdf(txtHtml.Text)
pdf.SaveAs("custom-output.pdf")
End Sub
為什麼要在產生 PDF 時使用 using 語句?
using 語句對於 PDF 產生中的正確資源管理至關重要:
1.自動銷毀:PDF 文件會佔用大量內存,尤其是包含圖像或大量內容的 PDF 文件。 using 語句確保 PDF 物件在使用後被正確釋放。
2.文件句柄釋放:如果沒有正確處置,文件句柄可能會保持鎖定狀態,從而阻止對 PDF 文件進行後續操作。
3.記憶體管理:IronPDF 的渲染引擎使用必須釋放的本機資源,以防止長時間運行的應用程式出現記憶體洩漏。
以下是圖案對比:
// Recommended approach with using
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
pdf.SaveAs("output.pdf");
} // Resources automatically released here
// Alternative with try-finally (more verbose)
PdfDocument pdf = null;
try
{
pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
}
finally
{
pdf?.Dispose();
}
// Recommended approach with using
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
pdf.SaveAs("output.pdf");
} // Resources automatically released here
// Alternative with try-finally (more verbose)
PdfDocument pdf = null;
try
{
pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("output.pdf");
}
finally
{
pdf?.Dispose();
}
' Recommended approach with Using
Using pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")
End Using ' Resources automatically released here
' Alternative with Try-Finally (more verbose)
Dim pdf As PdfDocument = Nothing
Try
pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("output.pdf")
Finally
If pdf IsNot Nothing Then
pdf.Dispose()
End If
End Try
對於非同步操作,請在 C# 8.0+ 中使用 await using:
await using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
await using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
Await Using pdf = Await renderer.RenderHtmlAsPdfAsync(html)
哪些常用的HTML標籤效果最佳?
IronPDF 的Chrome 渲染引擎支援所有現代 HTML5 標籤,但有些標籤特別適用於 PDF 產生:
文檔結構:
<html>
<head>
<meta charset="UTF-8">
<style>
@media print { /* PDF-specific styles */ }
body { font-family: Arial, sans-serif; }
.page-break { page-break-after: always; }
</style>
</head>
<body>
<h1>Document Title</h1>
<div class="page-break"></div>
<h2>New Page Content</h2>
</body>
</html>
<html>
<head>
<meta charset="UTF-8">
<style>
@media print { /* PDF-specific styles */ }
body { font-family: Arial, sans-serif; }
.page-break { page-break-after: always; }
</style>
</head>
<body>
<h1>Document Title</h1>
<div class="page-break"></div>
<h2>New Page Content</h2>
</body>
</html>
PDF 效能最佳的標籤:
<h1>至<h6>:創建清晰的文檔層級結構<table>: 非常適合結構化資料和發票<img>: 支援嵌入式影像和 base64 數據<div>使用 CSS:精確的佈局控制<p>和<span>: 標準文字格式<ul>和<ol>: 清理清單格式
特殊考慮因素:
- 使用CSS 分頁符號實現多頁面控制
- 使用@font-face嵌入字體以保持一致性
- 謹慎使用絕對定位
- 全面測試JavaScript 產生的內容
如何測試PDF生成應用程式?
運行專案後,您將看到以下畫面:
這是一個 Windows 窗體應用程序,包含一個文字輸入欄位(其中包含用於生成簡單 PDF 文件的 HTML 程式碼)和一個"轉換"按鈕。
在 RichTextBox 中輸入 HTML 程式碼,例如:
<h1>A Simple PDF File</h1><br><h6>Heading 6</h6>
<h1>A Simple PDF File</h1><br><h6>Heading 6</h6>
點擊"轉換"。 您將看到一個儲存檔案對話框。
Windows"儲存PDF"對話方塊顯示檔案瀏覽器,已選擇工作驅動器,檔案名稱設定為HtmlToPDF 。
點擊儲存按鈕後,檔案將以您指定的名稱和位置儲存到您指定的路徑。
我應該先測試哪些HTML元素?
首先從這些難度逐漸遞增的 HTML 範例入手,了解IronPDF 的渲染功能:
基本文字格式設定:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.highlight { background-color: yellow; }
.important { color: red; font-weight: bold; }
</style>
</head>
<body>
<h1>Test Document</h1>
<p>This is <strong>bold</strong> and <em>italic</em> text.</p>
<p class="highlight">Highlighted text example.</p>
<p class="important">Important notice!</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.highlight { background-color: yellow; }
.important { color: red; font-weight: bold; }
</style>
</head>
<body>
<h1>Test Document</h1>
<p>This is <strong>bold</strong> and <em>italic</em> text.</p>
<p class="highlight">Highlighted text example.</p>
<p class="important">Important notice!</p>
</body>
</html>
有樣式的表格:
<table style="border-collapse: collapse; width: 100%;">
<tr style="background-color: #f2f2f2;">
<th style="border: 1px solid #ddd; padding: 8px;">Product</th>
<th style="border: 1px solid #ddd; padding: 8px;">Price</th>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">IronPDF</td>
<td style="border: 1px solid #ddd; padding: 8px;">$749</td>
</tr>
</table>
<table style="border-collapse: collapse; width: 100%;">
<tr style="background-color: #f2f2f2;">
<th style="border: 1px solid #ddd; padding: 8px;">Product</th>
<th style="border: 1px solid #ddd; padding: 8px;">Price</th>
</tr>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;">IronPDF</td>
<td style="border: 1px solid #ddd; padding: 8px;">$749</td>
</tr>
</table>
進階功能:
<img src="___PROTECTED_URL_118___" width="200" alt="Company Logo">
<div style="page-break-after: always;"></div>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
<img src="___PROTECTED_URL_118___" width="200" alt="Company Logo">
<div style="page-break-after: always;"></div>
<ul>
<li>First item</li>
<li>Second item</li>
</ul>
測試這些元素,以確保HTML到PDF的轉換功能能如預期運作。
如果 PDF 文件無法生成,我該如何調試?
當 PDF 生成失敗時,請按照以下系統化的調試方法進行操作:
1.啟用日誌記錄:
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdfLog.txt";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LogFilePath = "IronPdfLog.txt";
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
IronPdf.Logging.Logger.EnableDebugging = True
IronPdf.Logging.Logger.LogFilePath = "IronPdfLog.txt"
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
2.檢查 HTML 有效性:
// Validate HTML before conversion
private bool IsValidHtml(string html)
{
try
{
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
return doc.ParseErrors.Count() == 0;
}
catch
{
return false;
}
}
// Validate HTML before conversion
private bool IsValidHtml(string html)
{
try
{
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
return doc.ParseErrors.Count() == 0;
}
catch
{
return false;
}
}
' Validate HTML before conversion
Private Function IsValidHtml(html As String) As Boolean
Try
Dim doc As New HtmlAgilityPack.HtmlDocument()
doc.LoadHtml(html)
Return doc.ParseErrors.Count() = 0
Catch
Return False
End Try
End Function
3.使用 Chrome DevTools:
將你的 HTML 程式碼儲存到文件,然後在 Chrome 瀏覽器中開啟。
按 F12 檢查 JavaScript 錯誤
- 檢查控制台是否有問題 -使用 Chrome 的列印預覽功能查看渲染效果
4.常見問題及解決方案: -空白 PDF :檢查JavaScript 是否需要更多渲染延遲 -圖片缺失:請確保圖片路徑為絕對路徑或使用 base64 編碼。 -字體問題:正確嵌入字體 -版面問題:檢查CSS 媒體類型
5.測試最小範例:
// Start with the simplest possible HTML
var testHtml = "<h1>Test</h1>";
var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(testHtml);
pdf.SaveAs("test.pdf");
// Start with the simplest possible HTML
var testHtml = "<h1>Test</h1>";
var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(testHtml);
pdf.SaveAs("test.pdf");
' Start with the simplest possible HTML
Dim testHtml = "<h1>Test</h1>"
Dim pdf = New ChromePdfRenderer().RenderHtmlAsPdf(testHtml)
pdf.SaveAs("test.pdf")
運行應用程式時常見的問題有哪些?
以下是初級開發人員最常遇到的問題及其解決方案:
-
"IronPdf.Exceptions.
IronPdfDeploymentException" 解決方案:確保已安裝 Visual C++ 執行階段環境。 執行 Windows 更新以取得最新的執行環境。 - "訪問被拒絕"錯誤
- 請勿儲存至受保護的目錄(C:\、Program Files)
- 使用
Environment.SpecialFolder取得安全路徑 檢查 Web 應用程式的IIS 權限
3.文件體積大
- 應用PDF 壓縮:
pdf.CompressImages(90); // 90% qualitypdf.CompressImages(90); // 90% qualitypdf.CompressImages(90) ' 90% quality$vbLabelText $csharpLabel
4.性能緩慢
5.內容缺失 外部資源可能需要絕對URL。 JavaScript 內容可能需要延遲載入。 檢查受保護資源的網路憑證
如果問題持續存在,請參閱綜合故障排除指南。
最終的PDF輸出是什麼樣子的?
輸出的PDF文件將如下所示:
! 一個簡單的PDF文件截圖,標題為"一個簡單的PDF文件",文字為"標題6",背景為白色。
如何提升PDF品質?
使用以下專業技巧提升您的 PDF 輸出品質:
1.高解析度渲染:
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.ImageQuality = 95; // Higher quality for images
renderer.RenderingOptions.DPI = 300; // Print-quality resolution
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.ImageQuality = 95; // Higher quality for images
renderer.RenderingOptions.DPI = 300; // Print-quality resolution
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.ImageQuality = 95 ' Higher quality for images
renderer.RenderingOptions.DPI = 300 ' Print-quality resolution
2.專業造型:
<style>
@page {
size: A4;
margin: 2cm;
}
body {
font-family: 'Segoe UI', Tahoma, sans-serif;
line-height: 1.6;
color: #333;
}
h1 {
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
</style>
<style>
@page {
size: A4;
margin: 2cm;
}
body {
font-family: 'Segoe UI', Tahoma, sans-serif;
line-height: 1.6;
color: #333;
}
h1 {
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
</style>
3.加入視覺元素: -自訂頁首和頁尾 草稿浮水印 頁碼 公司標誌
4.針對不同用途進行最佳化: 螢幕檢視:降低 DPI(96-150), PDF 壓縮 -印刷:高解析度(300DPI以上), CMYK色彩模式 -存檔格式: PDF/A 格式
為什麼輸出結果可能與預期不同?
多種因素會導致HTML預覽和PDF輸出之間存在渲染差異:
- CSS 媒體類型:PDF 預設使用列印媒體。 新增列印專用樣式:
@media print { .no-print { display: none; } body { font-size: 12pt; } }
2.字體可用性:嵌入自訂字體以確保一致性:
@font-face {
font-family: 'MyFont';
src: url('data:font/woff2;base64,...') format('woff2');
}
3.動態內容: JavaScript渲染的內容需要時間載入:
renderer.RenderingOptions.RenderDelay = 2000; // Wait 2 seconds
renderer.RenderingOptions.RenderDelay = 2000; // Wait 2 seconds
renderer.RenderingOptions.RenderDelay = 2000 ' Wait 2 seconds
4.瀏覽器差異:IronPDF 使用 Chromium 內核,因此請在 Chrome 瀏覽器中測試以獲得準確的預覽效果。 了解 Chrome 渲染器。
5.解析度和縮放:顯示器 DPI 與列印 DPI 不同。 使用視窗設定以獲得一致的渲染效果。
為了獲得像素級完美的渲染效果,請遵循HTML 轉 PDF 最佳實踐指南。
本教學結束後下一步該怎麼做?
上面的教學說明如何使用 IronPDF 庫從 HTML 建立 PDF。
欲了解更多信息,請訪問IronPDF 官方網站。 該庫還提供了其他功能,支援完全可自訂的 PDF 文件、以程式設計方式合併和分割文件,或只是查看演示各種功能的範例程式碼。
您可以使用30 天試用金鑰進行評估。 目前有一個非常優惠的活動,您可以用兩件 Iron Software 產品的價格購買五件。 請造訪IronPDF 許可資訊頁面,以了解更多許可資訊。
接下來我應該學習哪些進階功能?
掌握了基本的 HTML 轉 PDF 功能後,可以探索以下進階功能:
- PDF 表單:建立可填寫表單以進行資料收集:
// Create interactive form fields pdf.Form.Fields.Add(new PdfTextField("name", "Enter your name", 100, 100));// Create interactive form fields pdf.Form.Fields.Add(new PdfTextField("name", "Enter your name", 100, 100));' Create interactive form fields pdf.Form.Fields.Add(New PdfTextField("name", "Enter your name", 100, 100))$vbLabelText $csharpLabel
2.數位簽章:增強文件的安全性和真實性
5.性能優化:
- Web應用程式的非同步渲染 批量處理多個文檔
- 記憶體高效的串流
首先選擇與專案需求最相關的功能。
如何從試驗階段過渡到生產階段?
從試驗階段過渡到生產階段涉及幾個重要步驟:
1.選擇合適的許可證:
- Lite :單人開發者,單一項目 優點:單一開發者,多個項目 -專業級:小型團隊(最多 3 位開發人員) -無限制:企業團隊
2.應用您的許可證密鑰:
// In application startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Or via configuration
// appsettings.json (for .NET Core)
{
"IronPdf.License.LicenseKey": "YOUR-LICENSE-KEY"
}
// In application startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
// Or via configuration
// appsettings.json (for .NET Core)
{
"IronPdf.License.LicenseKey": "YOUR-LICENSE-KEY"
}
' In application startup
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
' Or via configuration
' appsettings.json (for .NET Core)
' {
' "IronPdf.License.LicenseKey": "YOUR-LICENSE-KEY"
' }
3.移除試用浮水印:授權版本會自動從所有產生的 PDF 移除試用浮水印。
4.性能方面的考量:
5.部署檢查清單:
- 驗證伺服器要求
- 在目標部署平台上進行測試 -如適用,請設定 IIS
- 設定持續集成
有關詳細的許可指南,請參閱許可常見問題。
哪裡可以找到更複雜的例子?
透過以下綜合資源,拓展您的 IronPDF 知識:
2.教程系列: -完整的 HTML 轉 PDF 指南 -從零開始建立 PDF -進階 PDF 編輯
3.整合指南:
- API 文件:
- 全面的課程參考資料
- 方法簽名和參數
- 每個功能的程式碼片段
5.社區資源: Stack Overflow IronPDF 標籤
首先從最接近您使用場景的範例入手,然後根據需要逐步探索更高級的功能。
常見問題解答
怎樣在 C# 中將 HTML 轉換為 PDF?
您可以使用 IronPDF 的 RenderHtmlAsPdf 方法将 HTML 字符串轉换為 PDF。只需创建一個 HtmlToPdf 對象并調用該方法即可将 HTML 渲染為 PDF 文檔。
設置用于 PDF 生成的 Visual Studio 項目需要哪些步骤?
首先打開 Visual Studio 2019,選择'创建新項目',選择'Windows 窗体應用程序',并設置項目名称。然後,通過 NuGet 安装 IronPDF 以開始集成 PDF 生成功能。
如何在 Visual Studio 中安装 PDF 生成庫?
您可以通過导航到 Visual Studio 中的包管理器控制台并执行命令Install-Package IronPDF来安装 IronPDF。
生成 PDF 表单中應包括哪些组件?
包括用于指导的標签、用于輸入 HTML 的富文本框,以及一個標记為'轉换'的按钮,用戶将點击以生成 PDF。
如何實現用于创建 PDF 文件的後端代碼?
使用 IronPDF 声明一個 HtmlToPdf 對象。從文本框中獲取 HTML 輸入,提示用戶保存 PDF,并使用 RenderHtmlAsPdf 方法渲染 HTML。
HtmlToPdf 對象在 PDF 庫中具有什么功能?
IronPDF 中的 HtmlToPdf 對象用于使用庫的全面轉换功能将 HTML 內容轉换為 PDF 文檔。
如何验證我的 PDF 生成項目正常運行?
在 Visual Studio 中执行項目,将 HTML 輸入到 RichTextBox 中,并點击'轉换'。然後使用 SaveFileDialog 選择 PDF 文件的位置,确保成功完成轉换。
PDF 庫提供了哪些高级功能?
IronPDF 允許创建完全可定制的 PDF,还可以编程合并和拆分文件。庫还提供各种功能的示例代碼。
我可以在購買前试用 PDF 庫嗎?
是的,IronPDF 的官方網站提供 30 天的试用密钥,讓您在購買前探索其功能。
在哪里可以找到 PDF 庫的許可详情?
关于 IronPDF 的详细許可信息可以在其網站上的 IronPDF 許可信息頁面找到,包括選項和当前优惠。
IronPDF 是否與 .NET 10 相容?
是的 — IronPDF已經支援所有現代.NET版本,並符合即將於2025年11月發行的.NET 10。它可以開箱即用於.NET 10專案,無需額外的語法支持。 (ironpdf.com/blog/using-ironpdf/5-steps-to-generate-a-pdf-file-in-c-sharp/)



