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 (モデル-ビュー-コントローラ) は、ASP.NET Core を使用してウェブアプリケーションを構築するために Microsoft によって提供されるウェブアプリケーションです。

IronPDF拡張パッケージ

IronPdf.Extensions.Mvc.Core パッケージは、メインのIronPDFパッケージの拡張です。 ASP.NET Core MVCでビューをPDFドキュメントにレンダリングするためには、IronPdf.Extensions.Mvc.CoreパッケージとIronPdfパッケージの両方が必要です。

Install-Package IronPdf.Extensions.Mvc.Core

申し訳ありませんが、翻訳するコンテンツのテキストを提供してください。その後、英語から日本語に翻訳いたします。!-- NUGET ライブラリ ダウンロード ディレクティブ タグ :: スタート -->

PDF用C# NuGetライブラリ

でインストール NuGet

Install-Package IronPdf.Extensions.Mvc.Core

申し訳ありませんが、翻訳するコンテンツのテキストを提供してください。その後、英語から日本語に翻訳いたします。!-- NUGETライブラリダウンロード指示タグ :: 終了 -->

ビューをPDFにレンダリング

ASP.NET Coreウェブアプリが必要です。 (モデル-ビュー-コントローラ) ビューをPDFファイルに変換するプロジェクト。

クラスのモデルを追加

  • 「Models」フォルダーに移動する
  • 新しいC#クラスファイルを「Person」と名付けて作成します。このクラスは、個々のデータを表すモデルとして機能します。 以下のコードスニペットを使用してください:
: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 });
        }
    }
}
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(ByVal logger As ILogger(Of HomeController), ByVal viewRenderService As IRazorViewRenderer, ByVal 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)

'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 _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.Method Then

				Dim renderer As New ChromePdfRenderer()

				' Render View to PDF document
				Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons_Conflict)

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

				' Output PDF document
				Return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf")
			End If
			Return View(persons_Conflict)
		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
VB   C#

RenderRazorToPdfメソッドを使用した後、さらなる強化および修正が可能なPdfDocumentオブジェクトを受け取ります。 PDFを変換する柔軟性があります。 PDFA はい、以下の内容を日本語に翻訳いたします:

以下の内容を日本語に翻訳してください:

IronPDF allows developers to generate, edit and read PDF files in .NET applications. It simplifies the process of integrating PDF functionalities into software development projects.

Let's get started! PDFUA フォーマットを追加し、 デジタル署名 生成されたPDFに、 マージおよび分割 必要に応じてPDFドキュメントを作成します。 さらに、このライブラリを使用すると、ページを回転させたり、挿入したりすることができます。 注釈 はい、以下の内容を日本語に翻訳いたします:

以下の内容を日本語に翻訳してください:

IronPDF allows developers to generate, edit and read PDF files in .NET applications. It simplifies the process of integrating PDF functionalities into software development projects.

Let's get started! ブックマーク、および ユニークなウォーターマークを印刷する PDFファイルに直接埋め込む。

ビューを追加

  • 新しく追加されたPersonアクションを右クリックして、「ビューの追加」を選択します。

    「Personsアクションを右クリック」

  • 新しいスキャフォールド項目には「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();
Imports IronPdf.Extensions.Mvc.Core
Imports Microsoft.AspNetCore.Mvc.ViewFeatures

Private 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)()

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()
VB   C#

プロジェクトを実行

これにより、プロジェクトを実行してPDFドキュメントを生成する方法を示します。

ASP.NET Core MVC プロジェクトを実行する

申し訳ありませんが、翻訳するコンテンツのテキストを提供してください。その後、英語から日本語に翻訳いたします。!-- #### 出力 PDF

--> ## ASP.NET Core MVC プロジェクトをダウンロード このガイドの完全なコードは、ダウンロードすることができます。Visual StudioでASP.NET Core Webアプリとして開けるzipファイルとして提供されています。 (モデル-ビュー-コントローラ) プロジェクト [プロジェクトをダウンロードするにはこちらをクリックしてください。](/static-assets/pdf/how-to/cshtml-to-pdf-mvc-core/ViewToPdfMVCCoreSample.zip)

チャクニット・ビン

ソフトウェアエンジニア

チャクニットは開発者のシャーロック・ホームズです。彼がソフトウェアエンジニアリングの将来性に気付いたのは、楽しみでコーディングチャレンジをしていたときでした。彼のフォーカスはIronXLとIronBarcodeにありますが、すべての製品でお客様を助けることに誇りを持っています。チャクニットは顧客と直接話すことで得た知識を活用して、製品自体のさらなる改善に貢献しています。彼の逸話的なフィードバックは、単なるJiraチケットを超えて、製品開発、ドキュメントおよびマーケティングをサポートし、顧客の全体的な体験を向上させます。オフィスにいないときは、機械学習やコーディングについて学んだり、ハイキングを楽しんだりしています。