ASP.NET Core C#でViewをPDFに変換する方法

How to Convert Views to PDFs in ASP.NET MVC

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

ビューは、ウェブアプリケーションでHTMLマークアップを生成するために使用されるASP.NETフレームワークのコンポーネントです。 これは、ASP.NET MVCおよびASP.NET Core MVCアプリケーションで一般的に使用されるモデルビューコントローラ(MVC)パターンの一部です。 ビューは、動的にHTMLコンテンツをレンダリングすることでユーザーにデータを提示する責任を負います。

ASP.NET Web アプリケーション (.NET Framework) MVC は、Microsoft が提供する Web アプリケーションフレームワークです。 これは、モデル-ビュー-コントローラー (MVC) として知られる構造化されたアーキテクチャ パターンに従い、ウェブアプリケーションの開発を整理して効率化します。

  • モデル: データ、ビジネス ロジック、およびデータ整合性を管理します。
  • ビュー: ユーザーインターフェイスを提示し、情報をレンダリングします。
  • コントローラー: ユーザー入力を処理し、要求を処理し、モデルとビュー間の相互作用を調整します。

IronPDF は、ASP.NET MVC プロジェクト内でビューから PDF ファイルを作成するプロセスを簡素化します。 これにより、ASP.NET MVC での PDF 生成が簡単かつ直接的になります。

見出し:2 (クイックスタート: ASP.NET MVC Viewを簡単にPDFに変換する)

IronPDF を使用して、ASP.NET MVC ビューを PDF ドキュメントにすばやく変換する方法を学びましょう。 数行のコードで CSHTML ビューを高品質なPDFにレンダリングし、アプリケーションの機能を強化できます。 IronPDF はプロセスを簡素化し、すべてのレベルの開発者が利用しやすくしています。 ASP.NET Core プロジェクトに IronPDF を統合し、ビューからPDFを簡単に生成することから始めてください。

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    // Install-Package IronPdf.Extensions.Razor
    var pdf = new IronPdf.ChromePdfRenderer.RenderRazorToPdf(this.ControllerContext);
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer
class="hsg-featured-snippet">

最小のワークフロー (5 ステップ)

  1. ASP.NET MVC でビューを PDF に変換するための C# ライブラリをダウンロード
  2. データ用のモデル クラスを追加
  3. コントローラに「Person」アクションを作成し、RenderView メソッドを使用
  4. MVC 5 ビュー スキャフォールドを使用してビューを追加
  5. クイックスタート用にサンプル プロジェクトをダウンロード

IronPDF拡張パッケージ

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

Install-Package IronPdf.Extensions.Mvc.Framework
class="products-download-section">
data-modal-id="trial-license-after-download">
class="product-image"> C# NuGetライブラリ for PDF
class="product-info">

NuGetでインストール

data-original-title="クリックしてコピー">
class="copy-nuget-row">
Install-Package IronPdf.Extensions.Mvc.Framework
class="copy-button">
class="nuget-link">nuget.org/packages/IronPdf.Extensions.Mvc.Framework/

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

ビューをPDFファイルに変換するには、ASP.NET Web アプリケーション ( .NET Framework) MVC プロジェクトが必要です。

モデルクラスを追加

  • 「Models」フォルダーに移動します
  • "Person" という名前の新しい C# クラス ファイルを作成します。このクラスは、個々のデータを表すためのモデルとして機能します。 次のプレースホルダーを使用してガイダンスを受けてください。
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-mvc-framework-model.cs
namespace ViewToPdfMVCSample.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 ViewToPdfMVCSample.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

コントローラを編集

「Controllers」フォルダーに移動し、「HomeController」ファイルを開きます。「Persons」アクションを追加します。 以下のコードを参照してガイドにしてください:

提供されたコードでは、ChromePdfRenderer クラスが最初に作成されます。 RenderView メソッドを使用するには、HttpContext を提供し、「Persons.cshtml」ファイルへのパスを指定し、必要なデータを含むリストを提供する必要があります。 When rendering the View, users have the option to utilize RenderingOptions to customize margins, add custom text and HTML headers and footers, and apply page numbers to the resulting PDF document.

