フッターコンテンツにスキップ
IRONPDFの使用

C#でIronPDFを使用してFluent Validationを使用する方法

Fluent Validationとは?

FluentValidationは、強く型指定された検証ルールの作成を手助けする.NET検証ライブラリです。 流暢なインターフェースとラムダ式を使い、コードをより読みやすく、保守しやすくします。 モデルクラスでデータ注釈や手動検証を使用する代わりに、Fluent Validationを使用して検証論理のための別のクラスを作成できます。

Fluent Validationは検証における柔軟性を向上させます。 一般的なシナリオに対応したビルドインバリデーター、カスタムバリデーションの作成機能、バリデーションルールを簡単に連鎖する方法を提供し、Fluent Validationは.NET Coreツールキットの強力なツールです。

Fluent Validationの理解

Fluent Validationは、モデルクラスのための検証ルールを簡単に作成するための.NET向けオープンソースライブラリです。

  1. バリデーター: バリデーターは検証ロジックをカプセル化するクラスです。 AbstractValidator<T>基底クラスを継承することで、通常作成されます。
  2. ルール: ルールはプロパティが満たすべき条件です。 ルールはバリデータークラス内でRuleForメソッドを使って定義されます。
  3. バリデーションエラー: ルールが失敗した場合、Fluent Validationはエラーの詳細を含むValidationFailureオブジェクトを作成します。

IronPDFとは何ですか?

IronPDF - Convert HTML to PDF in C#はHTMLコンテンツからPDFドキュメントを生成できる強力な.NETライブラリです。 請求書やレポート、その他の文書を作成する必要がある場合、IronPDFは使いやすいソリューションを提供します。 ASP.NET Coreアプリケーションとシームレスに統合され、わずか数行のコードで高品質なPDFファイルを生成できます。

Fluent ValidationとIronPDFの使用法

Fluent ValidationとIronPDFが何であるかを理解したところで、それらを一緒に使用する方法を見てみましょう。 このチュートリアルでは、FluentValidationをASP.NET Coreで使用して請求書の内容を検証し、IronPDFを使ってPDFを生成する請求書ジェネレーターを構築します。

プロジェクトのセットアップ

まず、Visual Studioまたはお好みの開発環境で新しいコンソールアプリケーションを作成します。

  1. Visual Studioを開き、ファイル > 新規作成 > プロジェクトに進みます。
  2. プロジェクトテンプレートとして「Console App (ASP.NET Core)」を選択し、プロジェクトの名前を指定します。

    C#でFluent ValidationをIronPDFに使用する方法, 図1: 新しいコンソールアプリケーションの作成 新しいコンソール アプリケーションを作成する

  3. 次へボタンをクリックし、プロジェクトを命名してリポジトリの場所を選択して構成します。

    C#でFluent ValidationをIronPDFに使用する方法, 図2: 新しいアプリケーションの構成 新しいアプリケーションの構成

  4. 次へボタンをクリックし、.NETフレームワークを選択します。 最新の.NETフレームワーク(7)が推奨されます。

    C#でFluent ValidationをIronPDFに使用する方法, 図3: .NETフレームワークの選択 .NET Framework の選択

  5. 作成ボタンをクリックしてプロジェクトを作成します。

必要なパッケージをインストールする

プロジェクトが作成されたら、Fluent ValidationとIronPDFのための必要なNuGetパッケージを追加します。

  1. ソリューションエクスプローラーでプロジェクトを右クリックし、「NuGetパッケージの管理」を選択します。
  2. 「FluentValidation」を検索し、「インストール」をクリックしてパッケージをプロジェクトに追加します。

    C#でFluent ValidationをIronPDFに使用する方法, 図4: NuGetパッケージマネージャーUIでFluentValidationパッケージをインストールします NuGetパッケージマネージャーUIでFluentValidationパッケージをインストールします

  3. 同様にして「IronPDF - Powerful .NET PDF Library」を検索し、IronPDFパッケージをインストールします。

