How to Convert HTML String to PDF in C
IronPDF 使用 Chrome 渲染引擎以 C# 將 HTML 字串轉換為 PDF 文件,支援所有 HTML5、CSS3 和 JavaScript 內容,只需一行程式碼即可完成基本轉換。 該函式庫為 創建 PDF 提供了強大的功能,同時保持完美的渲染保真度。
IronPDF 讓開發人員可以輕鬆使用 C#、F# 和 VB.NET 為 .NET Core 和 .NET Framework 建立 PDF 文件。 IronPDF 支援將任何 HTML 字串渲染為 PDF,渲染過程使用功能完整的 Google Chromium 引擎版本。這可確保 HTML 內容在現代網頁瀏覽器中的顯示效果完全一樣,因此非常適合從動態 HTML 內容生成報表、發票和文件。
快速入門:數秒內將 HTML 字串轉換為 PDF
使用 IronPDF 將 HTML 字串轉換成 PDF 檔案。 本指南示範如何在 C# 中以最少的程式碼將 HTML 字串轉換為 PDF 文件。 非常適合需要將 PDF 渲染功能整合到專案中的開發人員。
最小工作流程(5 個步驟)
- 從 NuGet 下載 IronPDF C# 庫
- 實例化 PDF 渲染器並傳遞 HTML 字串
- 配置 PDF 中外部資源的 BasePath
- 配置渲染選項以微調輸出 PDF
- 儲存並下載生成的 PDF
如何將簡單的 HTML 字串轉換為 PDF?
以下是 IronPDF 使用 RenderHtmlAsPdf 方法將 HTML 字串渲染為 PDF 的範例。 該參數是一個HTML字串,將被渲染成PDF檔案。 此方法屬於 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、添加浮水印以及設定安全性選項。
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 內容,請使用內嵌樣式增強您的 HTML 字串,或使用 Base URLs & Asset Encoding 功能參考外部樣式表:
// 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 Request Header 功能提供支援,讓您在取得資源時包含授權標記或自訂標頭。
為什麼設定 BasePath 對外部資源很重要?
這是程式碼產生的檔案:
正確設定 BasePath 可確保能正確解析 HTML 中的所有相對引用。 沒有它,IronPDF 無法定位圖片、樣式表或腳本等外部資源。這在以下情況尤其重要:
1.轉換引用本機檔案系統資源的 HTML 2.使用相對 URL 的內容管理系統工作 3.將現有的網頁內容轉換為 PDF 格式 4.建立使用共用資產的範本
對於網頁型資源,請使用完整的 URL 作為基本路徑:
// 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)在現代 Web 瀏覽器中的顯示效果完全一樣。
我可以將採用 CSS 設定的 HTML 轉換成 PDF 嗎?
是的,IronPDF 支援将帶有 CSS 样式的 HTML 轉换為 PDF。您可以直接在 HTML 字串中使用內嵌樣式,或使用基礎 URL 與資產編碼功能引用外部樣式表,以確保樣式內容的正確呈現。
將 HTML 轉換成 PDF 的最快方法是什麼?
最快速的方法是使用 IronPDF 的靜態方法:IronPdf.ChromePdfRenderer.StaticRenderHtmlAsPdf("Your 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。這將禁用本機磁碟存取和跨來源請求,以增強安全性。

