跳至页脚内容
.NET 帮助

C# ObservableCollection(开发者用法)

在 C# 中,ObservableCollection 是一种强大的数据结构,可以在项目添加、删除或更改时自动通知监听者。 它对动态数据收集场景特别有用,例如当需要在用户界面或报告中反映实时变化时。 与 IronPDF 相结合时,这个强大的集合可以用于基于实时数据生成动态 PDF。

IronPDF 是一个在 C# 中生成 PDF 的强大库。 通过其HTML 到 PDF 的转换能力,无论是生成发票、报告,还是基于实时数据的其他文档,创建高质量的 PDF 都很简单。 在本文中,我们将向您展示如何将 ObservableCollection 类与 IronPDF 集成,利用数据绑定来生成一个随着数据变化而动态更新的 PDF。

理解 ObservableCollection

ObservableCollection 是什么?

ObservableCollection 是 C# 中的一个类,实现了 INotifyCollectionChanged 接口,当项目被添加、删除或修改时提供通知。 它通常用于 UI 应用程序中的数据绑定,如 WPF,在集合发生变化时自动触发 UI 更新。 与 List 等其他集合不同,ObservableCollection 提供了内置的事件通知,非常适合需要实时反映数据的场景。

ObservableCollection 自动处理整个集合的更改,使您能够轻松管理和显示应用程序中的动态数据集合。

常见用例

  • 与UI组件绑定:例如,在 WPF 中,ObservableCollection 经常用于将数据绑定到 ListView、DataGrid 和 ComboBox 等控件。 当底层集合发生变化时,UI 会自动更新。
  • 实时更新:当数据经常变化时,ObservableCollection 确保 UI 始终保持同步。 例如,您可以将其用于实时报告,其中新数据条目实时添加到集合中,报告相应地更新。
  • 动态变化:如果您的应用程序允许用户添加、删除或修改数据,可以使用 ObservableCollection 自动反映这些变化到 UI 或其他组件中。

使用 IronPDF 工作

IronPDF 概述

C# ObservableCollection(它如何为开发者服务):图 1

如我们在本文开头提到的,IronPDF 是一个 .NET PDF 生成库,它便于创建、修改和渲染 PDF 文档。 与某些其他 PDF 库不同,IronPDF 提供了丰富的功能集,简化了 PDF 的操作,如将 HTML 转换为 PDF、添加水印、操作现有的 PDF 等。

IronPDF 还允许开发人员从不同的数据源渲染 PDF,包括 HTML、图像和纯文本,这在需要呈现动态数据时特别有用。 使用 IronPDF 的 API,您可以生成高质量的 PDF,包括详细布局、表格、图像和样式。

IronPDF 设置

要开始使用 IronPDF,您需要通过 NuGet 安装该库。 您可以通过在包管理器控制台中运行以下命令将其添加到项目中:

Install-Package IronPdf

安装完成后,您可以初始化 IronPDF 并使用其强大功能。 在本文中,我们将专注于从 ObservableCollection 中的动态数据生成 PDF。

将 ObservableCollection 与 IronPDF 集成

用例:从 ObservableCollection 动态生成 PDF

让我们想象一个场景,您需要从存储在 ObservableCollection 中的项目列表生成发票 PDF。 当项目添加或从集合中删除时,PDF 应该自动重新生成以反映数据的当前状态。

对于这项任务,ObservableCollection 提供了管理发票项目的简便方法,而 IronPDF 将允许我们生成并导出发票至 PDF 格式。

将数据绑定到 PDF 内容中

要将 ObservableCollection 中的数据绑定到 PDF,您需要循环遍历集合并将其项目添加到 PDF 内容中。 IronPDF 提供了创建表格、添加文本和自定义布局的方法,可以轻松地以结构化格式表示数据。

例如,如果您有一张包含多个项目的发票,您可以通过循环遍历 ObservableCollection 并将每个项目添加到文档中的表格或列表中来动态生成 PDF。 IronPDF 允许高度的自定义,包括调整字体、边框,甚至包含类似标志或条形码的图像。

