视图是 ASP.NET Framework中用于在 Web 应用程序中生成 HTML 标记的组件。 它是模型-视图-控制器(MVC)模式的一部分,常用于 ASP.NET MVC 和 ASP.NET Core MVC 应用程序。 视图负责通过动态呈现 HTML 内容向用户展示数据。 视图通常使用 Razor 语法,这是一种将基于服务器的代码嵌入网页的标记语法,使其成为创建数据驱动型 PDF 文档的强大工具。
快速入门:在ASP.NET Core中将 CSHTML 转换为 PDF
using IronPDF for .NET 将 ASP.NET Core MVC 视图转换为 PDF。 只需一行代码,即可将您的.cshtml文件渲染为PDF文档。 将此功能直接集成到您的 MVC 应用程序中,以便从动态 HTML 视图无缝生成 PDF。 请按照本指南设置环境并开始转换。
1Install IronPDF with NuGet Package Manager
PM > Install-Package IronPdf
Install-Package IronPdf
2复制并运行这段代码。
// using IronPdf.Extensions.Mvc.CorenewIronPdf.ChromePdfRenderer().RenderRazorViewToPdf(HttpContext, "Views/Home/Report.cshtml", model).SaveAs("report.pdf");
// using IronPdf.Extensions.Mvc.Core
new IronPdf.ChromePdfRenderer().RenderRazorViewToPdf(HttpContext, "Views/Home/Report.cshtml", model).SaveAs("report.pdf");
您需要一个 ASP.NET Core Web App(模型-视图-控制器)项目来将视图转换为 PDF 文件。 该过程涉及创建一个控制器操作,使用IronPDF的RenderRazorViewToPdf方法将您的Razor视图转换为PDF文档。 这种方法充分利用了 Razor 语法的全部功能,使您能够创建具有动态内容的复杂、数据驱动型 PDF。
我应该使用哪种项目类型?
using ASP.NET Core Web App(模型-视图-控制器)模板,以获得与 IronPDF 视图渲染功能的最佳兼容性。 该项目类型为视图渲染提供了必要的基础设施,包括 Razor 视图引擎和适当的路由。 对于现有项目,应确保它们遵循 MVC 模式并安装了所需的视图渲染功能。
我可以使用最小化 API 吗?
虽然 Minimal API 没有内置视图支持,但您仍然可以使用 IronPDF 的 HTML 到 PDF 转换功能。 对于基于视图的 PDF 生成,请使用传统的 MVC 方法或考虑将 Razor Pages 作为替代方法。
namespace ViewToPdfMVCCoreSample.Models{ public class Person { public intId { get; set; } public stringName { get; set; } public stringTitle { get; set; } public stringDescription { get; set; } }}
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; }
}
}
NamespaceViewToPdfMVCCoreSample.Models Public Class Person Public Property Id() AsInteger Public Property Name() AsString Public Property Title() AsString Public Property Description() AsString End ClassEndNamespace
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
为什么我需要生成 PDF 的模型?
模型提供结构化数据,可传递给视图进行渲染。 这种关注点的分离确保了 PDF 生成逻辑的简洁性和可维护性。 模型是控制器与视图之间的契约,可确保类型安全并在 Razor 视图中启用 IntelliSense 支持。
哪些数据类型最适合使用视图?
简单的数据类型和集合最适合生成 PDF。 可以使用复杂的嵌套对象,但可能需要额外的视图逻辑。 为获得最佳性能,请在控制器中将复杂的数据结构扁平化,然后再将其传递给视图。 当您的领域模型过于复杂时,请考虑使用专为 PDF 输出设计的 ViewModels。
下面是一个适合生成 PDF 的复杂模型结构示例:
public class InvoiceViewModel{ public stringInvoiceNumber { get; set; } public DateTimeInvoiceDate { get; set; } public decimalTotalAmount { get; set; } public List<InvoiceLineItem> LineItems { get; set; } public CustomerInfoCustomer { get; set; } // Computed property for PDF display public stringFormattedTotal => TotalAmount.ToString("C");}public class InvoiceLineItem{ public stringDescription { get; set; } public intQuantity { get; set; } public decimalUnitPrice { get; set; } public decimalLineTotal => Quantity * UnitPrice;}public class CustomerInfo{ public stringName { get; set; } public stringEmail { get; set; } public stringAddress { get; set; }}
public class InvoiceViewModel
{
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public decimal TotalAmount { get; set; }
public List<InvoiceLineItem> LineItems { get; set; }
public CustomerInfo Customer { get; set; }
// Computed property for PDF display
public string FormattedTotal => TotalAmount.ToString("C");
}
public class InvoiceLineItem
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public decimal LineTotal => Quantity * UnitPrice;
}
public class CustomerInfo
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
}
Public Class InvoiceViewModel Public Property InvoiceNumberAsString Public Property InvoiceDateAsDateTime Public Property TotalAmountAsDecimal Public Property LineItemsAsList(OfInvoiceLineItem) Public Property CustomerAsCustomerInfo ' Computed property for PDF display PublicReadOnlyPropertyFormattedTotalAsString Get ReturnTotalAmount.ToString("C")End Get End PropertyEnd ClassPublic Class InvoiceLineItem Public Property DescriptionAsString Public Property QuantityAsInteger Public Property UnitPriceAsDecimal PublicReadOnlyPropertyLineTotalAsDecimal Get ReturnQuantity * UnitPriceEnd Get End PropertyEnd ClassPublic Class CustomerInfo Public Property NameAsString Public Property EmailAsString Public Property AddressAsStringEnd Class
Public Class InvoiceViewModel
Public Property InvoiceNumber As String
Public Property InvoiceDate As DateTime
Public Property TotalAmount As Decimal
Public Property LineItems As List(Of InvoiceLineItem)
Public Property Customer As CustomerInfo
' Computed property for PDF display
Public ReadOnly Property FormattedTotal As String
Get
Return TotalAmount.ToString("C")
End Get
End Property
End Class
Public Class InvoiceLineItem
Public Property Description As String
Public Property Quantity As Integer
Public Property UnitPrice As Decimal
Public ReadOnly Property LineTotal As Decimal
Get
Return Quantity * UnitPrice
End Get
End Property
End Class
Public Class CustomerInfo
Public Property Name As String
Public Property Email As String
Public Property Address As String
End Class
请注意: 可以使用以下代码在浏览器中查看PDF文档:File(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; publicHomeController(ILogger<HomeController> logger, IRazorViewRenderer viewRenderService, IHttpContextAccessor httpContextAccessor) { _logger = logger; _viewRenderService = viewRenderService; _httpContextAccessor = httpContextAccessor; } public IActionResultIndex() { returnView(); } public async Task<IActionResult> Persons() { // Example list of 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" } }; // Check if the request method is POST if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method) { // Create a new PDF renderer ChromePdfRenderer renderer = new ChromePdfRenderer(); // Configure rendering options for better output renderer.RenderingOptions.MarginTop = 40; renderer.RenderingOptions.MarginBottom = 40; renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait; renderer.RenderingOptions.Title = "Persons Report"; // Render View to PDF document PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);Response.Headers.Add("Content-Disposition", "inline"); // Output PDF document returnFile(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf"); } returnView(persons); } public IActionResultPrivacy() { returnView(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResultError() { returnView(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()
{
// Example list of 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" }
};
// Check if the request method is POST
if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
{
// Create a new PDF renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginBottom = 40;
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait;
renderer.RenderingOptions.Title = "Persons Report";
// 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 });
}
}
}
ImportsIronPdf.Extensions.Mvc.CoreImportsMicrosoft.AspNetCore.MvcImportsSystem.DiagnosticsImportsViewToPdfMVCCoreSample.ModelsNamespaceViewToPdfMVCCoreSample.Controllers Public Class HomeControllerInheritsController PrivateReadOnly _logger AsILogger(OfHomeController) PrivateReadOnly _viewRenderService AsIRazorViewRenderer PrivateReadOnly _httpContextAccessor AsIHttpContextAccessor Public Sub New(logger AsILogger(OfHomeController), viewRenderService AsIRazorViewRenderer, httpContextAccessor AsIHttpContextAccessor) _logger = logger _viewRenderService = viewRenderService _httpContextAccessor = httpContextAccessor End Sub Public Function Index() AsIActionResult ReturnView() End Function PublicAsync Function Persons() AsTask(OfIActionResult) ' Example list of persons Dim persons = New List(OfPerson) From { New PersonWith {.Name = "Alice", .Title = "Mrs.", .Description = "Software Engineer"}, New PersonWith {.Name = "Bob", .Title = "Mr.", .Description = "Software Engineer"}, New PersonWith {.Name = "Charlie", .Title = "Mr.", .Description = "Software Engineer"} } ' Check if the request method is POST If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.MethodThen ' Create a new PDF renderer Dim renderer As New ChromePdfRenderer() ' Configure rendering options for better output renderer.RenderingOptions.MarginTop = 40 renderer.RenderingOptions.MarginBottom = 40 renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait renderer.RenderingOptions.Title = "Persons Report" ' Render View to PDF document Dim pdf AsPdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons) Response.Headers.Add("Content-Disposition", "inline") ' Output PDF document ReturnFile(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf") End If ReturnView(persons) End Function Public Function Privacy() AsIActionResult ReturnView() End Function <ResponseCache(Duration:=0, Location:=ResponseCacheLocation.None, NoStore:=True)> Public Function Error() AsIActionResult ReturnView(New ErrorViewModelWith {.RequestId = If(Activity.Current?.Id, HttpContext.TraceIdentifier)}) End Function End ClassEndNamespace
Imports IronPdf.Extensions.Mvc.Core
Imports Microsoft.AspNetCore.Mvc
Imports System.Diagnostics
Imports ViewToPdfMVCCoreSample.Models
Namespace ViewToPdfMVCCoreSample.Controllers
Public Class HomeController
Inherits Controller
Private ReadOnly _logger As ILogger(Of HomeController)
Private ReadOnly _viewRenderService As IRazorViewRenderer
Private ReadOnly _httpContextAccessor As IHttpContextAccessor
Public Sub New(logger As ILogger(Of HomeController), viewRenderService As IRazorViewRenderer, httpContextAccessor As IHttpContextAccessor)
_logger = logger
_viewRenderService = viewRenderService
_httpContextAccessor = httpContextAccessor
End Sub
Public Function Index() As IActionResult
Return View()
End Function
Public Async Function Persons() As Task(Of IActionResult)
' Example list of persons
Dim persons = 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"}
}
' Check if the request method is POST
If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.Method Then
' Create a new PDF renderer
Dim renderer As New ChromePdfRenderer()
' Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 40
renderer.RenderingOptions.MarginBottom = 40
renderer.RenderingOptions.PaperOrientation = IronPdf.Rendering.PdfPaperOrientation.Portrait
renderer.RenderingOptions.Title = "Persons Report"
' Render View to PDF document
Dim pdf As PdfDocument = 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")
End If
Return View(persons)
End Function
Public Function Privacy() As IActionResult
Return View()
End Function
<ResponseCache(Duration:=0, Location:=ResponseCacheLocation.None, NoStore:=True)>
Public Function Error() As IActionResult
Return View(New ErrorViewModel With {.RequestId = If(Activity.Current?.Id, HttpContext.TraceIdentifier)})
End Function
End Class
End Namespace
使用PdfDocument对象。 您可以将 PDF 转换为 PDF/A 或 PDF/UA 格式,在生成的 PDF 上添加数字签名,或根据需要合并和拆分 PDF 文档。 此外,该库允许您旋转页面,插入注释或书签,并在您的 PDF 文件上加盖独特的水印。
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 herebuilder.Services.AddSingleton<IRazorViewRenderer, RazorViewRenderer>();// Optional: Configure IronPDF license if you have oneIronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";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>();
// Optional: Configure IronPDF license if you have one
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
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();
ImportsIronPdf.Extensions.Mvc.CoreImportsMicrosoft.AspNetCore.Mvc.ViewFeaturesDim builder = WebApplication.CreateBuilder(args)' Add services to the container.builder.Services.AddControllersWithViews()builder.Services.AddSingleton(OfIHttpContextAccessor, HttpContextAccessor)()builder.Services.AddSingleton(OfITempDataProvider, CookieTempDataProvider)()' Register IRazorViewRenderer herebuilder.Services.AddSingleton(OfIRazorViewRenderer, RazorViewRenderer)()' Optional: Configure IronPDF license if you have oneIronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE"Dim app = builder.Build()' Configure the HTTP request pipeline.IfNot app.Environment.IsDevelopment() Then 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()End Ifapp.UseHttpsRedirection()app.UseStaticFiles()app.UseRouting()app.UseAuthorization()app.MapControllerRoute( name:="default", pattern:="{controller=Home}/{action=Index}/{id?}")app.Run()
Imports IronPdf.Extensions.Mvc.Core
Imports Microsoft.AspNetCore.Mvc.ViewFeatures
Dim builder = WebApplication.CreateBuilder(args)
' Add services to the container.
builder.Services.AddControllersWithViews()
builder.Services.AddSingleton(Of IHttpContextAccessor, HttpContextAccessor)()
builder.Services.AddSingleton(Of ITempDataProvider, CookieTempDataProvider)()
' Register IRazorViewRenderer here
builder.Services.AddSingleton(Of IRazorViewRenderer, RazorViewRenderer)()
' Optional: Configure IronPDF license if you have one
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY-HERE"
Dim app = builder.Build()
' Configure the HTTP request pipeline.
If Not app.Environment.IsDevelopment() Then
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()
End If
app.UseHttpsRedirection()
app.UseStaticFiles()
app.UseRouting()
app.UseAuthorization()
app.MapControllerRoute(
name:="default",
pattern:="{controller=Home}/{action=Index}/{id?}")
app.Run()
Is it possible to use minimal APIs for PDF generation with IronPDF?
While minimal APIs don't have built-in view support, you can still use IronPDF's HTML to PDF conversion features. For view-based PDF generation, use the traditional MVC approach or consider Razor Pages.
Which project type is recommended for IronPDF's view rendering features?
The ASP.NET Core Web App (Model-View-Controller) template is recommended for optimal compatibility with IronPDF's view rendering features.
How do I handle common installation issues with IronPDF?
Common issues include version mismatches between core and extension packages or missing dependencies. Ensure your project targets a supported .NET version and review the installation overview for troubleshooting steps.
What troubleshooting steps should I take for project setup issues?
For setup issues, ensure all NuGet packages are restored and your .NET SDK version matches project requirements. For rendering issues, consult IronPDF's troubleshooting guide.
What is the `IRazorViewRenderer` service used for in IronPDF?
The `IRazorViewRenderer` service, provided by the `IronPdf.Extensions.Mvc.Core` package, handles the conversion of Razor views to HTML. It integrates with ASP.NET Core's view engine, executing Razor syntax to produce the final HTML that IronPDF converts to PDF.