ASP.NET Core MVCでビューをPDFに変換する方法|IronPDF

.NETコアMVCでビューをPDFに変換する方法

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPDF の RenderRazorViewToPdf メソッドを使用して、ASP.NET Core MVC のビューを PDF に変換します。この方法では、.cshtml ファイルを MVC アプリケーションで 1 行のコードで高品質な PDF ドキュメントに変換します。

ビューは、ウェブアプリケーションでHTMLマークアップを生成するために使用されるASP.NETフレームワークのコンポーネントです。 これは、ASP.NET MVCおよびASP.NET Core MVCアプリケーションで一般的に使用されているModel-View-Controller(MVC)パターンの一部です。 ビューは、HTMLコンテンツを動的にレンダリングすることで、ユーザーにデータを表示する役割を担っています。 ビューは通常、サーバーベースのコードをウェブページに埋め込むためのマークアップ構文である Razor 構文を使用しており、データ駆動型の PDF 文書を作成するための強力なツールとなっています。

クイックスタート: ASP.NET Coreで CSHTML を PDF に変換する

IronPDF を使用して ASP.NET Core MVC ビューを PDF に変換します。 1 行のコードで .cshtml ファイルを PDF ドキュメントにレンダリングします。 ダイナミックなHTMLビューからシームレスにPDFを生成するために、この機能をMVCアプリケーションに直接統合してください。 このガイドに従って環境をセットアップし、変換を開始してください。

  1. IronPDF をNuGetパッケージマネージャでインストール

    PM > Install-Package IronPdf
  2. このコード スニペットをコピーして実行します。

    // using IronPdf.Extensions.Mvc.Core
    new IronPdf.ChromePdfRenderer().RenderRazorViewToPdf(HttpContext, "Views/Home/Report.cshtml", model).SaveAs("report.pdf");
  3. 実際の環境でテストするためにデプロイする

    今日プロジェクトで IronPDF を使い始めましょう無料トライアル

    arrow pointer

ASP.NET Core Web App MVC(Model-View-Controller)は、ASP.NET Coreを使用してWebアプリケーションを構築するためにMicrosoftが提供するWebアプリケーションフレームワークです。

  • Model: データとビジネスロジックを表し、データのやり取りを管理し、データソースと通信します。
  • View: ユーザーインターフェイスを提示し、データを表示し、ユーザーに情報をレンダリングします。
  • Controller: ユーザー入力を処理し、リクエストに応答し、Model との通信を行い、モデル-ビューの相互作用を調整します。

IronPDFはASP.NET Core MVCプロジェクト内のビューから直接PDFファイルを作成することができます。 CSSスタイリングJavaScript実行カスタムフォントなどの最新の機能をサポートし、ASP.NET Core MVCでPDFを簡単に生成できるようにします。

IronPDF拡張機能にはどのようなパッケージが必要ですか?

IronPdf.Extensions.Mvc.Core パッケージは、メインの IronPdf パッケージの拡張です。 ASP.NET Core MVC でビューを PDF ドキュメントにレンダリングするには、IronPdf.Extensions.Mvc.CoreIronPdf の両方のパッケージが必要です。 拡張パッケージは、ASP.NET Coreの依存性注入システムとRazorビューレンダリングパイプラインと統合するための特定の機能を提供します。

インストール-パッケージ IronPdf.Extensions.Mvc.Core

なぜIronPDFと拡張パッケージの両方が必要なのですか?

メインの IronPDF パッケージにはコアの PDF レンダリングエンジンと基礎的な機能が含まれ、Extensions.Mvc.Core パッケージは ASP.NET Core MVC のビュー レンダリング システムとの専門的な統合を提供します。 このように分けることで、モジュール性を高め、プロジェクトのタイプに必要な特定の機能のみを含めることができます。 この拡張パッケージには、PDF 生成前に Razor ビューを HTML に変換するために必要な IRazorViewRenderer インターフェイスと実装が含まれています。

どのNuGetパッケージのバージョンを使用すべきですか?