ご注意The PDF document can be downloaded to the machine using the following code: File(pdf.BinaryData, "application/pdf", "viewToPdfMVC.pdf").

using IronPdf;
using System.Collections.Generic;
using System.Web.Mvc;
using ViewToPdfMVCSample.Models;

namespace ViewToPdfMVCSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // GET: Person
        public ActionResult Persons()
        {
            // Create a list of Person objects
            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 (HttpContext.Request.HttpMethod == "POST")
            {
                // Define the path to the View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                // Instantiate the ChromePdfRenderer
                ChromePdfRenderer renderer = new ChromePdfRenderer();

                // Render the view to a PDF document
                PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);

                // Set headers to view the PDF in-browser
                Response.Headers.Add("Content-Disposition", "inline");

                // Return the generated PDF file
                return File(pdf.BinaryData, "application/pdf");
            }
            return View(persons);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}
using IronPdf;
using System.Collections.Generic;
using System.Web.Mvc;
using ViewToPdfMVCSample.Models;

namespace ViewToPdfMVCSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        // GET: Person
        public ActionResult Persons()
        {
            // Create a list of Person objects
            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 (HttpContext.Request.HttpMethod == "POST")
            {
                // Define the path to the View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                // Instantiate the ChromePdfRenderer
                ChromePdfRenderer renderer = new ChromePdfRenderer();

                // Render the view to a PDF document
                PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);

                // Set headers to view the PDF in-browser
                Response.Headers.Add("Content-Disposition", "inline");

                // Return the generated PDF file
                return File(pdf.BinaryData, "application/pdf");
            }
            return View(persons);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}
Imports IronPdf
Imports System.Collections.Generic
Imports System.Web.Mvc
Imports ViewToPdfMVCSample.Models

Namespace ViewToPdfMVCSample.Controllers
	Public Class HomeController
		Inherits Controller

		Public Function Index() As ActionResult
			Return View()
		End Function

		' GET: Person
		Public Function Persons() As ActionResult
			' Create a list of Person objects
'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 HttpContext.Request.HttpMethod = "POST" Then
				' Define the path to the View file
				Dim viewPath = "~/Views/Home/Persons.cshtml"

				' Instantiate the ChromePdfRenderer
				Dim renderer As New ChromePdfRenderer()

				' Render the view to a PDF document
				Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)

				' Set headers to view the PDF in-browser
				Response.Headers.Add("Content-Disposition", "inline")

				' Return the generated PDF file
				Return File(pdf.BinaryData, "application/pdf")
			End If
			Return View(persons_Conflict)
		End Function

		Public Function About() As ActionResult
			ViewBag.Message = "Your application description page."
			Return View()
		End Function

		Public Function Contact() As ActionResult
			ViewBag.Message = "Your contact page."
			Return View()
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

RenderView メソッドを使用して PdfDocument オブジェクトを取得したら、さまざまな改善と調整を加えることができます。 You can convert the PDF to PDFA or PDFUA formats, sign digital signature to the created PDF, or merge and split PDF documents as required. Moreover, the library enables you to rotate pages, insert annotations or bookmarks, and apply distinct watermarks to your PDF files.

ビューを追加

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

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

  • 新しいスキャフォールド アイテムには「MVC 5 ビュー」を選択します。

スキャフォールドを選択

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

ビューを追加

これにより、「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」の後に配置します。

ActionLink メソッドの値が、今回の場合は「Persons」 というファイル名と完全に一致していることを確認してください。

<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
    <div class="container">
        @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Persons", "Persons", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
            </ul>
        </div>
    </div>
</nav>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-dark">
    <div class="container">
        @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
            <ul class="navbar-nav flex-grow-1">
                <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Persons", "Persons", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("About", "About", "Home", new { area = "" }, new { @class = "nav-link" })</li>
                <li>@Html.ActionLink("Contact", "Contact", "Home", new { area = "" }, new { @class = "nav-link" })</li>
            </ul>
        </div>
    </div>
</nav>
HTML

プロジェクトを実行する

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

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

出力PDF

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

