如何使用 C# 中的 Razor 無頭模式將 CSHTML 轉換為 PDF | IronPDF

How to Convert Razor Views to PDFs Headlessly

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

「無頭渲染」一詞是指在沒有圖形用戶界面 (GUI) 或瀏覽器窗口的情況下渲染網頁內容的過程。 雖然IronPdf.Extensions.Razor 套件非常有用,但它不提供無頭渲染功能。 無頭渲染可以解決 IronPdf.Extensions.Razor 套件無法滿足的用例差距。

我們將使用Razor.Templating.Core 套件將 cshtml (Razor 視圖) 轉換為 HTML,然後使用 IronPDF 從中生成 PDF 文件。

快速入門:在幾秒鐘內將 Razor 視圖轉換為 PDF

使用 IronPDF 的無頭轉換輕鬆將 Razor 視圖轉換為 PDF 文件。 使用 IronPdf.HtmlToPdf.StaticRender.RenderHtmlAsPdf 方法快速將您的 Razor 視圖中派生的 HTML 內容渲染為具有專業品質的 PDF。 這種精簡的方法確保過程順暢高效,非常適合在 ASP.NET Core 環境中工作的開發人員。 體驗 IronPDF 的簡便性和高性能,以滿足您的文檔需求。

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    var html = await RazorTemplateEngine.RenderAsync("Views/Template.cshtml", model); 
    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf(html).SaveAs("output.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer
class="hsg-featured-snippet">

最少工作流程(5 步)

  1. 下載將 Razor 視圖轉換為 PDF 的 C# 函式庫,用於 ASP.NET Core Web 應用
  2. 創建一個新的 Razor 視圖並編輯文件以顯示數據
  3. 使用RenderAsync方法將 Razor 視圖轉換為 HTML
  4. 使用RenderHtmlAsPdf方法將 HTML 轉換為 PDF
  5. 下載範例項目以快速開始

安裝Razor.Templating.Core 套件,以在 ASP.NET Core Web 應用中將 Razor 視圖轉換為 HTML 文件。

# Install the Razor.Templating.Core package using NuGet Package Manager
Install-Package Razor.Templating.Core
# Install the Razor.Templating.Core package using NuGet Package Manager
Install-Package Razor.Templating.Core
SHELL

將 Razor 視圖渲染為 PDF

您需要一個 ASP.NET Core Web App(模型-視圖-控制器)項目來將視圖轉換為 PDF 文件。

添加視圖

  • 右鍵單擊“Home”文件夾。 選擇“添加”和“添加視圖”。
  • 創建一個空的 Razor 視圖並將其命名為“Data.cshtml”。

添加視圖

編輯 Data.cshtml 文件

添加您希望渲染為 PDF 的 HTML 字符串:

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    <tr>
        <td>John Doe</td>
        <td>Software Engineer</td>
        <td>Experienced software engineer specializing in web development.</td>
    </tr>
    <tr>
        <td>Alice Smith</td>
        <td>Project Manager</td>
        <td>Seasoned project manager with expertise in agile methodologies.</td>
    </tr>
    <tr>
        <td>Michael Johnson</td>
        <td>Data Analyst</td>
        <td>Skilled data analyst proficient in statistical analysis and data visualization.</td>
    </tr>
</table>
<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    <tr>
        <td>John Doe</td>
        <td>Software Engineer</td>
        <td>Experienced software engineer specializing in web development.</td>
    </tr>
    <tr>
        <td>Alice Smith</td>
        <td>Project Manager</td>
        <td>Seasoned project manager with expertise in agile methodologies.</td>
    </tr>
    <tr>
        <td>Michael Johnson</td>
        <td>Data Analyst</td>
        <td>Skilled data analyst proficient in statistical analysis and data visualization.</td>
    </tr>
</table>
HTML

編輯 Program.cs 文件

在“Program.cs”文件中添加以下代碼。 以下代碼使用Razor.Templating.Core庫中的RenderAsync方法將 Razor 視圖轉換為 HTML。 其次,它實例化ChromePdfRenderer類,並將返回的 HTML 字符串傳遞給RenderHtmlAsPdf方法。 用戶可以利用 RenderingOptions 訪問一系列功能,例如在生成的 PDF 中添加自定義文本、包括 HTML 頁眉和頁腳、定義自定義邊距、應用頁面編號。

app.MapGet("/PrintPdf", async () =>
{
    // Set your IronPDF license key
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

    // Enable detailed logging for troubleshooting
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

    // Render the Razor view to an HTML string
    string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");

    // Create a new instance of ChromePdfRenderer 
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the HTML string as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");

    // Return the PDF file as a response
    return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", async () =>
{
    // Set your IronPDF license key
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

    // Enable detailed logging for troubleshooting
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

    // Render the Razor view to an HTML string
    string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");

    // Create a new instance of ChromePdfRenderer 
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the HTML string as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");

    // Return the PDF file as a response
    return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", Async Function()
	' Set your IronPDF license key
	IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

	' Enable detailed logging for troubleshooting
	IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All

	' Render the Razor view to an HTML string
	Dim html As String = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")

	' Create a new instance of ChromePdfRenderer
	Dim renderer As New ChromePdfRenderer()

	' Render the HTML string as a PDF document
	Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot")

	' Return the PDF file as a response
	Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
End Function)
$vbLabelText   $csharpLabel

更改資產鏈接

導航到“Views”文件夾 -> “Shared”文件夾 -> “_Layout.cshtml”文件。在鏈接標籤中,將“~/”更改為“./”。

這很重要,因為“~/”與 IronPDF 效果不佳。

運行項目

這將向您展示如何運行項目並生成 PDF 文檔。

運行 ASP.NET Core MVC 項目

輸出 PDF

下載 ASP.NET Core MVC 項目

您可以下載該指南的完整代碼。它是壓縮文件,可以在 Visual Studio 中作為 ASP.NET Core Web App(模型-視圖-控制器)項目打開。

點擊這裡下載項目。

常見問題解答

如何以無頭模式將 Razor 視圖轉換為 PDF?

若要以無頭方式將 Razor 視圖轉換為 PDF,請使用 Razor.Templating.Core 套件將 Razor 視圖渲染為 HTML。然後,利用 IronPDF 的RenderHtmlAsPdf方法將 HTML 轉換為 PDF 文件。

什麼是無頭渲染?它有什麼用途?

無頭渲染是指在不顯示圖形使用者介面的情況下產生網頁內容的過程。它適用於伺服器端渲染任務,例如產生 PDF 文件,這類任務不需要圖形使用者介面,可以節省資源。

IronPdf.Extensions.Razor 套件可以用於無頭 PDF 轉換嗎?

不,IronPdf.Extensions.Razor 套件不支援無頭渲染。請使用 Razor.Templating.Core 將 Razor 視圖轉換為 HTML,然後再使用 IronPDF 將 HTML 轉換為 PDF。

Razor.Templating.Core 套件在 PDF 轉換中扮演什麼角色?

Razor.Templating.Core 套件用於將 Razor 視圖轉換為 HTML 字串。然後可以使用 IronPDF 的RenderHtmlAsPdf方法將此 HTML 轉換為 PDF。

為什麼我需要修改 _Layout.cshtml 檔案才能與 IronPDF 相容?

您應該將 _Layout.cshtml 檔案中連結標籤中的“~/”變更為“./”,因為 IronPDF 對“~/”路徑的處理有問題。使用“./”可以確保在 PDF 生成過程中正確解析路徑。

如何排查將 Razor 視圖轉換為 PDF 時出現的問題?

IronPdf.Logging.Logger.LoggingMode設定為IronPdf.Logging.Logger.LoggingModes.All ,啟用 IronPDF 中的詳細日誌記錄。這將提供有助於診斷和解決轉換過程中問題的詳細資訊日誌。

在 Program.cs 中,Razor View 進行 PDF 轉換需要哪些設定?

在 Program.cs 檔案中,請確保 ASP.NET Core Web 應用程式已正確配置為支援 Razor 視圖,並參考必要的套件,例如 Razor.Templating.Core 和 IronPDF,以簡化轉換過程。

哪裡可以找到 Razor View 轉 PDF 的完整範例項目?

IronPDF 網站提供了一個完整的範例專案供下載。它包含了在 ASP.NET Core Web 應用程式(模型-視圖-控制器)專案中將 Razor 視圖轉換為 PDF 所需的所有設定。

IronPDF 以無頭模式將 Razor 視圖轉換為 PDF 時是否相容於 .NET 10?

是的。 IronPDF 支援 .NET 10,包括專為 .NET 10.0 框架設計的 IronPdf.Extensions.Razor 包,使其相容於 .NET 10 下的無頭 Razor 視圖到 PDF 的轉換。 ([nuget.org](https://www.nuget.org/packages/IronPdf.Extensions.Razor?utm_source=openai))

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: sections/author_component.php

Line Number: 18

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 18
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: sections/author_component.php

Line Number: 38

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 38
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: sections/author_component.php

Line Number: 48

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 48
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

準備好開始了嗎?
Nuget 下載 16,154,058 | 版本: 2025.11 剛剛發布