ASP.NET Core WebアプリでRazor PagesをPDFに変換する方法

Chaknith related to ASP.NET Core WebアプリでRazor PagesをPDFに変換する方法
チャクニット・ビン
2023年9月12日
更新済み 2024年12月10日
共有:
This article was translated from English: Does it need improvement?
Translated
View the article in English

Razorページは、C#とHTMLを組み合わせてWebコンテンツを生成する.cshtml拡張子のファイルです。 ASP.NET Coreでは、Razor PagesはWebアプリケーションのコードを整理するためのより簡単な方法であり、読み取り専用のページや簡単なデータ入力を行うシンプルなページに適しています。

ASP.NET Core Webアプリは、ASP.NET Coreを使用して構築されたWebアプリケーションです。ASP.NET Coreは、最新のWebアプリケーションを開発するためのクロスプラットフォームフレームワークです。

IronPDFは、ASP.NET Core Webアプリプロジェクト内のRazor PagesからPDFファイルを作成するプロセスを簡素化します。 これにより、ASP.NET Core WebアプリケーションでのPDF生成が簡単かつ直接的になります。



IronPDF拡張パッケージ

IronPdf.Extensions.Razorパッケージは主要なIronPdfパッケージの拡張機能です。 IronPdf.Extensions.Razor と IronPdf パッケージは、ASP.NET Core Web AppでRazor PagesをPDFドキュメントにレンダリングするために必要です。

Install-Package IronPdf.Extensions.Razor
C# NuGetライブラリ for PDF

NuGetでインストール

パッケージをインストールする:Install-Package IronPdf.Extensions.Razor

RazorページをPDFにレンダリングする

RazorページをPDFファイルに変換するには、ASP.NET Core Webアプリプロジェクトが必要です。

モデルクラスを作成する

  • プロジェクトに新しいフォルダーを作成し、「Models」と名前を付けます。
  • フォルダーに標準のC#クラスを追加し、名前を「Person」にしてください。このクラスは個々のデータのモデルとして機能します。 以下のコードスニペットを使用してください:
:path=/static-assets/pdf/content-code-examples/how-to/cshtml-to-pdf-razor-model.cs
namespace RazorPageSample.Models
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
    }
}

Razorページを追加

「Pages」フォルダーに空のRazorページを追加し、名前を「persons.cshtml」としてください。

  • 以下のコードサンプルを使用して、新しく作成された "Persons.cshtml" ファイルを修正してください。

    以下のコードは、ブラウザに情報を表示するためのものです。

@page
@using RazorPageSample.Models;
@model RazorPageSample.Pages.PersonsModel
@{
}

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    @foreach (var person in ViewData ["personList"] as List<Person>)
    {
        <tr>
            <td>@person.Name</td>
            <td>@person.Title</td>
            <td>@person.Description</td>
        </tr>
    }
</table>

<form method="post">
    <button type="submit">print</button>
</form>
@page
@using RazorPageSample.Models;
@model RazorPageSample.Pages.PersonsModel
@{
}

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    @foreach (var person in ViewData ["personList"] as List<Person>)
    {
        <tr>
            <td>@person.Name</td>
            <td>@person.Title</td>
            <td>@person.Description</td>
        </tr>
    }
</table>

<form method="post">
    <button type="submit">print</button>
</form>
HTML

次に、以下のコードはまずChromePdfRendererクラスをインスタンス化します。 thisRenderRazorToPdf メソッドに渡すことで、この Razor ページを PDF ドキュメントに変換するのに十分です。

