IronPDF を使用して ASP.NET Core MVC ビューを PDF に変換します。 1 行のコードで .cshtml ファイルを PDF ドキュメントにレンダリングします。 ダイナミックなHTMLビューからシームレスにPDFを生成するために、この機能をMVCアプリケーションに直接統合してください。 このガイドに従って環境をセットアップし、変換を開始してください。
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");
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
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
以下のコードは、最初に ChromePdfRenderer クラスをインスタンス化し、Views/Home/Persons.cshtml へのパス、および RenderRazorViewToPdf メソッドに必要なデータを含む List を渡します。 ユーザーはカスタムテキストを追加したり、PDF に HTML ヘッダーとフッターを含めたり、カスタムマージンを定義したり、ページ番号を適用したりする機能を RenderingOptions を使用して利用できます。 より高度なレンダリングオプションについては、レンダリングオプションのドキュメントを参照してください。
ご注意: 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
IRazorViewRenderer は IronPdf.Extensions.Mvc.Core パッケージが提供するサービスインターフェースで、Razor ビューの HTML への変換を処理します。 それは ASP.NET Core のビューエンジンと統合して、関連するモデルと共に .cshtml ファイルを処理し、すべての Razor 構文を実行して、IronPDF が PDF に変換する最終的な HTML を生成します。
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()
.NET 6以上のプロジェクトで最高の体験を得るには、Visual Studio 2022(バージョン17.0以降)を推奨します。 C#拡張機能を持つVisual Studio Codeは、クロスプラットフォーム開発にも適しています。 ASP.NETとWeb開発ワークロードがインストールされていることを確認してください。 プロジェクトは、デフォルトで.NET 6.0を対象としていますが、新しいバージョンに更新することも可能です。
最も簡単な方法はIronPDFのRenderRazorViewToPdfメソッドを使うことで、.cshtmlファイルをたった一行のコードでPDFドキュメントに変換することができます。次のように呼び出すだけです: new IronPdf.ChromePdfRenderer().RenderRazorViewToPdf(HttpContext, "Views/Home/Report.cshtml", model).SaveAs("report.pdf");
ASP.NET Core MVC でビューを PDF に変換するには、どの NuGet パッケージが必要ですか?
ASP.NET Core MVCでは、モデルはデータとビジネスロジックを含み、ビュー(.cshtmlファイル)はUIを表示しデータを表示し、コントローラーはリクエストを処理し、ビューからのPDF生成をオーケストレーションするためにIronPDFのRenderRazorViewToPdfメソッドを使用します。
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.