如何在 ASP.NET Core 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 Core Web 应用 MVC(模型-视图-控制器)是由Microsoft提供的一个Web应用程序,用于使用ASP.NET Core构建Web应用程序。

IronPDF 扩展包

IronPdf.Extensions.Mvc.Core 包 是主 IronPdf 包的一个扩展。 IronPdf.Extensions.Mvc.Core 和 IronPdf 这两个包都是在 ASP.NET Core MVC 中将视图渲染为PDF文档所必需的。

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

安装使用 NuGet

安装包 IronPdf.Extensions.Mvc.Core

将视图渲染为PDF文件

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

添加一个模型类

  • 导航到“Models”文件夹
  • 创建一个名为“Person”的新C#类文件。这个类将作为表示个人数据的模型。 使用以下代码片段:
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-mvc-core-model.cs
namespace ViewToPdfMVCCoreSample.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 ViewToPdfMVCCoreSample.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”文件。我们将仅对HomeController进行更改,并添加“Persons”操作。 请参考下面的代码以获取指导:

下面的代码首先实例化 ChromePdfRenderer 类,将一个 IRazorViewRenderer、指向我们的 "Persons.cshtml" 的路径以及包含所需数据的列表传递给 RenderRazorViewToPdf 方法。 用户可以使用RenderingOptions来访问一系列功能,例如添加自定义文本,包括 HTML 页眉和页脚在生成的 PDF 中定义自定义页边距,并应用页码.

请注意
可使用以下代码在浏览器中查看 PDF 文档: 文件(pdf.BinaryData、"application/pdf"). 然而,在浏览器中查看PDF文件后下载该文件,会导致PDF文件损坏。

using IronPdf.Extensions.Mvc.Core;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using ViewToPdfMVCCoreSample.Models;
namespace ViewToPdfMVCCoreSample.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IRazorViewRenderer _viewRenderService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public HomeController(ILogger<HomeController> logger, IRazorViewRenderer viewRenderService, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;
            _viewRenderService = viewRenderService;
            _httpContextAccessor = httpContextAccessor;
        }
        public IActionResult Index()
        {
            return View();
        }
        public async Task<IActionResult> 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 (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
            {
                ChromePdfRenderer renderer = new ChromePdfRenderer();
                // Render View to PDF document
                PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
                Response.Headers.Add("Content-Disposition", "inline");
                // Output PDF document
                return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
            }
            return View(persons);
        }
        public IActionResult Privacy()
        {
            return View();
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
using IronPdf.Extensions.Mvc.Core;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using ViewToPdfMVCCoreSample.Models;
namespace ViewToPdfMVCCoreSample.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IRazorViewRenderer _viewRenderService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public HomeController(ILogger<HomeController> logger, IRazorViewRenderer viewRenderService, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;
            _viewRenderService = viewRenderService;
            _httpContextAccessor = httpContextAccessor;
        }
        public IActionResult Index()
        {
            return View();
        }
        public async Task<IActionResult> 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 (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
            {
                ChromePdfRenderer renderer = new ChromePdfRenderer();
                // Render View to PDF document
                PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
                Response.Headers.Add("Content-Disposition", "inline");
                // Output PDF document
                return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
            }
            return View(persons);
        }
        public IActionResult Privacy()
        {
            return View();
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

在使用 RenderRazorToPdf 方法后,您将收到一个 PdfDocument 对象,该对象可以进一步增强和修改。 将 PDF 转换的灵活性PDF/APDFUA格式,添加您的数字签名合并和拆分根据需要处理PDF文档。 此外,该库允许您旋转页面,插入注释书签印上独特的水印到 PDF 文件上。

添加视图

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

    右键单击 人员 操作

  • 选择“Razor 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”之后。

    确保 asp-action 属性的值与我们的文件名完全匹配,在这种情况下是“Persons”。

<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container-fluid">
            <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ViewToPdfMVCCoreSample</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Persons">Person</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>
<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container-fluid">
            <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ViewToPdfMVCCoreSample</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                    aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Persons">Person</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>
HTML

编辑 Program.cs 文件

我们将在依赖注入中注册IHttpContextAccessor和IRazorViewRenderer接口。(DI)容器。 请查看下面的代码,供您参考。

using IronPdf.Extensions.Mvc.Core;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
// Register IRazorViewRenderer here
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
using IronPdf.Extensions.Mvc.Core;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
// Register IRazorViewRenderer here
builder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

运行项目

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

执行 ASP.NET Core MVC 项目

下载 ASP.NET Core MVC 项目

您可以下载本指南的完整代码。它是一个压缩文件,您可以在Visual Studio中将其打开为一个ASP.NET Core Web应用程序。(模型-视图-控制器)项目。

点击此处下载项目。

查克尼特·宾

软件工程师

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