あるいは、NuGetパッケージマネージャーコンソールを使用してIronPDFをインストールできます。以下のコマンドを使用します:

Install-Package IronPdf

C#でFluent ValidationをIronPDFに使用する方法, 図5: パッケージマネージャーコンソールでIronPdfパッケージをインストールします パッケージマネージャーコンソールでIronPdfパッケージをインストールします

プロジェクトがセットアップされ、必要なパッケージがインストールされたので、PDFコンテンツクラスの定義に進みましょう。

PDF コンテンツの定義

この例では、InvoiceContentおよびInvoiceItemの2つのクラスでHTMLコードから簡単な請求書PDFを作成します。

using System.Collections.Generic;
using System.Linq;

public abstract class PdfContent
{
    // Abstract method to generate the HTML string
    public abstract string RenderHtml();
}

public class InvoiceContent : PdfContent
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    public List<InvoiceItem> InvoiceItems { get; set; }

    // Constructs the HTML representation of the invoice
    public override string RenderHtml()
    {
        string invoiceItemsHtml = string.Join("", InvoiceItems.Select(item => $"<li>{item.Description}: {item.Price}</li>"));
        return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>";
    }
}

public class InvoiceItem
{
    public string Description { get; set; }
    public decimal Price { get; set; }
}
using System.Collections.Generic;
using System.Linq;

public abstract class PdfContent
{
    // Abstract method to generate the HTML string
    public abstract string RenderHtml();
}

public class InvoiceContent : PdfContent
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    public List<InvoiceItem> InvoiceItems { get; set; }

    // Constructs the HTML representation of the invoice
    public override string RenderHtml()
    {
        string invoiceItemsHtml = string.Join("", InvoiceItems.Select(item => $"<li>{item.Description}: {item.Price}</li>"));
        return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>";
    }
}

public class InvoiceItem
{
    public string Description { get; set; }
    public decimal Price { get; set; }
}
Imports System.Collections.Generic
Imports System.Linq

Public MustInherit Class PdfContent
	' Abstract method to generate the HTML string
	Public MustOverride Function RenderHtml() As String
End Class

Public Class InvoiceContent
	Inherits PdfContent

	Public Property CustomerName() As String
	Public Property Address() As String
	Public Property InvoiceItems() As List(Of InvoiceItem)

	' Constructs the HTML representation of the invoice
	Public Overrides Function RenderHtml() As String
		Dim invoiceItemsHtml As String = String.Join("", InvoiceItems.Select(Function(item) $"<li>{item.Description}: {item.Price}</li>"))
		Return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>"
	End Function
End Class

Public Class InvoiceItem
	Public Property Description() As String
	Public Property Price() As Decimal
End Class
$vbLabelText   $csharpLabel

上記のコードでは、RenderHtmlという抽象メソッドを持つ抽象PdfContentクラスが定義されています。 InvoiceContentクラスはPdfContentを拡張し、請求書PDFの内容を表します。 顧客の名前、住所、および請求書項目のリストのプロパティを持っています。 InvoiceItemクラスには、'Description'と'Price'の2つのプロパティがあります。 RenderHtmlメソッドは、コンテンツに基づいて請求書のHTMLマークアップを生成します。

PDFコンテンツが定義されたので、Fluent Validationを使用して検証ルールを作成しましょう。

検証ルールの作成

InvoiceContentクラスの検証ルールを構築するには、InvoiceContentValidatorというバリデータークラスを作成します。 このクラスはFluentValidationによって提供されるAbstractValidator<InvoiceContent>を継承します。

using FluentValidation;

