如何在 ASP.NET Core C# 中将视图转换为 PDF

How to Convert Views to PDFs in ASP.NET MVC

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

视图是 ASP.NET 框架中用于在 Web 应用程序中生成 HTML 标记的组件。 它是模型-视图-控制器 (MVC) 模式的一部分,通常用于 ASP.NET MVC 和 ASP.NET Core MVC 应用程序。 视图负责通过动态呈现 HTML 内容来向用户呈现数据。

ASP.NET Web 应用程序 (.NET Framework) MVC 是由 Microsoft 提供的 Web 应用程序框架。 它遵循一种称为模型-视图-控制器 (MVC) 的结构化架构模式,以组织和简化 Web 应用程序的开发。

  • 模型:管理数据、业务逻辑和数据完整性。
  • 视图:呈现用户界面并渲染信息。
  • 控制器:处理用户输入、处理请求并协调模型和视图之间的交互。

IronPDF 简化了在 ASP.NET MVC 项目中从视图创建 PDF 文件的过程。 这使得在 ASP.NET MVC 中生成 PDF 变得简单而直接。

快速入门:轻松将 ASP.NET MVC 视图转换为 PDF

了解如何使用 IronPDF 快速将 ASP.NET MVC 视图转换为 PDF 文档。 只需几行代码,您即可将 CSHTML 视图渲染为高质量的 PDF,从而增强应用程序的功能。 IronPDF 简化了这一过程,使所有级别的开发人员都能掌握。 通过将 IronPDF 集成到您的 ASP.NET Core 项目中,轻松从视图生成 PDF。

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.

    // Install-Package IronPdf.Extensions.Razor
    var pdf = new IronPdf.ChromePdfRenderer.RenderRazorToPdf(this.ControllerContext);
  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. 下载用于在 ASP.NET MVC 中将视图转换为 PDF 的 C# 库
  2. 为数据添加模型类
  3. 在控制器中创建一个 "Person" 动作并使用 RenderView 方法
  4. 使用 MVC 5 视图脚手架添加视图
  5. 下载示例项目以快速入门

IronPDF 扩展包

IronPdf.Extensions.Mvc.Framework 包是主IronPdf 包的扩展。 在 ASP.NET MVC 中将视图渲染为 PDF 文档需要同时使用 IronPdf.Extensions.Mvc.Framework 和 IronPdf 包。

Install-Package IronPdf.Extensions.Mvc.Framework
class="products-download-section">
data-modal-id="trial-license-after-download">
class="product-image"> C# NuGet Library for PDF
class="product-info">

使用 NuGet 安装

class="copy-nuget-row">
Install-Package IronPdf.Extensions.Mvc.Framework
class="copy-button">
class="nuget-link">nuget.org/packages/IronPdf.Extensions.Mvc.Framework/

将视图渲染为 PDF

要将视图转换为 PDF 文件,您需要一个 ASP.NET Web 应用程序 (.NET Framework) MVC 项目。

添加模型类

  • 导航到 "Models" 文件夹
  • 创建一个名为 "Person" 的新 C# 类文件。这个类将作为表示个人数据的模型。 使用以下占位符进行指导:
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-mvc-framework-model.cs
namespace ViewToPdfMVCSample.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}
Namespace ViewToPdfMVCSample.Models
	Public Class Person
		Public Property Id() As Integer
		Public Property Name() As String
		Public Property Title() As String
		Public Property Description() As String
	End Class
End Namespace
$vbLabelText   $csharpLabel

编辑控制器

导航到 "Controllers" 文件夹并打开 "HomeController" 文件。我们将添加 "Persons" 动作。 请参考下面的代码进行指导:

在提供的代码中,首先创建了ChromePdfRenderer类。 要使用 RenderView 方法,您需要提供一个 HttpContext,指定 "Persons.cshtml" 文件的路径,并提供一个包含必要数据的列表。 When rendering the View, users have the option to utilize RenderingOptions to customize margins, add custom text and HTML headers and footers, and apply page numbers to the resulting PDF document.

请注意The PDF document can be downloaded to the machine using the following code: File(pdf.BinaryData, "application/pdf", "viewToPdfMVC.pdf").