示例一:使用 ObservableCollection 生成 PDF

让我们看一个简单的例子来演示这是如何工作的。 假设您有一个 (由 Person 类表示的) 人员集合,并且您希望生成一个反映这些人员详细信息的 PDF。 每次向集合中添加新人员时,PDF 将自动更新。

人员类示例

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Public Class Person
	Public Property Name() As String
	Public Property Age() As Integer
End Class
$vbLabelText   $csharpLabel

在本例中,Person 类包含基本属性如名称和年龄。 我们将使用此类与 ObservableCollection 一起动态生成 PDF。

创建 ObservableCollection

using System.Collections.ObjectModel;

var collection = new ObservableCollection<Person>
{
    new Person { Name = "John Doe", Age = 30 },
    new Person { Name = "Jane Smith", Age = 28 }
};
using System.Collections.ObjectModel;

var collection = new ObservableCollection<Person>
{
    new Person { Name = "John Doe", Age = 30 },
    new Person { Name = "Jane Smith", Age = 28 }
};
Imports System.Collections.ObjectModel

Private collection = New ObservableCollection(Of Person) From {
	New Person With {
		.Name = "John Doe",
		.Age = 30
	},
	New Person With {
		.Name = "Jane Smith",
		.Age = 28
	}
}
$vbLabelText   $csharpLabel

这个ObservableCollection 包含一系列 Person 对象,每个对象都有姓名和年龄。 当项目被添加或删除时,将触发事件处理程序,我们将使用它来动态更新 PDF。

为集合更改添加事件处理程序

在此示例中,我们订阅了 ObservableCollection 类 的 CollectionChanged 事件,以便每当集合更改时自动重生成 PDF。 这非常有用,如果需要响应诸如添加或删除 Person 对象等更改。

// Subscribe to the ObservableCollection's CollectionChanged event
collection.CollectionChanged += (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) =>
{
    // Regenerate the PDF whenever the collection changes
    GeneratePersonPDF(collection);
};
// Subscribe to the ObservableCollection's CollectionChanged event
collection.CollectionChanged += (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) =>
{
    // Regenerate the PDF whenever the collection changes
    GeneratePersonPDF(collection);
};
' Subscribe to the ObservableCollection's CollectionChanged event
AddHandler collection.CollectionChanged, Sub(sender As Object, e As System.Collections.Specialized.NotifyCollectionChangedEventArgs)
	' Regenerate the PDF whenever the collection changes
	GeneratePersonPDF(collection)
End Sub
$vbLabelText   $csharpLabel

将新人员添加到集合中

您可以向集合中添加新人员,整个集合 将触发事件处理程序以重新生成 PDF。 此方法会自动处理对 整个名单 的人员的更改。

// Adding a new person to the collection
collection.Add(new Person { Name = "Alice Brown", Age = 32 });
// Adding a new person to the collection
collection.Add(new Person { Name = "Alice Brown", Age = 32 });
' Adding a new person to the collection
collection.Add(New Person With {
	.Name = "Alice Brown",
	.Age = 32
})
$vbLabelText   $csharpLabel

每次您向集合中添加新人员时,PDF 将重新生成,包括新条目。

绑定年龄属性

您还可以将 Person 的年龄属性绑定到某些外部系统(例如 UI 或应用程序的其他部分)以自动反映更改。

以下是如何在Person 类中绑定 Age 属性的示例:

public class Person
{
    public string Name { get; set; }
    private int _age;
    public int Age 
    {
        get { return _age; }
        set
        {
            _age = value;
            // Raise property changed event here if using data binding
        }
    }
}
public class Person
{
    public string Name { get; set; }
    private int _age;
    public int Age 
    {
        get { return _age; }
        set
        {
            _age = value;
            // Raise property changed event here if using data binding
        }
    }
}
Public Class Person
	Public Property Name() As String
	Private _age As Integer
	Public Property Age() As Integer
		Get
			Return _age
		End Get
		Set(ByVal value As Integer)
			_age = value
			' Raise property changed event here if using data binding
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