互換性を確保するために、常に IronPdfIronPdf.Extensions.Mvc.Core のバージョンを一致させてください。 最新の安定リリースとバージョンの互換性情報については、NuGetパッケージのドキュメントを確認してください。 アップデートの際には、適切な機能を維持するために、両方のパッケージが一緒にアップデートされるようにしてください。

よくあるインストール時の問題とは

よくあるインストールの問題には、コアパッケージと拡張パッケージのバージョンの不一致、依存関係の欠落、プラットフォーム固有の要件などがあります。 問題が発生した場合は、プロジェクトがサポートされている.NETバージョンをターゲットにしていることを確認し、トラブルシューティングの手順については、インストールの概要を確認してください。

PDF用C# NuGetライブラリ

NuGetでインストール

インストール-パッケージ IronPdf.Extensions.Mvc.Core

ビューを PDF にレンダリングするには?

View を PDF ファイルに変換するには、ASP.NET Core Web App (Model-View-Controller) プロジェクトが必要です。 このプロセスには、IronPDF の RenderRazorViewToPdf メソッドを使用して Razor ビューを PDF ドキュメントに変換するコントローラーアクションを作成することが含まれます。 このアプローチでは、Razorの構文をフルに活用し、動的コンテンツを含む複雑なデータ駆動型PDFを作成することができます。

どのプロジェクトタイプを使うべきですか?

IronPDF のビューレンダリング機能との最適な互換性のために、ASP.NET Core Web App (Model-View-Controller) テンプレートを使用してください。 このプロジェクトタイプは、Razorビューエンジンや適切なルーティングなど、ビューレンダリングに必要なインフラストラクチャを提供します。 既存のプロジェクトについては、MVCパターンに従い、必要なビューレンダリング機能がインストールされていることを確認してください。

最小限の API で使用できますか?

Minimal APIはビルトインのビューサポートを持っていませんが、IronPDFのHTMLからPDFへの変換機能を使用することができます。 ビューベースのPDF生成には、従来のMVCアプローチを使用するか、代替案としてRazor Pagesを検討してください。

モデルクラスを追加するにはどうすればよいですか?

  • "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
$vbLabelText   $csharpLabel

なぜPDF生成のためのモデルが必要なのでしょうか

モデルは、レンダリングのためにビューに渡すことができる構造化データを提供します。 このように関係性を分離することで、PDF生成ロジックがクリーンで保守可能な状態に保たれます。 モデルはコントローラとビューの間の契約として機能し、型の安全性を確保し、Razorビューでインテリセンスをサポートします。

どのようなデータ型がビューに最適ですか?

シンプルなデータ型とコレクションは、PDF生成に最適です。 複雑なネストされたオブジェクトを使用することができますが、追加のビューロジックが必要になる場合があります。 パフォーマンスを最適化するには、複雑なデータ構造をビューに渡す前に、コントローラ内で平坦化します。 ドメインモデルが複雑すぎる場合は、PDF出力専用に設計されたViewModelsの使用を検討してください。

以下は、PDF生成に適した、より複雑なモデル構造の例です:

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 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 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
$vbLabelText   $csharpLabel

コントローラーを編集するには?

"Controllers" フォルダーに移動し、HomeController.cs ファイルを開きます。HomeController にのみ変更を加え、Persons アクションを追加します。 以下のコードを参考にしてください:

以下のコードは、最初に 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;

        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 });
        }
    }
}
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 });
        }
    }
}
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
$vbLabelText   $csharpLabel

RenderRazorViewToPdf メソッドを使用した後、さらに拡張や修正ができる PdfDocument オブジェクトを受け取ります。 必要に応じて、PDFをPDF/AまたはPDF/UA形式に変換したり、生成されたPDFに電子署名を追加したり、PDF文書を結合したり分割したりすることができます。 さらに、このライブラリを使用すると、PDFファイルへのページ回転、注釈またはブックマークの挿入、ユニークなウォーターマークの印刷が可能です。

IRazorViewRenderer サービスとは何ですか?

