更新済み 2024年12月17日
共有:

RazorビューをPDFにヘッドレス変換する方法

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

Chaknith Bin によって

「ヘッドレスレンダリング」という用語は、グラフィカルユーザーインターフェイス(GUI)やブラウザウィンドウを使用せずにウェブコンテンツをレンダリングするプロセスを指します。 IronPdf.Extensions.Razor パッケージは非常に便利ですが、ヘッドレスレンダリング機能を提供していません。 ヘッドレスレンダリングは、IronPDF.Extensions.Razorパッケージが対応できないユースケースギャップを埋めることができます。

私たちは、Razor.Templating.Core パッケージを使用して、cshtml(Razor Views)からhtmlに変換し、その後IronPDFを利用してPDFドキュメントを生成します。

この記事は以下のYouTube動画に触発されました:

IronPDFを始めましょう

今日から無料トライアルでIronPDFをあなたのプロジェクトで使い始めましょう。

最初のステップ:
green arrow pointer


ASP.NET Core WebアプリでRazorビューをHTMLドキュメントに変換するには、Razor.Templating.Coreパッケージをインストールしてください。

Install-Package Razor.Templating.Core

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

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

ビューを追加

  • 「Home」フォルダーを右クリックします。 「add」と「Add View」を選択してください。
  • 空のRazorビューを作成し、"Data.cshtml "と名付けます。

    ビューを追加

Data.cshtmlファイルを編集

PDFにレンダリングしたいHTML文字列を追加してください:

<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    <tr>
        <td>John Doe</td>
        <td>Software Engineer</td>
        <td>Experienced software engineer specializing in web development.</td>
    </tr>
    <tr>
        <td>Alice Smith</td>
        <td>Project Manager</td>
        <td>Seasoned project manager with expertise in agile methodologies.</td>
    </tr>
    <tr>
        <td>Michael Johnson</td>
        <td>Data Analyst</td>
        <td>Skilled data analyst proficient in statistical analysis and data visualization.</td>
    </tr>
</table>
<table class="table">
    <tr>
        <th>Name</th>
        <th>Title</th>
        <th>Description</th>
    </tr>
    <tr>
        <td>John Doe</td>
        <td>Software Engineer</td>
        <td>Experienced software engineer specializing in web development.</td>
    </tr>
    <tr>
        <td>Alice Smith</td>
        <td>Project Manager</td>
        <td>Seasoned project manager with expertise in agile methodologies.</td>
    </tr>
    <tr>
        <td>Michael Johnson</td>
        <td>Data Analyst</td>
        <td>Skilled data analyst proficient in statistical analysis and data visualization.</td>
    </tr>
</table>
HTML

Program.cs ファイルを編集

Program.cs "ファイルの中に、以下のコードを追加してください。 以下のコードは、Razor.Templating.CoreライブラリのRenderAsyncメソッドを使用してRazorビューをHTMLに変換します。 次に、ChromePdfRenderer クラスをインスタンス化し、戻り値の HTML 文字列を RenderHtmlAsPdf メソッドに渡します。 ユーザーはRenderingOptionsを利用して、結果として得られるPDFにカスタムのテキスト、HTMLヘッダーおよびフッターを含める、カスタムの余白を定義する、ページ番号を適用するなど、さまざまな機能にアクセスできます。

app.MapGet("/PrintPdf", async () =>
{
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

    string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");

    ChromePdfRenderer renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");

    return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", async () =>
{
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

    string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");

    ChromePdfRenderer renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");

    return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});

アセットリンクの変更

「Views」フォルダ ->「Shared」フォルダ -> 「_Layout.cshtml」ファイルに移動します。リンクタグ内の「~/」を「./」に変更します。

これは重要です。なぜなら、"~/"はIronPDFとうまく機能しないからです。

プロジェクトを実行

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

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

PDFを出力

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

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

プロジェクトをダウンロードするにはこちらをクリックしてください。

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

チャクニット・ビン

ソフトウェアエンジニア

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