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

How to Convert HTML String to PDF in C

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中輕鬆建立PDF文件,適用於.NET Core和.NET Framework。 IronPDF支持將任何HTML字串轉換為PDF,渲染過程使用完全功能的Google Chromium引擎。這確保HTML內容的顯示與現代網頁瀏覽器中的完全一致,是從動態HTML內容生成報告、發票和文件的理想選擇。

快速入門:在幾秒鐘內將HTML字串轉換為PDF

使用IronPDF將HTML字串轉換為PDF文件。 本指南演示如何使用最少的程式碼在C#中將HTML字串轉換為PDF文件。 非常適合需要將PDF渲染功能整合到專案中的開發者。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 複製並運行這段程式碼片段。

    IronPdf.ChromePdfRenderer.StaticRenderHtmlAsPdf("<p>Hello World</p>").SaveAs("string-to-pdf.pdf");
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPDF,透過免費試用

    arrow pointer


我如何將簡單的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#
using var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf

' Instantiate Renderer
Dim renderer As New ChromePdfRenderer()

' Create a PDF from a HTML string using VB.NET
Using pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
    ' Export to a file or Stream
    pdf.SaveAs("output.pdf")
End Using
$vbLabelText   $csharpLabel

PdfDocument物件,該物件保存PDF資訊並提供操作PDF的方法,包括合併PDF新增水印以及設置安全選項

〔在ASP.NET Core、Blazor或背景服務中,建議使用異步變體RenderHtmlAsPdfAsync以避免阻塞執行緒。 返回的using塊中。 ChromePdfRenderer是執行緒安全的,可以實例化一次並跨請求重用,以提高性能。)

當從外部來源獲取HTML字串並需要禁用本地磁碟存取或跨源請求時,請在渲染前將IronPdf.Installation.EnableWebSecurity設置為true。 這是一個靜態全域設置,而不是渲染器上的實例屬性。

:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf-3.cs
// Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = true;
' Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = True
$vbLabelText   $csharpLabel

對於包含CSS樣式的複雜HTML內容,請增強您的HTML字串,使用內聯樣式或引用外部樣式表,使用基本URL和資產編碼功能:

:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf-4.cs
// 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
$vbLabelText   $csharpLabel

生成的PDF長什麼樣?

這是程式碼生成的文件:

生成的PDF保持了從HTML中獲得的精確格式和樣式,使其非常適合用於生成PDF報告或將網頁內容轉換為可列印文件。

Icon Quote related to 生成的PDF長什麼樣?

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic related to 生成的PDF長什麼樣?

Milan Jovanovic

Microsoft MVP

查看案例研究
Icon Quote related to 生成的PDF長什麼樣?

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle related to 生成的PDF長什麼樣?

Brent Matzelle

首席技術官,OPYN

查看案例研究
Icon Quote related to 生成的PDF長什麼樣?

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones related to 生成的PDF長什麼樣?

David Jones

首席軟體工程師,Agorus Build

查看案例研究

如何在將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
using var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf

' Instantiate Renderer
Dim renderer As 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
Using myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
    myAdvancedPdf.SaveAs("html-with-assets.pdf")
End Using
$vbLabelText   $csharpLabel

對於涉及複雜佈局或動態內容的高級場景,利用IronPDF對JavaScript渲染的支持:

:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf-6.cs
// 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.IO

' 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
$vbLabelText   $csharpLabel

在處理外部資產時,您可能需要處理身份驗證或特殊標頭。 IronPDF通過HTTP請求標頭功能支持這一點,允許您在獲取資源時包含授權令牌或自定義標頭。

為什麼設定BasePath對於外部資源至關重要?

這是程式碼生成的文件:

正確設定BasePath確保您的HTML中的所有相對參考都能正確解析。 未這樣做的話,IronPDF無法找到外部資源,如圖像、樣式表或腳本。這在以下情況中特別重要:

  1. 轉換引用本地檔案系統資源的HTML
  2. 設法與使用相對URL的內容管理系統協作
  3. 將現有網頁內容遷移到PDF格式
  4. 建立使用共享資產的範本

對於基於網頁的資源,請使用完整URL作為基本路徑:

:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf-7.cs
// 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"
);
Dim 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,看起來與現代網頁瀏覽器中一樣。

我可以將帶有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中配置外部資源的基底路徑。這確保了在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擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 20,296,129 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想快速獲得證明嗎? PM > Install-Package IronPdf
執行範例 看您的HTML變成PDF。