このガイドの完全なコードをダウンロードできます。これは、ASP.NET Web アプリケーション (.NET Framework) MVC プロジェクトとして Visual Studio で開くことのできる ZIP ファイル形式で提供されます。

PDF 変換用 MVC サンプル プロジェクトをダウンロード

よくある質問

ASP.NET Core MVCでViewをPDFに変換するにはどうすればよいですか?

ASP.NET Core MVCでは、IronPDFライブラリを使用してViewをPDFに変換できます。NuGetを介してIronPdf.Extensions.Mvc.Frameworkパッケージをインストールし、ChromePdfRendererクラスを使用してViewをPDFドキュメントにレンダリングします。

ASP.NET MVCでViewをPDFドキュメントにレンダリングするために必要なものは何ですか?

ASP.NET MVCでViewをPDFドキュメントにレンダリングするには、IronPDFライブラリとChromePdfRendererクラスが必要で、これにはHttpContext、Viewパス、およびPDFを生成するためのデータリストが必要です。

ASP.NETアプリケーションでIronPDFを使用してPDF出力をカスタマイズするにはどうすればよいですか?

IronPDFはRenderingOptionsを使用してPDF出力のカスタマイズを可能にします。マージンを調整したり、カスタムヘッダーやフッターを追加したり、ページ番号を含めてPDFドキュメントをニーズに合わせて調整できます。

PDF生成のためにASP.NET MVCでモデルクラスを設定するためにはどのような手順がありますか?

ASP.NET MVCでモデルクラスを設定するには、「Models」フォルダーに移動し、新しいC#クラスファイルを作成し、PDF生成に必要なデータ構造を表すプロパティでクラスを定義します。

ASP.NET MVCのViewにPDF生成ボタンを統合するにはどうすればよいですか?

ASP.NET MVCのViewにPDF生成ボタンを統合するには、ViewのHTMLマークアップにボタン要素を追加し、IronPDFを使用してViewをPDFとしてレンダリングするアクションにリンクします。

ASP.NET MVCでViewを追加するプロセスは何ですか?

ASP.NET MVCでViewを追加するには、コントローラー内の目的のアクションを右クリックし、「Add View」を選択し、「MVC 5 View」をスキャフォールディングされたアイテムとして選択し、適切なテンプレートとモデルクラスを選択します。

ASP.NET MVCでViewからPDFに変換するためのサンプルプロジェクトはどこで見つけることができますか?

IronPDFのウェブサイトからPDF変換のための完全なMVCサンプルプロジェクトをダウンロードでき、これはVisual Studioで実装するためのジップファイルを含んでいます。

ASP.NET MVCプロジェクトでIronPDFをインストールするにはどうすればよいですか?

NuGetパッケージマネージャーを使用して次のコマンドでASP.NET MVCプロジェクトにIronPDFをインストールします:Install-Package IronPdf.Extensions.Mvc.Framework

ASP.NET MVCでPDF生成が失敗した場合の一般的なトラブルシューティング手順は何ですか?

PDF生成がASP.NET MVCで失敗した場合は、IronPDFパッケージが正しくインストールされていることを確認し、ChromePdfRendererに渡されるパスとコンテキストをチェックし、ビューとデータが正しくレンダリングされているか確認します。

IronPDF は .NET 10 と互換性がありますか? また、アップグレードするとどのような利点がありますか?

はい。IronPDF は .NET 10 と完全に互換性があります。アップグレードすると、ヒープ割り当ての削減、メモリ使用量の改善、HTML から PDF へのレンダリングのパフォーマンス向上、新しい言語機能やフレームワーク拡張機能へのアクセスなど、ランタイムの改善が実現します。

Chaknith Bin
ソフトウェアエンジニア
ChaknithはIronXLとIronBarcodeに取り組んでいます。彼はC#と.NETの深い専門知識を持ち、ソフトウェアの改善や顧客サポートに貢献しています。ユーザーとの対話から得られる洞察が、より良い製品、ドキュメント、および全体的な経験に寄与しています。
準備はいいですか?
Nuget ダウンロード 16,154,058 | バージョン: 2025.11 ただ今リリースされました