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

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网页应用程序(.NET框架)MVC 是微软提供的一种 Web 应用框架。 它遵循一种称为模型-视图-控制器的结构化架构模式。(模型-视图-控制器 (MVC))组织和简化Web应用程序的开发。

IronPDF 扩展包

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

PM > Install-Package IronPdf.Extensions.Mvc.Framework
适用于PDF的C# NuGet库

安装使用 NuGet

安装包 IronPdf.Extensions.Mvc.Framework

将视图渲染为PDF文件

要将视图转换为PDF文件,您需要一个ASP.NET Web应用程序。(.NET框架)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
VB   C#

编辑控制器

导航到“Controllers”文件夹并打开“HomeController”文件。我们将添加“Persons”操作。 请参考下面的代码以获取指导:

在提供的代码中,首先创建了ChromePdfRenderer类。 要使用 RenderView 方法,您需要提供一个 HttpContext,指定 "Persons.cshtml" 文件的路径,并提供一个包含必要数据的列表。 在渲染视图时,用户可以使用RenderingOptions来自定义边距,添加自定义文本和 HTML 页眉和页脚并应用页码到生成的PDF文档中。

请注意
可使用以下代码将 PDF 文档下载到机器上: 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()
        {
            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")
            {
                // Provide the path to your View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                ChromePdfRenderer renderer = new ChromePdfRenderer();

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

                Response.Headers.Add("Content-Disposition", "inline");

                // View the PDF
                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()
        {
            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")
            {
                // Provide the path to your View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                ChromePdfRenderer renderer = new ChromePdfRenderer();

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

                Response.Headers.Add("Content-Disposition", "inline");

                // View the PDF
                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
'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
				' Provide the path to your View file
				Dim viewPath = "~/Views/Home/Persons.cshtml"

				Dim renderer As New ChromePdfRenderer()

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

				Response.Headers.Add("Content-Disposition", "inline")

				' View the PDF
				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
VB   C#

获得 PdfDocument 对象通过 RenderView 方法后,您可以对其进行各种改进和调整。 您可以将PDF转换为PDF/APDFUA格式、标志数字签名合并和拆分根据需要处理 PDF 文档。 此外,该库还使您能够旋转页面,插入注释书签打上明显的水印到 PDF 文件中。

添加视图

  • 右键单击新添加的Person操作,然后选择“添加视图”。

    右键单击 人员 操作

  • 选择“MVC 5 View”作为新的脚手架项。

    选择脚手架

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

    添加查看

    这将创建一个名为“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”文件。将“Person”导航项放置在“Home”之后。

    确保 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 项目

下载 ASP.NET MVC 项目

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

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

Chaknith related to 下载 ASP.NET MVC 项目

查克尼特·宾

软件工程师

Chaknith 是开发者中的福尔摩斯。他第一次意识到自己可能在软件工程方面有前途,是在他出于乐趣做代码挑战的时候。他的重点是 IronXL 和 IronBarcode,但他为能帮助客户解决每一款产品的问题而感到自豪。Chaknith 利用他从直接与客户交谈中获得的知识,帮助进一步改进产品。他的轶事反馈不仅仅局限于 Jira 票据,还支持产品开发、文档编写和市场营销,从而提升客户的整体体验。当他不在办公室时,他可能会在学习机器学习、编程或徒步旅行。