ASP.NET 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コンテンツを動的にレンダリングすることで、ユーザーにデータを提示する役割を担っています。

IronPDF拡張パッケージ

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

PM > Install-Package IronPdf.Extensions.Mvc.Framework

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

PDF用C# NuGetライブラリ

でインストール NuGet

Install-Package IronPdf.Extensions.Mvc.Framework

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

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

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

クラスのモデルを追加

  • 「Models」フォルダーに移動する
  • 新しいC#クラスファイル「Person」を作成してください。このクラスは個々のデータを表すモデルとして機能します。 以下のコードスニペットを使用してください:
: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
VB   C#

コントローラーを編集

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

コード内で、最初に ChromePdfRenderer クラスが作成されます。 RenderView メソッドを使用するには、HttpContext を提供し、「Persons.cshtml」ファイルへのパスを指定し、必要なデータを含むリストを提供する必要があります。 ビューをレンダリングする際、ユーザーはRenderingOptionsを利用して余白をカスタマイズし、 カスタムテキストおよびHTMLヘッダーとフッター, を適用 ページ番号 結果として得られるPDFドキュメント。

次の内容にご注意ください。
以下のコードを使用してPDFドキュメントをマシンにダウンロードすることができます: バイナリデータ(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()
        {
            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")
            {
                // Provide the path to your View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                ChromePdfRenderer renderer = new ChromePdfRenderer();

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

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

                // View the PDF
                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()
        {
            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")
            {
                // Provide the path to your View file
                var viewPath = "~/Views/Home/Persons.cshtml";

                ChromePdfRenderer renderer = new ChromePdfRenderer();

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

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

                // View the PDF
                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
'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
				' Provide the path to your View file
				Dim viewPath = "~/Views/Home/Persons.cshtml"

				Dim renderer As New ChromePdfRenderer()

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

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

				' View the PDF
				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
VB   C#

RenderViewメソッドを通じて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アクションを右クリック」

  • 新しくスキャフォールディングされたアイテムには「MVC 5 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」ファイルに移動します。「Home」の後に「Person」ナビゲーションアイテムを配置します。

    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プロジェクトをダウンロード このガイドの完全なコードをダウンロードできます。これはVisual StudioでASP.NET Webアプリケーションとして開くことができる圧縮ファイルとして提供されます。 (.NETフレームワーク) MVCプロジェクト。 [プロジェクトをダウンロードするにはこちらをクリックしてください。](/static-assets/pdf/how-to/cshtml-to-pdf-mvc-framework/ViewToPdfMVCSample.zip)

チャクニット・ビン

ソフトウェアエンジニア

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