如何在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) 或浏览器窗口的情况下渲染 Web 内容的过程。 尽管 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. 下载 C# 库用于在 ASP.NET Core Web App 中将 Razor 视图转换为 PDF
  2. 创建一个新的 Razor 视图并编辑文件以显示数据
  3. 使用 RenderAsync 方法将 Razor 视图转换为 HTML
  4. 使用 RenderHtmlAsPdf 方法将 HTML 转换为 PDF
  5. 下载示例项目以快速入门

安装 Razor.Templating.Core 软件包 将 Razor 视图转换为 ASP.NET Core Web App 中的 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

将视图转换为 PDF 文件,您将需要一个 ASP.NET Core Web App (模型-视图-控制器) 项目。

添加视图

  • 右键单击“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 来访问多种功能,例如添加自定义文本,包括 HTML 页眉和页脚在生成的 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 () =>
{
    // 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,其中不需要GUI,可以节省资源。

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视图PDF转换需要什么设置?

在您的Program.cs中,确保ASP.NET Core Web应用程序配置正确以支持Razor视图,并引用必要的包,如Razor.Templating.Core和IronPDF,以便进行转换过程。

在哪里可以找到完整的Razor视图到PDF转换示例项目?

IronPDF网站上提供了一个完整的示例项目供下载。它包含所有必要的设置,以在ASP.NET Core Web App (Model-View-Controller) 项目中将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))

Chaknith Bin
软件工程师
Chaknith 在 IronXL 和 IronBarcode 工作。他在 C# 和 .NET 方面有着深厚的专业知识,帮助改进软件并支持客户。他从用户互动中获得的见解有助于更好的产品、文档和整体体验。
准备开始了吗?
Nuget 下载 16,154,058 | 版本: 2025.11 刚刚发布