如何在 C# 中將 HTML 字串渲染為 PDF | IronPDF

如何在 C# 中將 HTML 字串轉換為 PDF

This article was translated from English: Does it need improvement?
Translated
View the article in English

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 渲染功能整合到專案中的開發人員。

Nuget Icon立即開始使用 NuGet 建立 PDF 檔案:

  1. 使用 NuGet 套件管理器安裝 IronPDF

    PM > Install-Package IronPdf

  2. 複製並運行這段程式碼。

    IronPdf.ChromePdfRender.StaticRenderHtmlAsPdf("<p>Hello World</p>").SaveAs("string-to-pdf.pdf");
  3. 部署到您的生產環境進行測試

    立即開始在您的專案中使用 IronPDF,免費試用!
    arrow pointer


如何將簡單的 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");
$vbLabelText   $csharpLabel

RenderHtmlAsPdf方法傳回一個PdfDocument對象,該類別用於保存 PDF 資訊。 此物件提供許多操作 PDF 的方法,包括 合併 PDF加入水印,以及 設定安全選項

當 HTML 字串從外部來源取得,且您需要停用本機磁碟存取或跨來源請求時,請將 ChromePdfRenderer.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>";

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>";

var styledPdf = renderer.RenderHtmlAsPdf(styledHtml);
styledPdf.SaveAs("styled-output.pdf");
$vbLabelText   $csharpLabel

生成的 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");
$vbLabelText   $csharpLabel

對於涉及複雜佈局或動態內容的進階方案,請利用 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
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
var dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, @"C:\site\");
dynamicPdf.SaveAs("dynamic-content.pdf");
$vbLabelText   $csharpLabel

在處理外部資產時,可能需要處理驗證或特殊標頭。 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"
);
$vbLabelText   $csharpLabel

如需對 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。這將禁用本機磁碟存取和跨來源請求,以增強安全性。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 17,527,568 | 版本: 2026.2 剛剛發布