public class InvoiceContentValidator : AbstractValidator<InvoiceContent>
{
    public InvoiceContentValidator()
    {
        RuleFor(content => content.CustomerName).NotEmpty().WithMessage("Customer name is required.");
        RuleFor(content => content.Address).NotEmpty().WithMessage("Address is required.");
        RuleFor(content => content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.");
        RuleForEach(content => content.InvoiceItems).SetValidator(new InvoiceItemValidator());
    }
}

public class InvoiceItemValidator : AbstractValidator<InvoiceItem>
{
    public InvoiceItemValidator()
    {
        RuleFor(item => item.Description).NotEmpty().WithMessage("Description is required.");
        RuleFor(item => item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.");
    }
}
using FluentValidation;

public class InvoiceContentValidator : AbstractValidator<InvoiceContent>
{
    public InvoiceContentValidator()
    {
        RuleFor(content => content.CustomerName).NotEmpty().WithMessage("Customer name is required.");
        RuleFor(content => content.Address).NotEmpty().WithMessage("Address is required.");
        RuleFor(content => content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.");
        RuleForEach(content => content.InvoiceItems).SetValidator(new InvoiceItemValidator());
    }
}

public class InvoiceItemValidator : AbstractValidator<InvoiceItem>
{
    public InvoiceItemValidator()
    {
        RuleFor(item => item.Description).NotEmpty().WithMessage("Description is required.");
        RuleFor(item => item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.");
    }
}
Imports FluentValidation

Public Class InvoiceContentValidator
	Inherits AbstractValidator(Of InvoiceContent)