ユーザーはRenderingOptionsで利用可能なすべての機能にフルアクセスできます。 これらの機能には、生成されたPDFにページ番号を適用する機能、カスタム余白を設定する機能、カスタムテキストやHTMLヘッダーとフッターを追加する機能が含まれています。

  • 「Persons.cshtml」ファイルのドロップダウンを開き、「Persons.cshtml.cs」ファイルを確認してください。
  • 次のコードで「Persons.cshtml.cs」を修正します。

    [{i:(PDFドキュメントは次のコードを使用してブラウザで表示できます:File(pdf.BinaryData, "application/pdf")。 しかし、ブラウザで表示した後にPDFをダウンロードすると、破損したPDFドキュメントが生成されます。

using IronPdf.Razor.Pages;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPageSample.Models;

namespace RazorPageSample.Pages
{
    public class PersonsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public List<Person> persons { get; set; }

        public void OnGet()
        {
            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" }
            };

            ViewData ["personList"] = persons;
        }
        public IActionResult OnPostAsync()
        {
            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" }
            };

            ViewData ["personList"] = persons;

            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render Razor Page to PDF document
            PdfDocument pdf = renderer.RenderRazorToPdf(this);

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

            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // View output PDF on browser
            return File(pdf.BinaryData, "application/pdf");
        }
    }
}
using IronPdf.Razor.Pages;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPageSample.Models;

namespace RazorPageSample.Pages
{
    public class PersonsModel : PageModel
    {
        [BindProperty(SupportsGet = true)]
        public List<Person> persons { get; set; }

        public void OnGet()
        {
            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" }
            };

            ViewData ["personList"] = persons;
        }
        public IActionResult OnPostAsync()
        {
            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" }
            };

            ViewData ["personList"] = persons;

            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render Razor Page to PDF document
            PdfDocument pdf = renderer.RenderRazorToPdf(this);

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

            return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");

            // View output PDF on browser
            return File(pdf.BinaryData, "application/pdf");
        }
    }
}

RenderRazorToPdf メソッドは、追加の処理や編集が可能な PdfDocument オブジェクトを返します。 PDFをPDFAまたはPDFUAとしてエクスポートしたり、レンダリングされたPDFドキュメントにデジタル署名を適用したり、PDFドキュメントを結合および分割したりできます。 この方法では、ページを回転させたり、注釈ブックマークを追加したり、カスタムの透かしをPDFに捺印することができます。

ナビゲーションバーの上部にセクションを追加

  • Pages フォルダー -> Shared フォルダー -> _Layout.cshtml に移動します。 「Person」ナビゲーション項目を「Home」の後に配置します。

    asp-page属性の値が、今回の場合「Persons」というファイル名と正確に一致していることを確認してください。

<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <a class="navbar-brand" asp-area="" asp-page="/Index">RazorPageSample</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-page="/Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Persons">Person</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/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">
            <a class="navbar-brand" asp-area="" asp-page="/Index">RazorPageSample</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-page="/Index">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Persons">Person</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</header>
HTML

プロジェクトを実行

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

ASP.NET Core Webアプリプロジェクトを実行 --> ## ASP.NET Core Webアプリプロジェクトをダウンロード このガイドのコード一式をzipファイルとしてダウンロードすることができ、Visual StudioでASP.NET Core Web Appプロジェクトとして開くことができます。 [RazorPageSample.zip ASP.NET Core Web アプリプロジェクトをダウンロード](/static-assets/pdf/how-to/cshtml-to-pdf-razor/RazorPageSample.zip)
Chaknith related to プロジェクトを実行
ソフトウェアエンジニア
チャクニットは開発者のシャーロック・ホームズです。彼がソフトウェアエンジニアリングの将来性に気付いたのは、楽しみでコーディングチャレンジをしていたときでした。彼のフォーカスはIronXLとIronBarcodeにありますが、すべての製品でお客様を助けることに誇りを持っています。チャクニットは顧客と直接話すことで得た知識を活用して、製品自体のさらなる改善に貢献しています。彼の逸話的なフィードバックは、単なるJiraチケットを超えて、製品開発、ドキュメントおよびマーケティングをサポートし、顧客の全体的な体験を向上させます。オフィスにいないときは、機械学習やコーディングについて学んだり、ハイキングを楽しんだりしています。