IRazorViewRendererIronPdf.Extensions.Mvc.Core パッケージが提供するサービスインターフェースで、Razor ビューの HTML への変換を処理します。 それは ASP.NET Core のビューエンジンと統合して、関連するモデルと共に .cshtml ファイルを処理し、すべての Razor 構文を実行して、IronPDF が PDF に変換する最終的な HTML を生成します。

なぜレンダリング前に POST メソッドをチェックするのですか

POSTチェックにより、フォーム送信により明示的に要求された場合にのみPDF生成が行われるようにします。 これは、ページロード時に誤ってPDFが生成されるのを防ぎ、同じアクションでHTMLビュー(GET時)とPDFダウンロード(POST時)の両方を提供することを可能にします。 このパターンはRESTfulの原則に従い、より良いユーザーエクスペリエンスを提供します。

PDF出力をカスタマイズするにはどうすればよいですか?

IronPDF は RenderingOptions プロパティを通じて広範なカスタマイズオプションを提供します。 以下は、より高度な設定の例です:

:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-mvc-core-6.cs
// Advanced rendering configuration example
var renderer = new ChromePdfRenderer();

// Page setup
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;

// Headers and footers with merge fields
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    Height = 25,
    HtmlFragment = "<div style='text-align: center; font-size: 12px;'>Page {page} of {total-pages}</div>"
};

// JavaScript execution delay for dynamic content
renderer.RenderingOptions.WaitFor.RenderDelay(500); // Wait 500ms for JS execution
renderer.RenderingOptions.WaitFor.NetworkIdle0(); // Wait for network requests

// Apply watermark
renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
{
    DrawDividerLine = true,
    CenterText = "CONFIDENTIAL",
    Font = IronSoftware.Drawing.FontTypes.Arial,
    FontSize = 16
};
Imports IronPdf
Imports IronSoftware.Drawing

' Advanced rendering configuration example
Dim renderer = New ChromePdfRenderer()

' Page setup
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20

' Headers and footers with merge fields
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
    .Height = 25,
    .HtmlFragment = "<div style='text-align: center; font-size: 12px;'>Page {page} of {total-pages}</div>"
}

' JavaScript execution delay for dynamic content
renderer.RenderingOptions.WaitFor.RenderDelay(500) ' Wait 500ms for JS execution
renderer.RenderingOptions.WaitFor.NetworkIdle0() ' Wait for network requests

' Apply watermark
renderer.RenderingOptions.TextHeader = New TextHeaderFooter() With {
    .DrawDividerLine = True,
    .CenterText = "CONFIDENTIAL",
    .Font = FontTypes.Arial,
    .FontSize = 16
}
$vbLabelText   $csharpLabel

よくあるコントローラーのエラーとは

よくあるエラーには、サービスが適切に注入されていない場合のヌル参照例外、ビューの場所を指定する際のパスの問題、モデルのバインディングの問題などがあります。 すべての必要なサービスが Program.cs に登録されていることを確認し、ビューの位置を指定する際はプロジェクトのルートからの相対パスを使用してください。 トラブルシューティングのために、開発モードで詳細なエラーメッセージを有効にします。

Icon Quote related to よくあるコントローラーのエラーとは

私のお気に入りのこの種のライブラリはIronPDFです。PDFファイルの迅速で効率的な操作が可能です。また、PDF/A形式へのエクスポートやPDF文書へのデジタル署名といった多くの貴重な機能も備えています。

Milan Jovanovic related to よくあるコントローラーのエラーとは

Milan Jovanovic

Microsoft MVP

ケーススタディを見る
Icon Quote related to よくあるコントローラーのエラーとは

IronOCRのおかげで私たちは年間$40,000を手作業の処理から節約し、生産性を向上させ、高影響のタスクにリソースを充てることができます。非常にお勧めします。

Brent Matzelle related to よくあるコントローラーのエラーとは

Brent Matzelle

最高技術責任者, OPYN

ケーススタディを見る
Icon Quote related to よくあるコントローラーのエラーとは