	Public Sub New()
		RuleFor(Function(content) content.CustomerName).NotEmpty().WithMessage("Customer name is required.")
		RuleFor(Function(content) content.Address).NotEmpty().WithMessage("Address is required.")
		RuleFor(Function(content) content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.")
		RuleForEach(Function(content) content.InvoiceItems).SetValidator(New InvoiceItemValidator())
	End Sub
End Class

Public Class InvoiceItemValidator
	Inherits AbstractValidator(Of InvoiceItem)

	Public Sub New()
		RuleFor(Function(item) item.Description).NotEmpty().WithMessage("Description is required.")
		RuleFor(Function(item) item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.")
	End Sub
End Class
$vbLabelText   $csharpLabel

ソースコードでは、InvoiceContentValidatorクラスが定義されており、AbstractValidator<InvoiceContent>を継承します。 バリデータークラスのコンストラクタ内で、RuleForメソッドがInvoiceContentクラスの各プロパティの検証ルールを定義します。

例えば、RuleFor(content => content.CustomerName)は顧客名が空でないことを指定します。 同様に、住所および請求書項目のプロパティに対しても検証ルールが定義されています。

RuleForEachメソッドは、InvoiceItemsリスト内の各項目を繰り返し、InvoiceItemValidatorを適用します。 InvoiceItemValidatorクラスはInvoiceItemクラスの検証ルールを含んでいます。

これらの検証ルールが整ったら、IronPDFを使用したPDF生成に進みましょう。

IronPDFを使用してPDFを生成する

IronPDF - Generate and Edit PDF Documentsは、PDFドキュメントの作成および操作のための人気のある.NETライブラリです。 IronPDFは、検証済みの請求書内容に基づいてPDFを生成するために使用されます。

using IronPdf;
using FluentValidation;

public class PdfService
{
    // Generates a PDF document for the provided content
    public PdfDocument GeneratePdf<T>(T content) where T : PdfContent
    {
        // Validate the content using the appropriate validator
        var validator = GetValidatorForContent(content);
        var validationResult = validator.Validate(content);

        // Check if validation is successful
        if (!validationResult.IsValid)
        {
            throw new FluentValidation.ValidationException(validationResult.Errors);
        }

        // Generate the PDF using IronPDF
        var renderer = new ChromePdfRenderer();
        return renderer.RenderHtmlAsPdf(content.RenderHtml());
    }

    // Retrieves the appropriate validator for the content
    private IValidator<T> GetValidatorForContent<T>(T content) where T : PdfContent
    {
        if (content is InvoiceContent)
        {
            return (IValidator<T>)new InvoiceContentValidator();
        }
        else
        {
            throw new NotSupportedException("Unsupported content type.");
        }
    }
}
using IronPdf;
using FluentValidation;

public class PdfService
{
    // Generates a PDF document for the provided content
    public PdfDocument GeneratePdf<T>(T content) where T : PdfContent
    {
        // Validate the content using the appropriate validator
        var validator = GetValidatorForContent(content);
        var validationResult = validator.Validate(content);

        // Check if validation is successful
        if (!validationResult.IsValid)
        {
            throw new FluentValidation.ValidationException(validationResult.Errors);
        }

        // Generate the PDF using IronPDF
        var renderer = new ChromePdfRenderer();
        return renderer.RenderHtmlAsPdf(content.RenderHtml());
    }

    // Retrieves the appropriate validator for the content
    private IValidator<T> GetValidatorForContent<T>(T content) where T : PdfContent
    {
        if (content is InvoiceContent)
        {
            return (IValidator<T>)new InvoiceContentValidator();
        }
        else
        {
            throw new NotSupportedException("Unsupported content type.");
        }
    }
}
Imports IronPdf
Imports FluentValidation

Public Class PdfService
	' Generates a PDF document for the provided content
	Public Function GeneratePdf(Of T As PdfContent)(ByVal content As T) As PdfDocument
		' Validate the content using the appropriate validator
		Dim validator = GetValidatorForContent(content)
		Dim validationResult = validator.Validate(content)

		' Check if validation is successful
		If Not validationResult.IsValid Then
			Throw New FluentValidation.ValidationException(validationResult.Errors)
		End If

		' Generate the PDF using IronPDF
		Dim renderer = New ChromePdfRenderer()
		Return renderer.RenderHtmlAsPdf(content.RenderHtml())
	End Function

	' Retrieves the appropriate validator for the content
	Private Function GetValidatorForContent(Of T As PdfContent)(ByVal content As T) As IValidator(Of T)
		If TypeOf content Is InvoiceContent Then
			Return DirectCast(New InvoiceContentValidator(), IValidator(Of T))
		Else
			Throw New NotSupportedException("Unsupported content type.")
		End If
	End Function
End Class
$vbLabelText   $csharpLabel

PdfServiceクラスはGeneratePdfメソッドを提供します。 このメソッドはPdfContentオブジェクトを入力として受け取り、検証済みのコンテンツに基づいてPDFドキュメントを生成します。

まず、GetValidatorForContentメソッドを呼び出して適切な検証器を取得し、コンテンツの種類を確認し、対応する検証器を返します。 私たちの場合、InvoiceContentをサポートし、InvoiceContentValidatorを使用します。

次に、バリデーターのValidateメソッドを呼び出してコンテンツを検証します。 検証結果はValidationResultオブジェクトに格納されます。

もし検証が失敗した場合(!validationResult.IsValid)、検証エラーを含むFluentValidation.ValidationExceptionがスローされます。 それ以外の場合、IronPDFを使用してPDFが生成されます。

ChromePdfRendererのインスタンスを作成して、HTMLコンテンツをPDFとしてレンダリングします。 RenderHtmlAsPdfメソッドがrendererオブジェクトで呼び出され、content.RenderHtmlメソッドによって生成されるHTMLを渡し、PDFドキュメントを生成します。

PDF生成ロジックを定義したので、発生する可能性のある検証エラーを処理しましょう。

検証エラーの処理

検証エラーが発生した場合は、ユーザーにエラーメッセージを表示し、優雅に処理したいです。 ProgramクラスのMainメソッドを修正して、例外を処理し、ユーザーに意味のあるメッセージを表示するようにしましょう。

using System;
using System.Collections.Generic;

public class Program
{
    static void Main(string[] args)
    {
        var pdfService = new PdfService();

        // Test 1: Empty Customer Name
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                    new InvoiceItem { Description = "Item 1", Price = 19.99M },
                    new InvoiceItem { Description = "Item 2", Price = 29.99M }
                }
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        // Test 2: Empty InvoiceItems
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem>()  // Empty list
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        // Successful generation
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                    new InvoiceItem { Description = "Item 1", Price = 19.99M },
                    new InvoiceItem { Description = "Item 2", Price = 29.99M }
                }
            };
            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }
    }
}
using System;
using System.Collections.Generic;

public class Program
{
    static void Main(string[] args)
    {
        var pdfService = new PdfService();

        // Test 1: Empty Customer Name
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                    new InvoiceItem { Description = "Item 1", Price = 19.99M },
                    new InvoiceItem { Description = "Item 2", Price = 29.99M }
                }
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        // Test 2: Empty InvoiceItems
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem>()  // Empty list
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        // Successful generation
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                    new InvoiceItem { Description = "Item 1", Price = 19.99M },
                    new InvoiceItem { Description = "Item 2", Price = 29.99M }
                }
            };
            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }
    }
}
Imports System
Imports System.Collections.Generic