使用 ObservableCollection 进行绑定

让我们演示使用绑定年龄到 UI 元素,更新年龄值并观察在集合中反映的变化:

ObservableCollection<Person> people = new ObservableCollection<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 28 }
};
// Binding the Age of the first person to a UI element (pseudo-code)
someUIElement.Text = people[0].Age.ToString();
ObservableCollection<Person> people = new ObservableCollection<Person>
{
    new Person { Name = "John", Age = 30 },
    new Person { Name = "Jane", Age = 28 }
};
// Binding the Age of the first person to a UI element (pseudo-code)
someUIElement.Text = people[0].Age.ToString();
Dim people As New ObservableCollection(Of Person) From {
	New Person With {
		.Name = "John",
		.Age = 30
	},
	New Person With {
		.Name = "Jane",
		.Age = 28
	}
}
' Binding the Age of the first person to a UI element (pseudo-code)
someUIElement.Text = people(0).Age.ToString()
$vbLabelText   $csharpLabel

使用 IronPDF 生成 PDF

现在我们已经设置了 ObservableCollection 并添加了事件处理程序,是时候专注于生成反映动态人物集合的 PDF。

using IronPdf;

public void GeneratePersonPDF(ObservableCollection<Person> people)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer class
    // Create HTML content representing the people in the collection
    var htmlContent = "<h1>People Information</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                      "<tr><th>Name</th><th>Age</th></tr>";
    foreach (var person in people)
    {
        htmlContent += $"<tr><td>{person.Name}</td><td>{person.Age}</td></tr>";
    }

    htmlContent += "</table>";
    // Convert the HTML content to a PDF
    var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
    // Save the generated PDF to disk
    pdfDocument.SaveAs("PeopleInformation.pdf");
}
using IronPdf;

public void GeneratePersonPDF(ObservableCollection<Person> people)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer class
    // Create HTML content representing the people in the collection
    var htmlContent = "<h1>People Information</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                      "<tr><th>Name</th><th>Age</th></tr>";
    foreach (var person in people)
    {
        htmlContent += $"<tr><td>{person.Name}</td><td>{person.Age}</td></tr>";
    }

    htmlContent += "</table>";
    // Convert the HTML content to a PDF
    var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
    // Save the generated PDF to disk
    pdfDocument.SaveAs("PeopleInformation.pdf");
}
Imports IronPdf

Public Sub GeneratePersonPDF(ByVal people As ObservableCollection(Of Person))
	Dim pdf = New ChromePdfRenderer() ' Initialize IronPDF's ChromePdfRenderer class
	' Create HTML content representing the people in the collection
	Dim htmlContent = "<h1>People Information</h1><table border='1' cellpadding='5' cellspacing='0'>" & "<tr><th>Name</th><th>Age</th></tr>"
	For Each person In people
		htmlContent &= $"<tr><td>{person.Name}</td><td>{person.Age}</td></tr>"
	Next person

	htmlContent &= "</table>"
	' Convert the HTML content to a PDF
	Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)
	' Save the generated PDF to disk
	pdfDocument.SaveAs("PeopleInformation.pdf")
End Sub
$vbLabelText   $csharpLabel

示例二:从 ObservableCollection 生成 PDF 发票

下面是如何使用 IronPDF 从 ObservableCollection 发票项目生成 PDF 的示例:

步骤 1:示例发票项目类

此类代表发票中的一个项目,具有项目名称、数量、价格和总价属性。

public class InvoiceItem
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public decimal Total => Quantity * Price;
}
public class InvoiceItem
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    public decimal Total => Quantity * Price;
}
Public Class InvoiceItem
	Public Property ItemName() As String
	Public Property Quantity() As Integer
	Public Property Price() As Decimal
	Public ReadOnly Property Total() As Decimal
		Get
			Return Quantity * Price
		End Get
	End Property
End Class
$vbLabelText   $csharpLabel

步骤 2:示例 ObservableCollection

