C# ObservableCollection(對開發者來說是如何工作的)
在 C# 中, ObservableCollection是一種強大的資料結構,當項目被新增、刪除或變更時,會自動通知監聽器。 這對於動態資料收集情境特別有用,例如當您需要在 UI 或報表中反映即時變更時。 當與 IronPDF 結合時,這個功能強大的合集可用於根據即時資料產生動態 PDF。
IronPDF是一個強大的函式庫,可用於在 C# 中產生 PDF。 利用其 HTML-to-PDF 轉換功能,無論您需要根據即時資料產生發票、報告或任何其他文件,都能輕鬆建立高品質的 PDF。 在這篇文章中,我們將告訴您如何將 ObservableCollection 類與 IronPDF 整合,利用資料綁定來產生隨著資料變化而動態更新的 PDF。
瞭解 ObservableCollection
什麼是 ObservableCollection?
ObservableCollection是 C# 中的一個類,實作了 INotifyCollectionChanged 接口,該接口會在新增、刪除或修改項目時提供通知。 它通常用於 WPF 等 UI 應用程式中的資料綁定,其中集合的變更會自動觸發 UI 中的更新。 與其他集合(例如列表)不同ObservableCollection 提供內建事件通知,非常適合需要即時反映資料的場景。
ObservableCollection會自動處理整個集合的更改,使您輕鬆管理和展示應用程式中的動態資料集合。
常見使用案例
*與 UI 元件綁定:*例如,在 WPF 中,ObservableCollection 通常用於將資料綁定到 ListView、DataGrid 和 ComboBox 等控制項。 當底層集合改變時,UI 也會自動更新。 即時更新:**當資料頻繁變化時,ObservableCollection 可確保 UI 始終保持同步。 例如,您可以將其用於即時報告,在該報告中,新的資料項目被即時添加到集合中,報告也會相應更新。 *動態變化:如果您的應用程式允許使用者新增、刪除或修改數據,則可以使用 ObservableCollection 自動將這些變化反映在 UI 或其他元件中。
使用 IronPDF
IronPDF 的概述

正如我們在本文開頭提到的,IronPDF 適用於 .NET 是一個 .NET PDF 產生函式庫,可以輕鬆建立、修改和渲染 PDF 文件。 與其他一些 PDF 函式庫不同,IronPDF 提供豐富的功能,可簡化處理 PDF 的工作,例如將 HTML 轉換為 PDF、加入水印、處理現有的 PDF 等。
IronPDF 還允許開發人員從不同的資料來源(包括 HTML、圖片和純文字)渲染 PDF,這在您需要呈現動態資料時會特別有用。 使用 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 允許高度客製化,包括調整字型、邊框,甚至包含圖片,如 Logo 或 BarCode。
範例一:使用 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
在本案例中,Person 類別包含 Name 和 Age 等基本屬性。 我們將結合 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
}
}
這個 ObservableCollection 包含 Person 物件的集合,每個物件都有 Name 和 Age。 當新增或移除項目時,事件處理程式會被觸發,我們會使用這些處理程式來動態更新 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
添加新人
您可以新增一個 Person 到集合中,整個集合會觸發事件處理程式重新產生 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
})
每次您將新的人加入收藏,PDF 將重新生成,包括新的項目。
綁定年齡屬性
您也可以將 Person 的 age 屬性綁定到某些外部系統 (例如 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
透過綁定使用 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()
使用 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
範例二:從 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
步驟 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
}
}
第 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
步驟 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
步驟 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
})
完整程式碼範例
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
輸出

程式碼的功能
- 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 嗎? 立即下載 免費試用版,提升您的 C# PDF 專案,並請務必查看 廣泛的說明文件部分,以瞭解此函式庫的更多實作。
常見問題解答
什麼是C#中的ObservableCollection?
ObservableCollection
如何在C#中從動態資料中生成PDF?
使用 IronPDF,您可以通過利用 C# 的 ObservableCollection
使用ObservableCollection與PDF生成有哪些好處?
ObservableCollection
如何將ObservableCollection中的資料綁定到C#中的PDF?
可以通過遍歷集合項並使用IronPDF的方法將它們添加到PDF中作為結構化元素(如表或列表)來將ObservableCollection中的資料綁定到PDF。這確保了PDF內容始終與資料保持同步。
在C#中使用ObservableCollection生成PDF的常見案例是什麼?
一個常見的案例是從ObservableCollection的項目生成發票。隨著項目的添加或移除,PDF發票可以重新生成,以準確反映當前的項目列表,確保文檔的及時性。
IronPDF如何處理C#中的HTML到PDF轉換?
IronPDF可以使用諸如RenderHtmlAsPdf和RenderHtmlFileAsPdf等方法將HTML轉換為PDF。這使開發人員能夠從網頁或HTML字串創建PDF,方便動態內容渲染。
在使用大型ObservableCollections進行PDF生成時應考慮什麼?
在處理大型集合時,應考慮使用分頁、批量更新和優化佈局以防止性能問題。IronPDF的緩存和渲染優化也有助於有效管理大資料。
IronPDF如何提高.NET應用程式的生產力?
IronPDF通過提供強大的PDF創建功能提高生產力,如詳細的佈局自定義、HTML到PDF轉換和與各種資料源的集成。它簡化了複雜的PDF任務,使開發人員能夠專注於核心應用程式邏輯。



