IRONPDF 사용 How to Use Fluent Validation With IronPDF in C# 커티스 차우 업데이트됨:7월 28, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 What is Fluent Validation? FluentValidation is a .NET validation library that helps in building strongly typed validation rules. It uses a fluent interface and lambda expressions, making the code more readable and maintainable. Instead of using data annotations or manual validation in your model classes, you can use Fluent Validation to build a separate class for your validation logic. Fluent Validation brings more flexibility to the validation game. With built-in validators for common scenarios, the ability to build custom validations, and a simple way to chain validation rules, Fluent Validation is a powerful tool in the .NET Core toolkit. Understanding Fluent Validation Fluent Validation is an open-source library for .NET that makes it easy to build validation rules for your model classes. Validators: Validators are classes that encapsulate the validation logic. They are typically created by inheriting from the AbstractValidator<T> base class. Rules: A rule is a validation condition that a property must meet. Rules are defined using the RuleFor method in a validator class. Validation Failures: If a rule fails, Fluent Validation creates a ValidationFailure object that contains details about the error, including the property name and error message. What is IronPDF? IronPDF - Convert HTML to PDF in C# is a powerful .NET library that allows you to generate PDF documents from HTML content. Whether you need to create invoices, reports, or any other type of document, IronPDF provides an easy-to-use solution. It seamlessly integrates with your ASP.NET Core applications, enabling you to generate high-quality PDF files with just a few lines of code. Using Fluent Validation with IronPDF Now that we understand what Fluent Validation and IronPDF are, let's see how they can be used together. This tutorial will help build an invoice generator, where the invoice content will be validated using FluentValidation in ASP.NET Core before generating the PDF using IronPDF. Setting Up the Project To begin, let's create a new Console Application in Visual Studio or your preferred development environment. Open Visual Studio and go to File > New > Project. Select "Console App (ASP.NET Core)" as the project template and provide a name for your project. Create a new Console Application Click the Next button and configure your project by naming it and selecting the repository location. Configure the new application Click on the Next button and select the .NET Framework. The latest .NET Framework (7) is recommended. .NET Framework selection Click on the Create button to create the project. Install Required Packages Once the project is created, add the necessary NuGet packages for Fluent Validation and IronPDF. Right-click on the project in the Solution Explorer and select "Manage NuGet Packages." Search for "FluentValidation" and click "Install" to add the package to your project. Install the FluentValidation package in NuGet Package Manager UI Similarly, search for "IronPDF - Powerful .NET PDF Library" and install the IronPDF package. Alternatively, you can install IronPDF using NuGet Package Manager Console with the following command: Install-Package IronPdf Install the IronPdf package in the Package Manager Console With the project set up and the required packages installed, let's move on to defining the PDF content class. Defining the PDF Content In this example, a simple invoice PDF will be created from the HTML codes in two classes: InvoiceContent and InvoiceItem. 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; } } $vbLabelText $csharpLabel In the code above, an abstract PdfContent class is defined with an abstract method called RenderHtml. The InvoiceContent class extends PdfContent and represents the content of the invoice PDF. It has properties for the customer's name, address, and a list of invoice items. The InvoiceItem class contains two properties: 'Description' and 'Price'. The RenderHtml method generates the HTML markup for the invoice based on the content. Now that the PDF content is defined, let's move on to creating validation rules using Fluent Validation. Creating Validation Rules For building validation rules for the InvoiceContent class, create a validator class called InvoiceContentValidator. This class will inherit from AbstractValidator<InvoiceContent>, which is provided by FluentValidation. 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."); } } $vbLabelText $csharpLabel In the source code, the InvoiceContentValidator class is defined, which inherits from AbstractValidator<InvoiceContent>. Inside the constructor of the validator class, the RuleFor method defines validation rules for each property of the InvoiceContent class. For example, RuleFor(content => content.CustomerName) specifies that the customer name should not be empty. Similarly, validation rules are defined for the address and invoice items properties. The RuleForEach method iterates over each item in the InvoiceItems list and applies the InvoiceItemValidator. The InvoiceItemValidator class contains validation rules for the InvoiceItem class. With these validation rules in place, let's move on to generating the PDF using IronPDF. Generating PDF using IronPDF IronPDF - Generate and Edit PDF Documents is a popular .NET library for creating and manipulating PDF documents. IronPDF will be used to generate the PDF based on the validated invoice content. 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."); } } } $vbLabelText $csharpLabel The PdfService class provides a GeneratePdf method. This method takes a PdfContent object as input and generates the PDF document based on the validated content. First, it retrieves the appropriate validator for the content by calling the GetValidatorForContent method, which checks the type of content and returns the corresponding validator. In our case, we support InvoiceContent and use the InvoiceContentValidator. Next, the content is validated using the validator by calling its Validate method. The validation result is stored in a ValidationResult object. If the validation fails (!validationResult.IsValid), a FluentValidation.ValidationException is thrown with the validation errors. Otherwise, the PDF is generated using IronPDF. An instance of ChromePdfRenderer is created to render the HTML content as a PDF. The RenderHtmlAsPdf method is called on the renderer object, passing in the HTML generated by the content.RenderHtml method, generating the PDF document. Now that we have defined the PDF generation logic, let's handle any validation errors that may occur. Handling Validation Errors When a validation error occurs, we want to display an error message and handle it gracefully. Let's modify the Main method of the Program class to handle any exceptions and display meaningful messages to the user. 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); } } } $vbLabelText $csharpLabel In the code above, try-catch blocks are used to catch any exceptions that may occur. If an exception is caught, an error message will be shown to the user using Console.WriteLine. Now let's test this application with different scenarios to validate the PDF generation and the validation rules. Testing the Application In the code example, there are three scenarios to test: Empty customer name: Leave the customer name empty to trigger a validation error. Empty invoice items: Provide an empty list of invoice items to trigger a validation error. Successful generation: Provide valid content to generate the PDF successfully. Run the application and observe the output in the console. 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! The output error in the Console The output PDF file As expected, validation errors are shown for the first two scenarios and a success message for the third scenario. Conclusion This tutorial explored Fluent Validation and how to use it with IronPDF to generate PDF documents. Starting by setting up a Console Application and defining the PDF content class. Then, created validation rules using Fluent Validation and tested the PDF generation with different scenarios. Fluent Validation provides a flexible and easy-to-use approach for validating objects in .NET applications. It allows you to define validation rules in a strongly typed manner, customize error messages, and handle validation errors gracefully. IronPDF Free Trial & Licensing Information offers a free trial, and the license starts from $499 per developer. 자주 묻는 질문 Fluent Validation과 C#의 PDF 생성을 통합하려면 어떻게 해야 하나요? Fluent Validation과 C#의 PDF 생성을 통합하려면 Visual Studio에서 콘솔 애플리케이션을 설정하고, NuGet을 통해 FluentValidation 및 IronPDF 패키지를 설치한 다음, IronPDF를 사용하여 PDF를 생성하면서 Fluent Validation을 사용하여 모델 유효성 검사 로직을 정의할 수 있습니다. PDF 생성 및 유효성 검사를 위한 프로젝트 설정에는 어떤 단계가 포함되나요? 프로젝트를 설정하려면 Visual Studio에서 새 콘솔 애플리케이션을 만들고 NuGet을 통해 IronPDF 및 FluentValidation 패키지를 설치한 다음 각 라이브러리를 사용하여 PDF 콘텐츠 및 유효성 검사 규칙을 정의합니다. .NET 라이브러리를 사용하여 HTML 콘텐츠에서 PDF를 생성하려면 어떻게 해야 하나요? HTML 문자열이나 파일을 고품질 PDF로 변환할 수 있는 IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 HTML 콘텐츠로부터 PDF를 생성할 수 있습니다. 튜토리얼에서 PdfService 클래스의 목적은 무엇인가요? 튜토리얼의 PdfService 클래스는 먼저 유창한 유효성 검사를 사용하여 콘텐츠의 유효성을 검사하여 PDF 생성을 관리하도록 설계되었습니다. 유효성 검사가 성공하면 IronPDF의 ChromePdfRenderer 및 RenderHtmlAsPdf 메서드를 사용하여 PDF를 생성합니다. 유창한 유효성 검사를 사용하여 유효성 검사 규칙은 어떻게 정의되나요? 유창한 유효성 검사의 유효성 검사 규칙은 AbstractValidator에서 상속하는 유효성 검사기 클래스를 생성하여 정의합니다. 이 클래스 내에서 RuleFor 메서드를 사용하여 각 속성에 대한 조건을 지정하여 사용자 지정 오류 메시지 및 규칙 연쇄를 허용합니다. PDF 생성 중 유효성 검사에 실패하면 어떻게 되나요? 유효성 검사에 실패하면 유창한 유효성 검사는 사용자에게 무엇이 잘못되었는지 알려주는 데 사용할 수 있는 유효성 검사 오류에 대한 자세한 정보가 포함된 ValidationException를 던집니다. 복잡한 개체 유효성 검사에 Fluent Validation을 사용할 수 있나요? 예, 유창한 유효성 검사는 하위 유효성 검사기를 사용하여 복잡한 개체 유효성 검사를 지원하므로 모델 내에서 중첩된 프로퍼티 및 컬렉션의 유효성을 검사할 수 있습니다. 유창한 유효성 검사에서 오류 메시지를 사용자 지정하려면 어떻게 해야 하나요? 유창한 유효성 검사의 사용자 지정 오류 메시지는 RuleFor로 지정된 각 유효성 검사 규칙에 대해 WithMessage 메서드를 사용하여 정의할 수 있습니다. PDF 생성 라이브러리에 대한 평가판이 있나요? 예, IronPDF는 개발자가 라이브러리의 기능을 테스트할 수 있는 무료 평가판을 제공하며, 개발자당 499달러부터 시작하는 라이선스 옵션을 사용할 수 있습니다. IronPDF는 .NET 10과 완벽하게 호환되나요? 예. IronPDF는 .NET 10과 완벽하게 호환되며 다양한 프로젝트 유형(콘솔, 웹, 데스크톱, Blazor 등)에서 Windows, Linux, macOS를 포함한 플랫폼을 지원합니다. 별도의 해결 방법 없이 최신 런타임으로 즉시 작동합니다. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다. 커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다. 관련 기사 업데이트됨 1월 22, 2026 How to Create PDF Documents in .NET with IronPDF: Complete Guide Discover effective methods to create PDF files in C# for developers. Enhance your coding skills and streamline your projects. Read the article now! 더 읽어보기 업데이트됨 1월 21, 2026 How to Merge PDF Files in VB.NET: Complete Tutorial Merge PDF VB NET with IronPDF. Learn to combine multiple PDF files into one document using simple VB.NET code. Step-by-step examples included. 더 읽어보기 업데이트됨 1월 21, 2026 C# PDFWriter Tutorial: Create PDF Documents in .NET Learn to create PDFs efficiently using C# PDFWriter with this step-by-step guide for developers. Read the article to enhance your skills today! 더 읽어보기 PDF vs PDFA (How It Works For Developers)How to Use ChatGPT with IronPDF For...
업데이트됨 1월 22, 2026 How to Create PDF Documents in .NET with IronPDF: Complete Guide Discover effective methods to create PDF files in C# for developers. Enhance your coding skills and streamline your projects. Read the article now! 더 읽어보기
업데이트됨 1월 21, 2026 How to Merge PDF Files in VB.NET: Complete Tutorial Merge PDF VB NET with IronPDF. Learn to combine multiple PDF files into one document using simple VB.NET code. Step-by-step examples included. 더 읽어보기
업데이트됨 1월 21, 2026 C# PDFWriter Tutorial: Create PDF Documents in .NET Learn to create PDFs efficiently using C# PDFWriter with this step-by-step guide for developers. Read the article to enhance your skills today! 더 읽어보기