此示例初始化了一个 ObservableCollection,其中包含几个发票项目。 您可以在此集合中动态添加、删除或修改项目。

ObservableCollection<InvoiceItem> invoiceItems = new ObservableCollection<InvoiceItem>
{
    new InvoiceItem { ItemName = "Item 1", Quantity = 2, Price = 10.00m },
    new InvoiceItem { ItemName = "Item 2", Quantity = 1, Price = 25.00m },
    new InvoiceItem { ItemName = "Item 3", Quantity = 5, Price = 5.00m }
};
ObservableCollection<InvoiceItem> invoiceItems = new ObservableCollection<InvoiceItem>
{
    new InvoiceItem { ItemName = "Item 1", Quantity = 2, Price = 10.00m },
    new InvoiceItem { ItemName = "Item 2", Quantity = 1, Price = 25.00m },
    new InvoiceItem { ItemName = "Item 3", Quantity = 5, Price = 5.00m }
};
Dim invoiceItems As New ObservableCollection(Of InvoiceItem) From {
	New InvoiceItem With {
		.ItemName = "Item 1",
		.Quantity = 2,
		.Price = 10.00D
	},
	New InvoiceItem With {
		.ItemName = "Item 2",
		.Quantity = 1,
		.Price = 25.00D
	},
	New InvoiceItem With {
		.ItemName = "Item 3",
		.Quantity = 5,
		.Price = 5.00D
	}
}
$vbLabelText   $csharpLabel

步骤 3:使用 IronPDF 生成 PDF

这里,我们创建了一个生成 PDF 的函数。 这个函数使用 ObservableCollection 中的数据并将其转换为 HTML,然后使用 IronPDF 将其渲染为 PDF。

public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer class
    // Create HTML content representing the invoice
    var htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                      "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";
    foreach (var item in items)
    {
        htmlContent += $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>";
    }
    htmlContent += "</table>";
    // Convert the HTML content to a PDF
    var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
    // Save the generated PDF to disk
    pdfDocument.SaveAs("Invoice.pdf");
}
public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
{
    var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer class
    // Create HTML content representing the invoice
    var htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                      "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";
    foreach (var item in items)
    {
        htmlContent += $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>";
    }
    htmlContent += "</table>";
    // Convert the HTML content to a PDF
    var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
    // Save the generated PDF to disk
    pdfDocument.SaveAs("Invoice.pdf");
}
Public Sub GenerateInvoicePDF(ByVal items As ObservableCollection(Of InvoiceItem))
	Dim pdf = New ChromePdfRenderer() ' Initialize IronPDF's ChromePdfRenderer class
	' Create HTML content representing the invoice
	Dim htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" & "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>"
	For Each item In items
		htmlContent &= $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>"
	Next item
	htmlContent &= "</table>"
	' Convert the HTML content to a PDF
	Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)
	' Save the generated PDF to disk
	pdfDocument.SaveAs("Invoice.pdf")
End Sub
$vbLabelText   $csharpLabel

步骤 4:订阅 CollectionChanged 事件

因为 ObservableCollection 自动通知更改,您可以在集合更新时轻松地重新生成 PDF。 例如,如果添加或删除项目,PDF 可以使用更新的数据重新生成。

下面是如何订阅 CollectionChanged 事件并在集合更改时重新生成 PDF 的方法:

// Subscribe to the ObservableCollection's CollectionChanged event
invoiceItems.CollectionChanged += (sender, e) =>
{
    // Regenerate the PDF whenever the collection changes
    GenerateInvoicePDF(invoiceItems);
};
// Subscribe to the ObservableCollection's CollectionChanged event
invoiceItems.CollectionChanged += (sender, e) =>
{
    // Regenerate the PDF whenever the collection changes
    GenerateInvoicePDF(invoiceItems);
};
' Subscribe to the ObservableCollection's CollectionChanged event
AddHandler invoiceItems.CollectionChanged, Sub(sender, e)
	' Regenerate the PDF whenever the collection changes
	GenerateInvoicePDF(invoiceItems)