using IronPdf;
using System.Collections.Generic;
using System.Web.Mvc;
using ViewToPdfMVCSample.Models;

namespace ViewToPdfMVCSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // GET: Person
        public ActionResult Persons()
        {
            // Create a list of Person objects
            var persons = new List<Person>
            {
                new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
                new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
                new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
            };

            if (HttpContext.Request.HttpMethod == "POST")
            {
                // Define the path to the View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                // Instantiate the ChromePdfRenderer
                ChromePdfRenderer renderer = new ChromePdfRenderer();

                // Render the view to a PDF document
                PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);

                // Set headers to view the PDF in-browser
                Response.Headers.Add("Content-Disposition", "inline");

                // Return the generated PDF file
                return File(pdf.BinaryData, "application/pdf");
            }
            return View(persons);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}
using IronPdf;
using System.Collections.Generic;
using System.Web.Mvc;
using ViewToPdfMVCSample.Models;

namespace ViewToPdfMVCSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // GET: Person
        public ActionResult Persons()
        {
            // Create a list of Person objects
            var persons = new List<Person>
            {
                new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
                new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
                new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
            };

            if (HttpContext.Request.HttpMethod == "POST")
            {
                // Define the path to the View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                // Instantiate the ChromePdfRenderer
                ChromePdfRenderer renderer = new ChromePdfRenderer();

                // Render the view to a PDF document
                PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);

                // Set headers to view the PDF in-browser
                Response.Headers.Add("Content-Disposition", "inline");

                // Return the generated PDF file
                return File(pdf.BinaryData, "application/pdf");
            }
            return View(persons);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}
Imports IronPdf
Imports System.Collections.Generic
Imports System.Web.Mvc
Imports ViewToPdfMVCSample.Models

Namespace ViewToPdfMVCSample.Controllers
	Public Class HomeController
		Inherits Controller

		Public Function Index() As ActionResult
			Return View()
		End Function

		' GET: Person
		Public Function Persons() As ActionResult
			' Create a list of Person objects
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
			Dim persons_Conflict = New List(Of Person) From {
				New Person With {
					.Name = "Alice",
					.Title = "Mrs.",
					.Description = "Software Engineer"
				},
				New Person With {
					.Name = "Bob",
					.Title = "Mr.",
					.Description = "Software Engineer"
				},
				New Person With {
					.Name = "Charlie",
					.Title = "Mr.",
					.Description = "Software Engineer"
				}
			}

			If HttpContext.Request.HttpMethod = "POST" Then
				' Define the path to the View file
				Dim viewPath = "~/Views/Home/Persons.cshtml"

				' Instantiate the ChromePdfRenderer
				Dim renderer As New ChromePdfRenderer()

				' Render the view to a PDF document
				Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)

				' Set headers to view the PDF in-browser
				Response.Headers.Add("Content-Disposition", "inline")

				' Return the generated PDF file
				Return File(pdf.BinaryData, "application/pdf")
			End If
			Return View(persons_Conflict)
		End Function

		Public Function About() As ActionResult
			ViewBag.Message = "Your application description page."
			Return View()
		End Function

		Public Function Contact() As ActionResult
			ViewBag.Message = "Your contact page."
			Return View()
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

一旦通过 RenderView 方法获取PdfDocument对象,您可以对其进行各种改进和调整。 You can convert the PDF to PDFA or PDFUA formats, sign digital signature to the created PDF, or merge and split PDF documents as required. Moreover, the library enables you to rotate pages, insert annotations or bookmarks, and apply distinct watermarks to your PDF files.

添加视图

  • 右键单击新添加的 Persons 操作并选择“添加视图”。

右键单击 Persons 动作

  • 为新的脚手架项目选择 "MVC 5 视图"。

选择脚手架

  • 选择“列表”模板和“Person”模型类。

添加视图

这将创建一个名为“Persons”的 .cshtml 文件。

  • 导航到“Views”文件夹 -> “Home”文件夹 -> “Persons.cshtml”文件。

要添加一个调用“Persons”操作的按钮,请使用下面的代码:

