How to Convert HTML String to PDF in C
IronPDF 透過 Chrome 渲染引擎,在 C# 環境中將 HTML 字串轉換為 PDF 文件,支援所有 HTML5、CSS3 及 JavaScript 內容,且僅需一行程式碼即可完成基本轉換。 此函式庫提供強大的 PDF 建立功能,同時能完美呈現原始內容。
IronPDF 讓開發人員能夠在 C#、F# 和 VB.NET 中輕鬆建立 PDF 文件,適用於 .NET Core 和 .NET Framework。 IronPDF 支援將任何 HTML 字串渲染為 PDF,其渲染過程採用功能完整的 Google Chromium 引擎。這確保 HTML 內容的顯示效果與現代網頁瀏覽器完全一致,使其成為從動態 HTML 內容生成報告、發票及文件的理想選擇。
快速入門:數秒內將 HTML 字串轉換為 PDF using IronPDF 將 HTML 字串轉換為 PDF 檔案。 本指南將示範如何使用 C# 將 HTML 字串轉換為 PDF 文件,且僅需極少量的程式碼。 非常適合需要將 PDF 渲染功能整合至專案中的開發人員。
簡化工作流程(5 個步驟)
- 從 NuGet 下載 IronPDF C# 函式庫
- 建立 PDF Renderer 實例並傳入 HTML 字串
- 設定 PDF 中外部資源的 BasePath
- 設定 RenderingOptions 以微調輸出 PDF
- 儲存並下載生成的 PDF
如何將簡單的 HTML 字串轉換為 PDF?
以下是 IronPDF 使用 RenderHtmlAsPdf 方法將 HTML 字串渲染為 PDF 的範例。 該參數為將渲染為 PDF 的 HTML 字串。 此方法屬於 ChromePdfRenderer 類別的一部分,該類別提供廣泛的渲染選項控制,以滿足您的 PDF 生成需求。
:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Create a PDF from a HTML string using C#
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
' Export to a file or Stream
pdf.SaveAs("output.pdf")
RenderHtmlAsPdf 方法會傳回一個 PdfDocument 物件,該物件包含 PDF 資訊,並提供用於操作 PDF 的方法,包括合併 PDF、添加浮水印以及設定安全性選項。
RenderHtmlAsPdfAsync 以避免阻塞執行緒。 由於 PdfDocument 返回的值實作了 IDisposable,因此請將其包裹在 using 區塊中,以因應高吞吐量情境。 ChromePdfRenderer 具有線程安全性,可單次建立實例並在不同請求間重複使用,以提升效能。當從外部來源取得 HTML 字串,且您需要停用本地磁碟存取或跨來源請求時,請在渲染前將 IronPdf.Installation.EnableWebSecurity 設為 true。 這是靜態的全域設定,而非渲染器上的實例屬性。
// Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = true;
// Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = true;
' Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = True
對於包含 CSS 樣式的複雜 HTML 內容,請透過"基礎 URL 與資產編碼"功能,使用內嵌樣式或引用外部樣式表來強化您的 HTML 字串:
// Example with inline CSS
var styledHtml = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; border-bottom: 2px solid #0066cc; }
p { line-height: 1.6; }
</style>
</head>
<body>
<h1>Professional Report</h1>
<p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>";
using var styledPdf = renderer.RenderHtmlAsPdf(styledHtml);
styledPdf.SaveAs("styled-output.pdf");
// Example with inline CSS
var styledHtml = @"
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; border-bottom: 2px solid #0066cc; }
p { line-height: 1.6; }
</style>
</head>
<body>
<h1>Professional Report</h1>
<p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>";
using var styledPdf = renderer.RenderHtmlAsPdf(styledHtml);
styledPdf.SaveAs("styled-output.pdf");
Dim styledHtml As String = "
<html>
<head>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
h1 { color: #333; border-bottom: 2px solid #0066cc; }
p { line-height: 1.6; }
</style>
</head>
<body>
<h1>Professional Report</h1>
<p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>"
Using styledPdf = renderer.RenderHtmlAsPdf(styledHtml)
styledPdf.SaveAs("styled-output.pdf")
End Using
生成的 PDF 檔案看起來是什麼樣子?
這是程式碼產生的檔案:
生成的 PDF 完全保留原始 HTML 的格式與樣式,非常適合用於生成 PDF 報告,或將網頁內容轉換為可直接列印的文件。
將 HTML 轉換為 PDF 時,該如何包含外部資源?
此範例展示 IronPDF 如何從可選的 BasePath 載入外部圖像資源。 設定 BaseUrlOrPath 屬性,可為超連結、圖片、CSS 及 JavaScript 檔案提供相對檔案路徑或 URL 上下文。 這在處理 PDF 中的圖片,或需要引用外部資源時尤為重要。
:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf-2.cs
using IronPdf;
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
// Advanced Example with HTML Assets
// Load external html assets: Images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf
' Instantiate Renderer
Private renderer = New ChromePdfRenderer()
' Advanced Example with HTML Assets
' Load external html assets: Images, CSS and JavaScript.
' An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
Private myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
針對涉及複雜版面配置或動態內容的高階情境,請利用 IronPDF 对 JavaScript 渲染的支持:
// Example with JavaScript-generated content
var jsHtml = @"
<html>
<head>
<script>
window.onload = function() {
document.getElementById('dynamic').innerHTML =
'Generated on: ' + new Date().toLocaleString();
};
</script>
</head>
<body>
<h1>Dynamic Content Example</h1>
<div id='dynamic'></div>
</body>
</html>";
// Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500); // milliseconds
using var dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, @"C:\site\");
dynamicPdf.SaveAs("dynamic-content.pdf");
// Example with JavaScript-generated content
var jsHtml = @"
<html>
<head>
<script>
window.onload = function() {
document.getElementById('dynamic').innerHTML =
'Generated on: ' + new Date().toLocaleString();
};
</script>
</head>
<body>
<h1>Dynamic Content Example</h1>
<div id='dynamic'></div>
</body>
</html>";
// Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500); // milliseconds
using var dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, @"C:\site\");
dynamicPdf.SaveAs("dynamic-content.pdf");
Imports System
' Example with JavaScript-generated content
Dim jsHtml As String = "
<html>
<head>
<script>
window.onload = function() {
document.getElementById('dynamic').innerHTML =
'Generated on: ' + new Date().toLocaleString();
};
</script>
</head>
<body>
<h1>Dynamic Content Example</h1>
<div id='dynamic'></div>
</body>
</html>"
' Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500) ' milliseconds
Using dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, "C:\site\")
dynamicPdf.SaveAs("dynamic-content.pdf")
End Using
在處理外部資源時,您可能需要處理驗證或特殊標頭。 IronPDF 透過 HTTP 請求標頭功能支援此功能,讓您在擷取資源時能加入授權憑證或自訂標頭。
為何設定 BasePath 對外部資源至關重要?
這是程式碼產生的檔案:
正確設定 BasePath 可確保 HTML 中的所有相對參照皆能正確解析。 若缺少此檔案,IronPDF 將無法定位圖片、樣式表或腳本等外部資源。這在以下情況下尤為重要:
- 轉換引用本地檔案系統資源的 HTML
- 處理使用相對網址的內容管理系統
- 將現有網頁內容轉換為 PDF 格式
- 建立使用共用資源的範本
針對網路資源,請使用完整網址作為基礎路徑:
// Using a web URL as base path
var webBasedPdf = renderer.RenderHtmlAsPdf(
"<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>",
"https://mywebsite.com"
);
// Using a web URL as base path
var webBasedPdf = renderer.RenderHtmlAsPdf(
"<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>",
"https://mywebsite.com"
);
' Using a web URL as base path
Dim webBasedPdf = renderer.RenderHtmlAsPdf(
"<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>",
"https://mywebsite.com"
)
若需進一步控制 PDF 生成流程,請參閱 IronPDF 詳盡的文件,了解自訂邊距、頁面方向及 PDF 壓縮等功能,以針對各種使用情境優化輸出檔案。
常見問題
如何在 C# 中將簡單的 HTML 字串轉換為 PDF?
您可以使用 IronPDF 的 ChromePdfRenderer 類別及其 RenderHtmlAsPdf 方法,將 HTML 字串轉換為 PDF。只需建立渲染器的實例,將您的 HTML 字串傳遞給該方法,並儲存生成的 PdfDocument 物件即可。IronPDF 採用 Chrome 渲染引擎,以確保完美還原原始內容。
HTML 轉 PDF 功能使用哪種渲染引擎?
IronPDF 採用功能完整的 Google Chromium 引擎來將 HTML 渲染為 PDF。這確保您的 HTML 內容(包括 HTML5、CSS3 和 JavaScript)呈現效果與在現代網頁瀏覽器中完全一致。
我可以將帶有 CSS 樣式的 HTML 轉換為 PDF 嗎?
是的,IronPDF 支援將帶有 CSS 樣式的 HTML 轉換為 PDF。您可以在 HTML 字串中直接使用內嵌樣式,或透過「基礎 URL 與資源編碼」功能引用外部樣式表,以確保樣式化內容能正確呈現。
將 HTML 轉換為 PDF 的最快方法是什麼?
最快速的方法是使用 IronPDF 的靜態方法:IronPdf.ChromePdfRenderer.StaticRenderHtmlAsPdf("您的 HTML")。SaveAs("output.pdf")。這一行程式碼即可將您的 HTML 字串轉換並儲存為 PDF 檔案。
轉換 HTML 字串時,應如何處理外部資源?
IronPDF 允許您設定 PDF 中外部資源的 BasePath。這可確保在轉換過程中,HTML 中引用的圖片、樣式表及其他資源能正確載入。
將 HTML 轉換為 PDF 時,能否自訂 PDF 輸出格式?
是的,IronPDF 提供豐富的 RenderingOptions 選項,讓您能精細調整 PDF 輸出效果。您可以透過 ChromePdfRenderer 類別,控制頁面大小、邊距、頁首、頁尾以及生成的 PDF 的許多其他方面。
轉換後的 PDF 檔案可以進行哪些操作?
IronPDF 的 PdfDocument 物件提供多種 PDF 處理方法,包括合併 PDF、添加浮水印、設定安全性選項等。轉換後的 PDF 可依需求儲存至磁碟、以串流方式輸出,或進行後續處理。
在轉換外部來源的 HTML 時,該如何處理安全性問題?
在轉換外部來源的 HTML 時,IronPDF 允許您將 ChromePdfRenderer 的 EnableWebSecurity 屬性設為 true。此設定將停用本地磁碟存取及跨來源請求,以提升安全性。