End Sub
$vbLabelText   $csharpLabel

步骤 5:添加项目和测试

您现在可以通过向 ObservableCollection 添加新项目进行测试,并观察 PDF 如何自动重新生成。

// Adding a new item to the ObservableCollection
invoiceItems.Add(new InvoiceItem { ItemName = "Item 4", Quantity = 3, Price = 12.50m });
// Adding a new item to the ObservableCollection
invoiceItems.Add(new InvoiceItem { ItemName = "Item 4", Quantity = 3, Price = 12.50m });
' Adding a new item to the ObservableCollection
invoiceItems.Add(New InvoiceItem With {
	.ItemName = "Item 4",
	.Quantity = 3,
	.Price = 12.50D
})
$vbLabelText   $csharpLabel

完整代码示例

using System;
using System.Collections.ObjectModel;
using IronPdf;

public class InvoiceItem
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    // Property to calculate the total price for each item
    public decimal Total => Quantity * Price;
}
public class InvoiceGenerator
{
    // Function to generate the invoice PDF
    public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
    {
        var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer class
        // Create HTML content representing the invoice
        var htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                          "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";
        foreach (var item in items)
        {
            htmlContent += $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>";
        }
        htmlContent += "</table>";
        // Convert the HTML content to a PDF
        var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
        // Save the generated PDF to disk
        pdfDocument.SaveAs("Invoice.pdf");
    }

    // Main function to test the code
    public static void Main(string[] args)
    {
        var invoiceItems = new ObservableCollection<InvoiceItem>
        {
            new InvoiceItem { ItemName = "Item 1", Quantity = 2, Price = 10.00m },
            new InvoiceItem { ItemName = "Item 2", Quantity = 1, Price = 25.00m },
            new InvoiceItem { ItemName = "Item 3", Quantity = 5, Price = 5.00m }
        };

        var invoiceGenerator = new InvoiceGenerator();

        // Subscribe to the ObservableCollection's CollectionChanged event
        invoiceItems.CollectionChanged += (sender, e) =>
        {
            // Regenerate the PDF whenever the collection changes
            invoiceGenerator.GenerateInvoicePDF(invoiceItems);
        };

        // Generate initial PDF
        invoiceGenerator.GenerateInvoicePDF(invoiceItems);

        // Add a new item to the collection and automatically regenerate the PDF
        invoiceItems.Add(new InvoiceItem { ItemName = "Item 4", Quantity = 3, Price = 12.50m });

        // Remove an item and see the PDF update
        invoiceItems.RemoveAt(0);
    }
}
using System;
using System.Collections.ObjectModel;
using IronPdf;

public class InvoiceItem
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    // Property to calculate the total price for each item
    public decimal Total => Quantity * Price;
}
public class InvoiceGenerator
{
    // Function to generate the invoice PDF
    public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
    {
        var pdf = new ChromePdfRenderer();  // Initialize IronPDF's ChromePdfRenderer class
        // Create HTML content representing the invoice
        var htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" +
                          "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>";
        foreach (var item in items)
        {
            htmlContent += $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>";
        }
        htmlContent += "</table>";
        // Convert the HTML content to a PDF
        var pdfDocument = pdf.RenderHtmlAsPdf(htmlContent);
        // Save the generated PDF to disk
        pdfDocument.SaveAs("Invoice.pdf");
    }

    // Main function to test the code
    public static void Main(string[] args)
    {
        var invoiceItems = new ObservableCollection<InvoiceItem>
        {
            new InvoiceItem { ItemName = "Item 1", Quantity = 2, Price = 10.00m },
            new InvoiceItem { ItemName = "Item 2", Quantity = 1, Price = 25.00m },
            new InvoiceItem { ItemName = "Item 3", Quantity = 5, Price = 5.00m }
        };

        var invoiceGenerator = new InvoiceGenerator();

        // Subscribe to the ObservableCollection's CollectionChanged event
        invoiceItems.CollectionChanged += (sender, e) =>
        {
            // Regenerate the PDF whenever the collection changes
            invoiceGenerator.GenerateInvoicePDF(invoiceItems);
        };

        // Generate initial PDF
        invoiceGenerator.GenerateInvoicePDF(invoiceItems);

        // Add a new item to the collection and automatically regenerate the PDF
        invoiceItems.Add(new InvoiceItem { ItemName = "Item 4", Quantity = 3, Price = 12.50m });

        // Remove an item and see the PDF update
        invoiceItems.RemoveAt(0);
    }
}
Imports System
Imports System.Collections.ObjectModel
Imports IronPdf