Public Class Program
	Shared Sub Main(ByVal args() As String)
		Dim pdfService As New PdfService()

		' Test 1: Empty Customer Name
		Try
			Dim invoiceContent As New InvoiceContent With {
				.CustomerName = "",
				.Address = "123 Main St, Anytown, USA",
				.InvoiceItems = New List(Of InvoiceItem) From {
					New InvoiceItem With {
						.Description = "Item 1",
						.Price = 19.99D
					},
					New InvoiceItem With {
						.Description = "Item 2",
						.Price = 29.99D
					}
				}
			}

			Dim pdfDocument = pdfService.GeneratePdf(invoiceContent)
			pdfDocument.SaveAs("C:\TestInvoice.pdf")
			Console.WriteLine("PDF generated successfully!")
		Catch ex As Exception
			Console.WriteLine("Error generating PDF: " & ex.Message)
		End Try

		' Test 2: Empty InvoiceItems
		Try
			Dim invoiceContent As New InvoiceContent With {
				.CustomerName = "John Doe",
				.Address = "123 Main St, Anytown, USA",
				.InvoiceItems = New List(Of InvoiceItem)()
			}

			Dim pdfDocument = pdfService.GeneratePdf(invoiceContent)
			pdfDocument.SaveAs("C:\TestInvoice.pdf")
			Console.WriteLine("PDF generated successfully!")
		Catch ex As Exception
			Console.WriteLine("Error generating PDF: " & ex.Message)
		End Try

		' Successful generation
		Try
			Dim invoiceContent As New InvoiceContent With {
				.CustomerName = "John Doe",
				.Address = "123 Main St, Anytown, USA",
				.InvoiceItems = New List(Of InvoiceItem) From {
					New InvoiceItem With {
						.Description = "Item 1",
						.Price = 19.99D
					},
					New InvoiceItem With {
						.Description = "Item 2",
						.Price = 29.99D
					}
				}
			}
			Dim pdfDocument = pdfService.GeneratePdf(invoiceContent)
			pdfDocument.SaveAs("C:\TestInvoice.pdf")
			Console.WriteLine("PDF generated successfully!")
		Catch ex As Exception
			Console.WriteLine("Error generating PDF: " & ex.Message)
		End Try
	End Sub
End Class
$vbLabelText   $csharpLabel

上記のコードでは、発生する可能性のある例外をキャッチするためにtry-catchブロックが使用されています。 例外がキャッチされた場合、Console.WriteLineを使用してユーザーにエラーメッセージが表示されます。

このアプリケーションを異なるシナリオでテストして、PDF生成と検証ルールを確認しましょう。

アプリケーションのテスト

コード例では、テストする3つのシナリオがあります:

  1. 顧客名が空である場合:顧客名を空にして検証エラーを引き起こします。
  2. 請求書項目が空である場合:請求書項目のリストを空にして検証エラーを引き起こします。
  3. 成功した生成:有効なコンテンツを提供してPDFを正常に生成します。

アプリケーションを実行し、コンソールに出力を観察してください。

Error generating PDF: Validation failed:
    -- CustomerName: Customer name is required. Severity: Error
Error generating PDF: Validation failed:
    -- InvoiceItems: At least one invoice item is required. Severity: Error
PDF generated successfully!