IronSuiteは私たちの業務において重要な役割を果たしています。これらは、フロアプランの作成や在庫管理の改善を含め、ビジネス全体の効率を向上させるツールです。

David Jones related to よくあるコントローラーのエラーとは

David Jones

リードソフトウェアエンジニア、Agorus Build

ケーススタディを見る

どのようにビューを追加しますか?

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

Visual Studio のコンテキストメニューが表示され、

  • 新しいスキャフォールドアイテムには"Razor View"を選んでください。

Visual Studio の Razor ビューの追加ダイアログが表示され、

  • "List"テンプレートと Person モデルクラスを選択します。

Visual Studio の Razor ビューの追加ダイアログが表示され、

これにより、Persons という名前の .cshtml ファイルが作成されます。

  • "Views"フォルダー -> "Home"フォルダー -> Persons.cshtml ファイルに移動します。

IronPdf.Extensions.Mvc.Core

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

PDF生成にFormMethod.Postを使用する理由は何ですか?

PDF生成にFormMethod.Postを使用することは、ブラウザのリフレッシュやブックマークされたURLによる不要なPDF生成を防ぎ、アクションを明確にすることで、ウェブのベストプラクティスに従います。 POST リクエストは冪等性を持つべきであり(サーバーの状態を変更しない)、POST リクエストは結果を生むアクションを示します - この場合、PDFドキュメントの生成です。

どのように PDF 印刷ボタンをスタイルできますか?

CSSクラスを使用して印刷ボタンをスタイル設定し、より良いユーザーエクスペリエンスのためにJavaScriptで強化してください。 こちらは強化版です:

@using (Html.BeginForm("Persons", "Home", FormMethod.Post, new { @class = "pdf-form" }))
{
    <button type="submit" class="btn btn-primary pdf-download-btn">
        <i class="fas fa-file-pdf"></i> Download as PDF
    </button>
}