Public Class InvoiceItem
	Public Property ItemName() As String
	Public Property Quantity() As Integer
	Public Property Price() As Decimal
	' Property to calculate the total price for each item
	Public ReadOnly Property Total() As Decimal
		Get
			Return Quantity * Price
		End Get
	End Property
End Class
Public Class InvoiceGenerator
	' Function to generate the invoice PDF
	Public Sub GenerateInvoicePDF(ByVal items As ObservableCollection(Of InvoiceItem))
		Dim pdf = New ChromePdfRenderer() ' Initialize IronPDF's ChromePdfRenderer class
		' Create HTML content representing the invoice
		Dim htmlContent = "<h1>Invoice</h1><table border='1' cellpadding='5' cellspacing='0'>" & "<tr><th>Item</th><th>Quantity</th><th>Price</th><th>Total</th></tr>"
		For Each item In items
			htmlContent &= $"<tr><td>{item.ItemName}</td><td>{item.Quantity}</td><td>{item.Price:C}</td><td>{item.Total:C}</td></tr>"
		Next item
		htmlContent &= "</table>"
		' Convert the HTML content to a PDF
		Dim pdfDocument = pdf.RenderHtmlAsPdf(htmlContent)
		' Save the generated PDF to disk
		pdfDocument.SaveAs("Invoice.pdf")
	End Sub

	' Main function to test the code
	Public Shared Sub Main(ByVal args() As String)
		Dim invoiceItems = New ObservableCollection(Of InvoiceItem) From {
			New InvoiceItem With {
				.ItemName = "Item 1",
				.Quantity = 2,
				.Price = 10.00D
			},
			New InvoiceItem With {
				.ItemName = "Item 2",
				.Quantity = 1,
				.Price = 25.00D
			},
			New InvoiceItem With {
				.ItemName = "Item 3",
				.Quantity = 5,
				.Price = 5.00D
			}
		}

'INSTANT VB NOTE: The variable invoiceGenerator was renamed since it may cause conflicts with calls to static members of the user-defined type with this name:
		Dim invoiceGenerator_Conflict As New InvoiceGenerator()

		' Subscribe to the ObservableCollection's CollectionChanged event
		AddHandler invoiceItems.CollectionChanged, Sub(sender, e)
			' Regenerate the PDF whenever the collection changes
			invoiceGenerator_Conflict.GenerateInvoicePDF(invoiceItems)
		End Sub

		' Generate initial PDF
		invoiceGenerator_Conflict.GenerateInvoicePDF(invoiceItems)

		' Add a new item to the collection and automatically regenerate the PDF
		invoiceItems.Add(New InvoiceItem With {
			.ItemName = "Item 4",
			.Quantity = 3,
			.Price = 12.50D
		})

		' Remove an item and see the PDF update
		invoiceItems.RemoveAt(0)
	End Sub
End Class
$vbLabelText   $csharpLabel

输出

C# ObservableCollection(它如何为开发者服务):图 2 - 输出PDF文件

代码作用

  • InvoiceItem 类:代表具有 ItemName、Quantity、Price 属性和计算 Total 的发票项目。
  • ObservableCollection:用于存储发票项目列表。 这个集合会自动通知监听者的任何更改(例如,添加或删除项目时)。
  • GenerateInvoicePDF:此方法创建代表发票的 HTML 内容并使用 IronPDF 将其转换为 PDF。
  • CollectionChanged:处理 ObservableCollection 事件以在集合更改时重新生成 PDF,使 PDF 生成动态化。
  • 测试:Main 方法演示了如何通过添加和删除 ObservableCollection 中的项目触发 PDF 重新生成。

