How to Convert PDF to JPG in .NET
什麼是Fluent Validation?
FluentValidation 是一個 .NET 驗證程式庫,幫助建立強型別的驗證規則。 它使用流暢的介面和lambda表達式,使程式碼更易於閱讀和維護。 您可以使用Fluent Validation來為您的驗證邏輯建立一個單獨的類別,而不是在模型類別中使用資料註釋或手動驗證。
Fluent Validation為驗證帶來了更多的靈活性。 Fluent Validation是 .NET Core 工具包中的一個強大工具,具有內建的常見情境驗證器、自定義驗證的能力,以及簡單連接驗證規則的方法。
理解Fluent Validation
Fluent Validation是一個針對 .NET 的開源程式庫,可以輕鬆為您的模型類別建立驗證規則。
- 驗證器: 驗證器是封裝驗證邏輯的類別。 它們通常通過繼承
AbstractValidator<t>基底類別來建立。 - 規則: 規則是一個屬性必須滿足的驗證條件。 規則是在驗證器類別中使用
RuleFor方法來定義的。 - 驗證失敗: 如果規則失敗,Fluent Validation會建立一個包含錯誤詳細資訊的
ValidationFailure物件,包括屬性名稱和錯誤資訊。
什麼是IronPDF?
IronPDF - 在C#中將HTML轉換為PDF 是一個強大的 .NET 程式庫,允許您從HTML內容生成PDF文件。 無論您需要建立發票、報告或其他型別的文件,IronPDF都提供了一個易於使用的解決方案。 它與您的ASP.NET Core應用程式無縫整合,使您只需幾行程式碼即可生成高質量的PDF文件。
將Fluent Validation與IronPDF結合使用
現在我們了解了Fluent Validation和IronPDF,讓我們看看它們如何結合使用。 本教程將幫助您建立一個發票生成器,在生成PDF之前,將使用ASP.NET Core中的FluentValidation來驗證發票內容。
設置項目
首先,讓我們在Visual Studio或您首選的開發環境中建立一個新的控制台應用程式。
- 打開Visual Studio並到 檔案 > 新建 > 專案。
-
選擇 "Console App (ASP.NET Core)" 作為專案模板,並為您的專案提供一個名稱。
建立新控制台應用程式 -
點擊 下一步 並通過命名和選擇儲存庫位置來配置您的專案。
配置新應用程式 -
點擊 下一步 並選擇 .NET Framework。 推薦使用最新的 .NET Framework (7)。
選擇 .NET Framework - 點擊 建立 按鈕來建立專案。
安裝必要軟體包
一旦專案建立後,新增Fluent Validation和IronPDF所需的NuGet軟體包。
- 在方案總管中右鍵點擊專案,然後選擇 "管理 NuGet 軟體包"。
-
搜尋 "FluentValidation" 然後點擊 "安裝" 以將此包新增到您的專案中。
在NuGet包管理器介面中安裝FluentValidation包 - 同樣,搜尋 "IronPDF - 強大的 .NET PDF 程式庫" 並安裝IronPDF包。
或者,您可以在 NuGet包管理器控制台 中使用以下命令來安裝IronPDF:
Install-Package IronPdf
在包管理器控制台中安裝IronPDF包
隨著專案設置完畢和必要包安裝完畢,讓我們繼續定義PDF內容類。
定義PDF內容
在此例中,將從HTML程式碼中建立一個簡單的發票PDF,包含在兩個類別中: InvoiceContent 和 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; }
}
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
在上面的程式碼中,定義了一個抽象 PdfContent 類別,其包含一個名為 RenderHtml 的抽象方法。 InvoiceContent 類繼承了 PdfContent,代表發票PDF的內容。 它有使用者名、地址及發票項目列表的屬性。 InvoiceItem 類包含兩個屬性:'描述' 和 '價格'。 RenderHtml 方法根據內容生成發票的HTML標記。
既然定義了PDF內容,讓我們繼續使用Fluent Validation建立驗證規則。
建立驗證規則
為了為 InvoiceContent 類建立驗證規則,請建立名為 InvoiceContentValidator 的驗證器類。 此類將從 AbstractValidator<InvoiceContent> 繼承,這是由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.");
}
}
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
在源程式碼中,定義了 InvoiceContentValidator 類,它繼承自 AbstractValidator<InvoiceContent>。 在驗證器類的構造函式中,RuleFor 方法為 InvoiceContent 類的每個屬性定義驗證規則。
例如,RuleFor(content => content.CustomerName) 指定使用者名稱不應為空。 同樣,為地址和發票項目屬性定義驗證規則。
RuleForEach 方法遍歷 InvoiceItems 列表中的每個項目並應用 InvoiceItemValidator。 InvoiceItemValidator 類包含 InvoiceItem 類的驗證規則。
有了這些驗證規則,我們繼續使用IronPDF生成PDF。
使用IronPDF生成PDF
IronPDF - 生成和編輯PDF文件 是一個流行的 .NET 程式庫,用於建立和操作PDF文件。 將使用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)(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)(content As T) As IValidator(Of T)
If TypeOf content Is InvoiceContent Then
Return CType(New InvoiceContentValidator(), IValidator(Of T))
Else
Throw New NotSupportedException("Unsupported content type.")
End If
End Function
End Class
PdfService 類提供了一個 GeneratePdf 方法。 此方法以 PdfContent 物件為輸入,根據經過驗證的內容生成PDF文件。
首先,它通過調用 GetValidatorForContent 方法來檢索內容的適當驗證器,該方法檢查內容的型別並返回相應的驗證器。 在我們的情況中,我們支持 InvoiceContent 並使用 InvoiceContentValidator。
然後,通過調用其 Validate 方法,使用驗證器驗證內容。 驗證結果儲存在 ValidationResult 物件中。
如果驗證失敗(!validationResult.IsValid),將拋出含驗證錯誤的 FluentValidation.ValidationException。 否則,將使用IronPDF生成PDF。
建立了一個 ChromePdfRenderer 實例以將HTML內容渲染為PDF。 在 renderer 物件上調用 RenderHtmlAsPdf 方法,傳入 content.RenderHtml 方法生成的HTML,從而生成PDF文件。
現在我們已定義了PDF生成邏輯,讓我們處理可能發生的任何驗證錯誤。
處理驗證錯誤
當發生驗證錯誤時,我們希望顯示錯誤資訊並優雅地處理它。 讓我們修改 Main 類的 Program 方法以處理任何異常並向使用者顯示有意義的消息。
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
在上面的程式碼中,使用 try-catch 塊來捕獲可能發生的任何異常。 如果捕捉到異常,則將使用 Console.WriteLine 向使用者顯示錯誤資訊。
現在讓我們使用不同的情境來測試這個應用程式以驗證PDF生成和驗證規則。
測試應用程式
在程式碼範例中,有三種情境可測試:
- 空的使用者名稱:將使用者名稱留空以觸發驗證錯誤。
- 空的發票項目:提供一個空的發票項目列表以觸發驗證錯誤。
- 成功生成:提供有效的內容以成功生成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!
控制台中的輸出錯誤
輸出PDF文件
正如預期的那樣,前兩個情境顯示驗證錯誤,第三個情境顯示成功資訊。
總結
本教程探討了Fluent Validation以及如何將其與IronPDF結合使用來生成PDF文件。 從設置控制台應用程式和定義PDF內容類開始。 然後,使用Fluent Validation建立驗證規則,並在不同情境中測試PDF生成。
Fluent Validation提供了一種靈活且易於使用的方法來驗證 .NET 應用程式中的物件。 它允許您以強型別的方式定義驗證規則,自定義錯誤資訊,並優雅地處理驗證錯誤。
IronPDF Free Trial & Licensing Information 提供免費試用,許可證從 $499/每位開發者開始。
常見問題
如何將Fluent Validation與C#中的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,這可讓您將HTML字串或文件轉換為高品質的PDF。
教程中的PdfService類別的目的是什麼?
教程中的PdfService類別旨在通過首先使用Fluent Validation驗證內容來管理PDF生成。成功驗證後,它使用IronPDF的ChromePdfRenderer和RenderHtmlAsPdf方法來建立PDF。
如何使用Fluent Validation定義驗證規則?
Fluent Validation中的驗證規則是透過建立繼承自AbstractValidator的驗證器類別來定義的。在此類別中,使用RuleFor方法來指定每個屬性的條件,允許客製化錯誤訊息和規則連結。
如果在PDF生成過程中驗證失敗會發生什麼?
如果驗證失敗,Fluent Validation會拋出一個ValidationException,其中包含詳細的驗證錯誤訊息,可用於通知使用者出錯原因。
我可以使用Fluent Validation進行複雜的物件驗證嗎?
是的,Fluent Validation支援複雜的物件驗證,透過使用子驗證器允許您驗證模型中的巢狀屬性和集合。
如何在Fluent Validation中自訂錯誤訊息?
在Fluent Validation中,可以使用WithMessage方法為指定的RuleFor驗證規則定義自訂錯誤訊息。
PDF生成程式庫提供試用版本嗎?
有的,IronPDF提供免費試用版供開發者測試程式庫的功能,並有授權選項,每位開發者起價為$499。
IronPDF 是否完全相容 .NET 10?
是的,IronPDF完全相容於.NET 10,並支援包括Windows、Linux、macOS在內的多種專案型別(控制台、網頁、桌面、Blazor等)。它無需任何變通措施即可與最新運行時開箱即用。

