IronPDF Razor拡張

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

IronPDFは、.NETおよび.NET Core向けのPDFライブラリです。 これは主に無料のPDFライブラリです。IronPDFはオープンに商業利用できるC# PDFライブラリです。 開発に関しては無料ですが、商用展開にはライセンスが必要です。 このより明確なライセンスモデルでは、開発者がGNU / AGPLライセンスモデルの細部を学ぶ必要がなく、自分のプロジェクトに集中することができます。

IronPDFは、.NETおよび.NET Core開発者が、C#、F#、およびVB.NETでPDFコンテンツを簡単に生成、マージ、分割、編集、および抽出することを可能にします。.NET Coreおよび.NET Frameworkで、HTML、ASPX、CSS、JS、および画像ファイルからPDFを作成することもできます。

IronPDFは、HTMLからPDFへの変換を通じて、包括的なPDF編集および生成機能を提供します。 それはどのように動作しますか? ほとんどのドキュメントデザインとレイアウトは既存のHTMLおよびHTML5アセットを使用できます。

このリンクからプロジェクトファイルをダウンロードできます リンク.

.NETおよび.NET Coreアプリケーション向けのIronPDF機能

素晴らしいIronPDF pdfライブラリの特徴には次のようなものがあります:

  • .NET の PDF ライブラリは可能です PDFを生成 HTML、画像、ASPXファイルからドキュメント
  • .NETおよび.NET CoreアプリケーションでPDFテキストを読み取る
  • PDFからデータと画像を抽出する
  • PDF文書の結合
  • PDF分割
  • PDFの操作

IronPDFの利点

  • IronPDF PDFライブラリは簡単にインストールできます。
  • IronPDF .NETライブラリには迅速で簡単なライセンスオプションがあります。
  • IronPDFは、ほとんどの.NET PDFライブラリよりも優れており、ほとんどの.NET Core PDFライブラリよりも優れたパフォーマンスを発揮します。

IronPDFは、あなたが探していたPDFソリューションです。


IronPDF pdfライブラリのインストール

.NETまたは.NET CoreにIronPDFライブラリをインストールすることは非常に簡単です。 次の方法でインストールすることができます:

NuGetパッケージマネージャーを使用し、コマンドプロンプトに以下を入力してください:

Install-Package IronPdf

Visual Studio の NuGet パッケージ マネージャーを使用して、プロジェクト メニューから Manage NuGet Packages を選択し、以下のように IronPDF を検索します。

//『マージンを大きくするための画像ラッパー - リンクは保持』

図1 - IronPDF NuGet パッケージ

これはPDF拡張機能をインストールします。

IronPDFを使用して、ASP.NET MVCでPDFファイルを返すことができます。以下にいくつかのコード例を示します:

以下に示されているように、コントローラーによって提供されるメソッドの例。

public FileResult Generate_PDF_FromHTML_Or_MVC(long id) {

  using var objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>"); //Create a PDF Document 
  var objLength = objPDF.BinaryData.Length; //return a pdf document from a view
  Response.AppendHeader("Content-Length", objLength.ToString());
  Response.AppendHeader("Content-Disposition", "inline; filename=PDFDocument_" + id + ".pdf");

  return File(objPDF.BinaryData, "application/pdf;");
}
public FileResult Generate_PDF_FromHTML_Or_MVC(long id) {

  using var objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>"); //Create a PDF Document 
  var objLength = objPDF.BinaryData.Length; //return a pdf document from a view
  Response.AppendHeader("Content-Length", objLength.ToString());
  Response.AppendHeader("Content-Disposition", "inline; filename=PDFDocument_" + id + ".pdf");

  return File(objPDF.BinaryData, "application/pdf;");
}
Public Function Generate_PDF_FromHTML_Or_MVC(ByVal id As Long) As FileResult

  Dim objPDF = Renderer.RenderHtmlAsPdf("<h1>IronPDF and MVC Example</h1>") 'Create a PDF Document
  Dim objLength = objPDF.BinaryData.Length 'return a pdf document from a view
  Response.AppendHeader("Content-Length", objLength.ToString())
  Response.AppendHeader("Content-Disposition", "inline; filename=PDFDocument_" & id & ".pdf")

  Return File(objPDF.BinaryData, "application/pdf;")