性能考虑

处理大型集合

在处理大型 ObservableCollection 实例时,性能可能会成为问题。 如果有大量项目,每次集合更改时重新生成 PDF 可能会消耗大量资源。 为了减轻这种情况,请考虑分批更新或使用分页等技术,以避免 PDF 生成过程过载。

高效的 PDF 渲染

为了确保 PDF 渲染的效率,请注意以下提示:

  • 减少不必要的重新渲染:仅在数据发生重大变化时(例如,添加或删除项目时)重新生成 PDF。
  • 优化表格布局:当渲染大量数据集时,最好将它们分为更小、更易管理的部分,以提高渲染时间。
  • 使用缓存:缓存先前生成的 PDF 用于静态或不经常变化的数据。

结论

通过将 C# 的 ObservableCollection 与 IronPDF 结合使用,您可以轻松生成反映应用程序数据实时变化的动态 PDF。 无论您是在生成发票、报告还是其他文档,此方法都允许您在底层集合更改时自动更新 PDF 内容。

ObservableCollection 的集成确保您的应用程序始终保持最新状态,并且只需最少的努力,而 IronPDF 则负责渲染高质量 PDF 的艰苦工作。 通过遵循本文中讨论的最佳实践和性能提示,您可以为 .NET 应用程序创建无缝的 PDF 生成体验。

想要亲自试用 IronPDF 吗? Download the free trial today to elevate your C# PDF projects, and be sure to check out the extensive documentation section to see more of this library in action.

常见问题解答

什么是 C# 中的 ObservableCollection?

ObservableCollection 是 C# 中的一个类,实现了 INotifyCollectionChanged 接口。它提供了添加、移除或修改项目时的通知,非常适合需要实时更新的 UI 应用程序中的数据绑定。

如何用 C# 从动态数据生成 PDF?

使用 IronPDF,您可以通过利用 C# 的 ObservableCollection 从动态数据生成 PDF。当集合更新时,您可以自动重新生成 PDF 以反映当前数据状态。

使用 ObservableCollection 生成 PDF 有什么好处?

ObservableCollection 允许实时数据跟踪,这在需要反映实时数据更改的 PDF 生成中非常有利。与 IronPDF 结合使用,它确保数据中的任何更新都能及时反映在 PDF 输出中。

如何在 C# 中将数据从 ObservableCollection 绑定到 PDF?

您可以通过遍历集合项并使用 IronPDF 的方法将其作为结构化元素(如表格或列表)添加到 PDF 中来绑定 ObservableCollection 的数据到 PDF。这确保了 PDF 内容始终与数据同步。

在 C# 中使用 ObservableCollection 生成 PDF 的常见用例是什么?

一个常见用例是从一个项目的 ObservableCollection 生成发票。当项目被添加或从集合中移除时,PDF 发票可以重新生成以准确反映当前项目列表,确保文档的最新性。

IronPDF 如何在 C# 中处理 HTML 到 PDF 的转换?

IronPDF 可以使用 RenderHtmlAsPdfRenderHtmlFileAsPdf 等方法将 HTML 转换为 PDF。这允许开发人员从网页或 HTML 字符串创建 PDF,从而实现动态内容呈现。

在使用大型 ObservableCollection 进行 PDF 生成时应考虑什么?

处理大型集合时,请考虑使用分页、分批更新和优化布局以防止性能问题。IronPDF 的缓存和渲染优化也有助于高效管理大量数据。

IronPDF 如何在 .NET 应用程序中提升生产力?

IronPDF 通过提供用于 PDF 创建的强大功能来提高生产力,例如详细的布局自定义、HTML 到 PDF 的转换以及与各种数据源的集成。它简化了复杂的 PDF 任务,使开发人员能够专注于核心应用程序逻辑。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。