@using (Html.BeginForm("Persons", "Home", FormMethod.Post))
{
    <input type="submit" value="Print Person" />
}
@using (Html.BeginForm("Persons", "Home", FormMethod.Post))
{
    <input type="submit" value="Print Person" />
}
HTML

在顶部导航栏添加一个部分

  • 在 "Views" 文件夹中,导航到 "Shared" 文件夹 -> "_Layout.cshtml" 文件。在 "Home" 之后放置 "Person" 导航项。

确保 ActionLink 方法的值与我们的文件名完全匹配,在这种情况下是 "Persons"。

<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
    <div class="container">
        @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Persons", "Persons", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
            </ul>
        </div>
    </div>
</nav>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
    <div class="container">
        @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Persons", "Persons", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
            </ul>
        </div>
    </div>
</nav>
HTML

运行项目

这将向您展示如何运行项目并生成 PDF 文档。

执行 ASP.NET MVC 项目

输出 PDF 文件

下载 ASP.NET MVC 项目

您可以下载本指南的完整代码。它作为一个压缩文件提供,可以在 Visual Studio 中作为 ASP.NET Web 应用程序 (.NET Framework) MVC 项目打开。

下载用于 PDF 转换的 MVC 示例项目

常见问题解答

我如何在 ASP.NET Core MVC 中将视图转换为 PDF?

您可以使用 IronPDF 库在 ASP.NET Core MVC 中将视图转换为 PDF。通过 NuGet 安装 IronPdf.Extensions.Mvc.Framework 包,并使用 ChromePdfRenderer 类将视图渲染为 PDF 文档。

在 ASP.NET MVC 中渲染视图为 PDF 文档所必需的是什么?

要在 ASP.NET MVC 中将视图渲染为 PDF 文档,您需要 IronPDF 库和 ChromePdfRenderer 类,该类需要 HttpContext、视图路径以及用于生成 PDF 的数据列表。

如何在 ASP.NET 应用程序中使用 IronPDF 自定义 PDF 输出?

IronPDF 允许使用 RenderingOptions 自定义 PDF 输出。您可以调整边距、添加自定义页眉和页脚,并包含页码以根据需要调整 PDF 文档。

在 ASP.NET MVC 中设置用于 PDF 生成的模型类涉及哪些步骤?

要在 ASP.NET MVC 中设置模型类,请导航到 'Models' 文件夹,创建一个新的 C# 类文件,并定义包含您需要的用于 PDF 生成的数据结构的类。

如何在 ASP.NET MVC 中将 PDF 生成按钮集成到视图中?

要在 ASP.NET MVC 中将 PDF 生成按钮集成到视图中,您可以在视图的 HTML 标记中添加一个按钮元素,并将其链接到您的控制器中的一个操作,该操作使用 IronPDF 将视图渲染为 PDF。

在 ASP.NET MVC 中添加视图的过程是什么?

要在 ASP.NET MVC 中添加视图,请在控制器中右键单击所需的操作,选择“添加视图”,选择“MVC 5 视图”作为生成项,并选择合适的模板和模型类。

我在哪里可以找到在 ASP.NET MVC 中将视图转换为 PDF 的示例项目?

您可以从 IronPDF 网站下载一个完整的 MVC 示例项目用于 PDF 转换,其中包括一个可在 Visual Studio 中打开的压缩文件用于实际实施。

如何在 ASP.NET MVC 项目中安装 IronPDF?

通过 NuGet 包管理器使用以下命令在 ASP.NET MVC 项目中安装 IronPDF:Install-Package IronPdf.Extensions.Mvc.Framework

如果在 ASP.NET MVC 中 PDF 生成失败,有哪些常见的故障排除步骤?

如果在 ASP.NET MVC 中 PDF 生成失败,确保 IronPDF 包已正确安装,检查传递给 ChromePdfRenderer 的路径和上下文,并验证视图和数据是否已正确渲染。

IronPDF 是否兼容 .NET 10?升级到 .NET 10 有哪些好处?

是的——IronPDF 与 .NET 10 完全兼容。升级后可带来运行时改进,例如减少堆分配、提高内存使用率、增强 HTML 到 PDF 的渲染性能,以及访问新的语言特性和框架增强功能。

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