<style>
    .pdf-download-btn {
        background-color: #dc3545;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }

    .pdf-download-btn:hover {
        background-color: #c82333;
    }

    .pdf-download-btn:active {
        transform: translateY(1px);
    }
</style>

<script>
    // Optional: Show loading indicator during PDF generation
    document.querySelector('.pdf-form').addEventListener('submit', function() {
        const button = this.querySelector('button');
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
        button.disabled = true;
    });
</script>
@using (Html.BeginForm("Persons", "Home", FormMethod.Post, new { @class = "pdf-form" }))
{
    <button type="submit" class="btn btn-primary pdf-download-btn">
        <i class="fas fa-file-pdf"></i> Download as PDF
    </button>
}

<style>
    .pdf-download-btn {
        background-color: #dc3545;
        color: white;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s ease;
    }

    .pdf-download-btn:hover {
        background-color: #c82333;
    }

    .pdf-download-btn:active {
        transform: translateY(1px);
    }
</style>

<script>
    // Optional: Show loading indicator during PDF generation
    document.querySelector('.pdf-form').addEventListener('submit', function() {
        const button = this.querySelector('button');
        button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
        button.disabled = true;
    });
</script>
HTML

PDFに最適なビューテンプレートは?

ListDetails テンプレートは特に構造化されたレイアウトを提供するため、PDF 生成に適しています。 PDF出力用に特別に設計されたカスタムテンプレートは、多くの場合、最良の結果をもたらします。 画面表示ではなく印刷レイアウトに最適化し、ナビゲーション要素を削除してコンテンツの表示に焦点を当てた専用のPDFビューを作成することを検討してください。

トップナビゲーションバーにセクションを追加するにはどうすればよいですか?

  • 同じ"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

なぜasp-actionは正確に一致する必要があるのですか?

asp-action 属性は ASP.NET Core のタグヘルパーを使用して、ルーティング構成に基づいて正しい URL を生成します。 完全一致は、リンクが正しいコントローラアクションに解決することを保証します。 不一致は、404エラーや意図しないアクションへのルーティングにつながります。 タグヘルパーは大文字と小文字を区別し、コントローラ内のメソッド名と正確に一致する必要があります。

ナビゲーション リンクが一致しない場合はどうなりますか?

ナビゲーションリンクがコントローラのアクションと一致しない場合、ユーザーは404エラーに遭遇したり、正しくないページに誘導されたりします。 開発中、ASP.NET Coreの開発者例外ページには、詳細なルーティングエラーが表示されます。 本番環境では、ユーザーには一般的なエラーページが表示されます。 ユーザーエクスペリエンスが損なわれないように、ナビゲーションリンクがコントローラのアクション名と正確に一致していることを常に確認してください。

Program.csファイルを編集するには?

依存性注入 (DI) コンテナに IHttpContextAccessorIRazorViewRenderer インターフェイスを登録します。 以下のコードを参考にしてください。

:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-mvc-core-10.cs
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();
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()
$vbLabelText   $csharpLabel

なぜサービスをシングルトンとして登録するのですか?

シングルトンサービスは一度作成され、アプリケーションのライフタイム中に再利用されるため、IRazorViewRenderer のようなステートレスサービスに効率的です。 このパターンでは、ビューのレンダリングサービスがリクエスト固有の状態を保持しないため、メモリのオーバーヘッドが削減され、パフォーマンスが向上します。 IHttpContextAccessor はシングルトンでなければならず、異なるサービスライフタイム間でアクセスできるようにします。

ITempDataProviderは何に使用されますか?

ITempDataProvider は、リダイレクト後のメッセージ表示によく使われる、リクエスト間の一時的なデータストレージを可能にします。 PDF生成の文脈では、ビューをPDFにレンダリングするときに、ビューの状態が適切に維持されるようにします。 CookieTempDataProvider はこの一時データを暗号化されたクッキーに保存し、状態管理のための安全なメカニズムを提供します。

スコープ付きサービスを代わりに使用できますか?

一部のシナリオではスコープされたサービスを使用することもできますが、IRazorViewRenderer は要求特有の状態を持たないため、シングルトンとして最もよく機能します。 スコープされたサービスを使用すると、リクエストごとに新しいインスタンスが作成され、メモリ使用量が増加します。 ただし、スコープされたサービスをビューに注入する必要がある場合は、実行時エラーを避けるために、適切なサービス寿命管理を確実に行ってください。

プロジェクトを実行する

プロジェクトを実行し、PDFドキュメントを生成する方法を示します。 アプリケーションを実行するときは、トップナビゲーションメニューを使用して Persons ページに移動し、Print Person ボタンをクリックして PDF を生成およびダウンロードしてください。

ASP.NET Core MVC のコントローラーコードと IntelliSense の補助を含む HomeController.cs を表示する Visual Studio

ASP.NETコアMVCプロジェクトはどこでダウンロードできますか?

このガイドの完全なコードをダウンロードしてください。これは、ASP.NET Core Web App(Model-View-Controller)プロジェクトとしてVisual Studioで開くことができるzipファイルとして提供されます。

ASP.NET Core MVCサンプルプロジェクトをダウンロード

サンプルプロジェクトには何が含まれていますか?

サンプルプロジェクトには、.NET Core MVCアプリケーションとIronPDF統合が完全に構成され、ビューからPDFへの変換が実演されています。 Person モデル、PDF 生成ロジックを含む HomeController、適切な Razor 構文を持つ Persons ビュー、および Program.cs におけるすべての必要なサービス登録が含まれます。 このプロジェクトには、PDF出力に最適化されたスタイリングとレイアウトの構成例も含まれています。

どの Visual Studio のバージョンを使用すればよいですか?

.NET 6以上のプロジェクトで最高の体験を得るには、Visual Studio 2022(バージョン17.0以降)を推奨します。 C#拡張機能を持つVisual Studio Codeは、クロスプラットフォーム開発にも適しています。 ASP.NETとWeb開発ワークロードがインストールされていることを確認してください。 プロジェクトは、デフォルトで.NET 6.0を対象としていますが、新しいバージョンに更新することも可能です。

プロジェクトのセットアップに関する問題のトラブルシューティングはどうすればよいですか?

よくあるセットアップの問題には、NuGetパッケージの欠落、.NET SDKバージョンの誤り、設定の問題などがあります。 最初に dotnet restore または Visual Studio のパッケージマネージャーを使用して NuGet パッケージを復元します。 dotnet --version を使用して .NET SDK バージョンがプロジェクト要件に一致していることを確認します。 ライセンスの問題については、ライセンスキーのドキュメントを参照してください。 レンダリングの問題が発生した場合は、トラブルシューティングガイドで解決策を確認してください。

次に何ができるのかを見てみましょうか? 私たちのチュートリアルページをご覧ください: PDFの変換

よくある質問

ASP.NET Core MVCでCSHTMLビューをPDFに変換する最も簡単な方法は何ですか?

最も簡単な方法はIronPDFのRenderRazorViewToPdfメソッドを使うことで、.cshtmlファイルをたった一行のコードでPDFドキュメントに変換することができます。次のように呼び出すだけです: new IronPdf.ChromePdfRenderer().RenderRazorViewToPdf(HttpContext, "Views/Home/Report.cshtml", model).SaveAs("report.pdf");

ASP.NET Core MVC でビューを PDF に変換するには、どの NuGet パッケージが必要ですか?

2つのパッケージが必要です:IronPDF(メインパッケージ)とIronPdf.Extensions.Mvc.Core(拡張パッケージ)です。拡張パッケージはASP.NET Coreの依存性注入システムとRazorビューレンダリングパイプラインと統合するための特定の機能を提供します。

CSHTMLをPDFに変換する際、CSSスタイリングやJavaScriptを適用できますか?

はい、IronPDFはビューをPDFにレンダリングする際、CSSスタイリング、JavaScriptの実行、カスタムフォントを完全にサポートします。これにより、レスポンシブCSSやダイナミックJavaScriptコンテンツなど、PDFがWebビューと同じ外観と機能を維持できるようになります。

私のASP.NET Core MVCプロジェクトでViewからPDFへの変換を実装する主な手順は何ですか?

ワークフローには5つのステップがあります:1) IronPDFとそのMVC Coreエクステンションをダウンロードする、2) データのモデルクラスを追加する、3) RenderRazorViewToPdfメソッドを使用するようにコントローラーを編集する、4) PDFレンダリングのためにビュー(.cshtmlファイル)を作成または修正する、5) PDFを生成するためにアプリケーションを実行する。