C#でFluent ValidationをIronPDFに使用する方法, 図6: コンソールの出力エラー コンソールの出力エラー

C#でFluent ValidationをIronPDFに使用する方法, 図7: 出力PDFファイル 出力PDFファイル

予想通り、最初の2つのシナリオでは検証エラーが表示され、3番目のシナリオでは成功メッセージが表示されます。

結論

このチュートリアルでは、Fluent Validationと、そのFluent Validationを使用してIronPDFでPDFドキュメントを生成する方法を探りました。 コンソールアプリケーションを設定し、PDFコンテンツクラスを定義することから始めました。 次に、Fluent Validationを使用して検証ルールを作成し、さまざまなシナリオでPDF生成をテストしました。

Fluent Validationは.NETアプリケーションでオブジェクトを検証するための柔軟で使いやすいアプローチを提供します。 強く型付けされた方法で検証ルールを定義し、エラーメッセージをカスタマイズし、検証エラーを優雅に処理することができます。

IronPDF Free Trial & Licensing Information は無料トライアルを提供し、ライセンスは1人の開発者あたり499ドルから始まります。

よくある質問

C#でFluent ValidationをPDF生成に統合するにはどうすればよいですか?

C#でFluent ValidationをPDF生成に統合するには、Visual Studioでコンソールアプリケーションをセットアップし、NuGetを通じてFluentValidationとIronPDFのパッケージをインストールし、Fluent Validationでモデル検証ロジックを定義しながら、IronPDFでPDFを生成します。

PDF生成と検証のためにプロジェクトを設定するにはどのような手順がありますか?

プロジェクトをセットアップするには、Visual Studioで新しいコンソールアプリケーションを作成し、NuGetを通じてIronPDFとFluentValidationのパッケージをインストールし、各ライブラリを使用してPDFコンテンツと検証ルールを定義します。

.NETライブラリを使用してHTMLコンテンツからPDFを生成するにはどうすればよいですか?

IronPDFのRenderHtmlAsPdfメソッドを使用すると、HTML文字列やファイルを高品質のPDFに変換することができます。

チュートリアルでのPdfServiceクラスの目的は何ですか?

チュートリアルのPdfServiceクラスは、最初にFluent Validationでコンテンツを検証した後、PDFを生成する管理を目的としています。検証に成功した場合、IronPDFのChromePdfRendererRenderHtmlAsPdfメソッドを使用してPDFを作成します。

Fluent Validationを使用した検証ルールはどのように定義されますか?

Fluent Validationでは、AbstractValidatorから継承したバリデータークラスを作成し、その中でRuleForメソッドを使用して各プロパティに対する条件を指定し、カスタムエラーメッセージやルールのチェーンを可能にします。

PDF生成中に検証に失敗するとどうなりますか?

検証に失敗すると、Fluent ValidationはValidationExceptionをスローし、詳細な検証エラー情報を含むので、何が問題だったかをユーザーに知らせることができます。

Fluent Validationは複雑なオブジェクトの検証に使用できますか?

はい、Fluent Validationは子バリデーターを使用して複雑なオブジェクトを検証することができ、モデル内のネストされたプロパティやコレクションを検証することを可能にします。

Fluent Validationでエラーメッセージをカスタマイズするにはどうすればよいですか?

Fluent Validationでのカスタムエラーメッセージは、RuleForで指定された各検証ルールに対してWithMessageメソッドを使用して定義できます。

PDF生成ライブラリの無料試用版はありますか?

はい、IronPDFはライブラリの機能をテストするための無料試用版を開発者に提供しており、ライセンスオプションは開発者あたり$499から始まります。

IronPDF は .NET 10 と完全に互換性がありますか?

はい。IronPDFは.NET 10と完全に互換性があり、Windows、Linux、macOSを含むプラットフォームを、様々なプロジェクトタイプ(コンソール、Web、デスクトップ、Blazorなど)でサポートしています。最新のランタイムでも、特別な回避策を必要とせずにすぐに使用できます。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。