End Function
VB   C#

以下はASP.NETで既存のPDFを提供する例です。

Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment;filename=\"FileName.pdf\"");
Response.BinaryWrite(System.IO.File.ReadAllBytes("PdfName.pdf"));
Response.Flush();
Response.End();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment;filename=\"FileName.pdf\"");
Response.BinaryWrite(System.IO.File.ReadAllBytes("PdfName.pdf"));
Response.Flush();
Response.End();
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition","attachment;filename=""FileName.pdf""")
Response.BinaryWrite(System.IO.File.ReadAllBytes("PdfName.pdf"))
Response.Flush()
Response.End()
VB   C#

ASP.NETでMVCと.NET Coreを使用する簡単な例を見てみましょう。 Visual Studio を開き、新しい ASP.NET Core Web アプリケーションを作成してください。

以下を日本語に翻訳してください:

  1. Visual Studioで新しいASP.NET Core Webプロジェクトを作成する

ヴィジュアルスタジオで新しいASP.NET Coreウェブプロジェクトを作成する

ASP.NET Coreプロジェクトを作成

2. MVCモデルを作成する

  • 新しいフォルダを作成し、「Models」と名前を付けます。
フォルダーを追加
  • モデルフォルダを右クリックし、新しいクラスを追加します。
クラスを追加
  • クラス名を「ExampleModel」に変更します。 たとえば、モデルにコンテンツを追加します:
namespace WebApplication4.Models
{
    public class ExampleModel
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
}
namespace WebApplication4.Models
{
    public class ExampleModel
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
}
Namespace WebApplication4.Models
	Public Class ExampleModel
		Public Property Name() As String
		Public Property Surname() As String
		Public Property Age() As Integer
	End Class
End Namespace
VB   C#

3. MVCコントローラーを追加

  • 新しいフォルダを作成し、「Controllers」と名付けます。
  • コントローラーフォルダーを右クリックし、新しい「MVCコントローラー - 空」を追加します
コントローラークラスを追加

コントローラーにコンテンツを追加:

namespace WebApplication4.Models
{
    public class HomeController : Controller
    {
        [HttpPost]
        public IActionResult ExampleView(ExampleModel model)
        {
            var html = this.RenderViewAsync("_Example", model);
            var ironPdfRender = new IronPdf.ChromePdfRenderer();
            using var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result);

            return File(pdfDoc.Stream.ToArray(), "application/pdf");
        }
    }
}
namespace WebApplication4.Models
{
    public class HomeController : Controller
    {
        [HttpPost]
        public IActionResult ExampleView(ExampleModel model)
        {
            var html = this.RenderViewAsync("_Example", model);
            var ironPdfRender = new IronPdf.ChromePdfRenderer();
            using var pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result);

            return File(pdfDoc.Stream.ToArray(), "application/pdf");
        }
    }
}
Namespace WebApplication4.Models
	Public Class HomeController
		Inherits Controller

		<HttpPost>
		Public Function ExampleView(ByVal model As ExampleModel) As IActionResult
			Dim html = Me.RenderViewAsync("_Example", model)
			Dim ironPdfRender = New IronPdf.ChromePdfRenderer()
			Dim pdfDoc = ironPdfRender.RenderHtmlAsPdf(html.Result)

			Return File(pdfDoc.Stream.ToArray(), "application/pdf")
		End Function
	End Class
End Namespace
VB   C#

4. Index.cshtml を変更

Pagesフォルダー内のIndex.cshtmlファイルを次のように変更します:

@page
@model WebApplication4.Models.ExampleModel
@{
    ViewBag.Title = "Example Index View";
}
<h2>Index</h2>
<form asp-action="ExampleView" enctype="multipart/form-data">
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>
        <button type="submit">Save</button>
    </div>
}
</form>
@page
@model WebApplication4.Models.ExampleModel
@{
    ViewBag.Title = "Example Index View";
}
<h2>Index</h2>
<form asp-action="ExampleView" enctype="multipart/form-data">
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Surname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Surname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Surname, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>
        <button type="submit">Save</button>
    </div>
}
</form>
HTML

5. Razorページを追加する

PagesのSharedフォルダー内にRazorページを追加し、"_Example.cshtml" と名付けてください。

Razorページを追加

以下のコードを _Example.cshtml に追加してください:

@Html.Partial("../Index.cshtml")
@Html.Partial("../Index.cshtml")
HTML

新しいクラスを追加

  • 新しいクラス名「ControllerPDF」を追加する

    このクラスは、_Layout.cshtml のラップで _Example.cshtml からhtmlを取得し、それを HomeController.cs に返します。

  • 以下のコードを追加してください:
namespace WebApplication4
{
    public static class ControllerPDF
    {
        public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }
            controller.ViewData.Model = model;
            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
                if (viewResult.Success == false)
                {
                    return $"A view with the name {viewName} could not be found";
                }
                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
                await viewResult.View.RenderAsync(viewContext);
                return writer.GetStringBuilder().ToString();
            }
        }
    }
}
namespace WebApplication4
{
    public static class ControllerPDF
    {
        public static async Task<string> RenderViewAsync<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)
        {
            if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.ActionDescriptor.ActionName;
            }
            controller.ViewData.Model = model;
            using (var writer = new StringWriter())
            {
                IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
                ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);
                if (viewResult.Success == false)
                {
                    return $"A view with the name {viewName} could not be found";
                }
                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, new HtmlHelperOptions());
                await viewResult.View.RenderAsync(viewContext);
                return writer.GetStringBuilder().ToString();
            }
        }
    }
}
Namespace WebApplication4
	Public Module ControllerPDF
		<System.Runtime.CompilerServices.Extension> _
		Public Async Function RenderViewAsync(Of TModel)(ByVal controller As Controller, ByVal viewName As String, ByVal model As TModel, Optional ByVal As Boolean = False) As Task(Of String)
			If String.IsNullOrEmpty(viewName) Then
				viewName = controller.ControllerContext.ActionDescriptor.ActionName
			End If
			controller.ViewData.Model = model
			Using writer = New StringWriter()
				Dim viewEngine As IViewEngine = TryCast(controller.HttpContext.RequestServices.GetService(GetType(ICompositeViewEngine)), ICompositeViewEngine)
				Dim viewResult As ViewEngineResult = viewEngine.FindView(controller.ControllerContext, viewName, Not partial)
				If viewResult.Success = False Then
					Return $"A view with the name {viewName} could not be found"
				End If
				Dim viewContext As New ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer, New HtmlHelperOptions())
				Await viewResult.View.RenderAsync(viewContext)
				Return writer.GetStringBuilder().ToString()
			End Using
		End Function
	End Module
End Namespace
VB   C#

7. Program.csを修正する

以下のコードを追加して、保存ボタンが押されたときにページが正しいURLにナビゲートされるようにしてください。

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllerRoute(name:= "default", pattern:= "{controller=Home}/{action=Index}/{id?}")
VB   C#

デモンストレーション

  • Index.cshtmlから、asp-action="ExampleView"で保存ボタンが押されたときにExampleViewメソッドがアクティブになります。
  • ControllerPDFクラスのRenderViewAsyncメソッドはExampleViewから呼び出されます。 このメソッドは、_Example.cshtml を _layout.cshtml でラップした生成されたHTMLを返します。

  • RenderViewAsyncからの戻りHTMLをIronPDFのRenderHtmlAsPdfメソッドに渡すことによって、PDFドキュメントを生成します。
ASP.NET Coreプロジェクトを作成