MVC パターンは、Views からの PDF 生成でどのように機能しますか?

ASP.NET Core MVCでは、モデルはデータとビジネスロジックを含み、ビュー(.cshtmlファイル)はUIを表示しデータを表示し、コントローラーはリクエストを処理し、ビューからのPDF生成をオーケストレーションするためにIronPDFのRenderRazorViewToPdfメソッドを使用します。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

レビュー済み
Jeff Fritz
Jeffrey T. Fritz
プリンシパルプログラムマネージャー - .NETコミュニティチーム
Jeffはまた、.NETとVisual Studioチームのプリンシパルプログラムマネージャーです。彼は.NET Conf仮想会議シリーズのエグゼクティブプロデューサーであり、週に二回放送される開発者向けライブストリーム『Fritz and Friends』のホストを務め、テクノロジーについて話すことや視聴者と一緒にコードを書くことをしています。Jeffはワークショップ、プレゼンテーション、およびMicrosoft Build、Microsoft Ignite、.NET Conf、Microsoft MVPサミットを含む最大のMicrosoft開発者イベントのコンテンツを企画しています。
準備はできましたか?
Nuget ダウンロード 20,296,129 | バージョン: 2026.7 リリースされたばかり
Still Scrolling Icon

まだスクロールしていますか?

すぐに証拠が欲しいですか? PM > Install-Package IronPdf
サンプルを実行するHTML が PDF に変換されるのを確認します。