透かしなしで本番環境でテストしてください。
必要な場所で動作します。
30日間、完全に機能する製品をご利用いただけます。
数分で稼働させることができます。
製品トライアル期間中にサポートエンジニアリングチームへの完全アクセス
C#では、ObservableCollection
IronPDF は、C#でPDFを生成するための強力なライブラリです。 そのHTML-to-PDF変換機能により、請求書、レポート、またはリアルタイムデータに基づくその他のドキュメントを生成する必要がある場合でも、高品質のPDFを簡単に作成できます。 この記事では、データバインディングを活用して、データの変化に応じて動的に更新されるPDFを生成するために、ObservableCollectionクラスをIronPDFと統合する方法を紹介します。
ObservableCollection
ObservableCollection はコレクション全体への変更を自動的に処理し、アプリケーションで動的なデータコレクションを管理および表示することを容易にします。
Pixabay から追加アップロード
またはここに画像をドラッグアンドドロップします
画像の代替テキストを追加
この記事の冒頭で述べたように、IronPDFはPDFドキュメントの作成、修正、およびレンダリングを容易にする.NET PDF生成ライブラリです。 他のいくつかのPDFライブラリとは異なり、IronPDFは、HTMLをPDFに変換する、ウォーターマークを追加する、既存のPDFを操作するなど、PDFを扱う作業を簡素化する豊富な機能を提供します。
IronPDFは、HTML、画像、プレーンテキストなどのさまざまなデータソースからPDFをレンダリングすることもでき、特に動的データを提示する必要がある場合に役立ちます。 IronPDFのAPIを使用すると、高品質なPDFを生成でき、詳細なレイアウト、テーブル、画像、スタイルを含めることができます。
IronPDFを始めるには、NuGetを通じてライブラリをインストールする必要があります。 パッケージ マネージャー コンソールで次のコマンドを実行して、プロジェクトに追加できます:
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
インストール後、IronPDF を初期化して、その強力な機能を使用できます。 この記事では、ObservableCollectionの動的データからPDFを生成することに焦点を当てます。
リストに格納された項目から請求書PDFを生成する必要があるシナリオを想像してみましょう。 コレクションにアイテムが追加または削除されると、データの現在の状態を反映するためにPDFが自動的に再生成される必要があります。
このタスクでは、ObservableCollectionは請求書の項目を管理する簡単な方法を提供し、IronPDFは請求書をPDF形式で生成およびエクスポートすることを可能にします。
ObservableCollectionのデータをPDFにバインドするには、コレクションをループしてそのアイテムをPDFコンテンツに追加する必要があります。 IronPDFは、データを構造化された形式で表現するために、テーブルを作成する方法、テキストを追加する方法、レイアウトをカスタマイズする方法を提供します。
たとえば、複数の項目を含む請求書がある場合、ObservableCollection をループして各項目をドキュメント内のテーブルやリストに追加することで、PDF を動的に生成できます。 IronPDFは、フォントや枠線の調整、さらにはロゴやバーコードなどの画像の挿入を含め、高度なカスタマイズが可能です。
これがどのように機能するかを示すために、簡単な例を見てみましょう。 人々のコレクション(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を生成します。
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オブジェクトのコレクションが含まれています。 アイテムが追加または削除されると、イベントハンドラーがトリガーされ、それを使用してPDFを動的に更新します。
この例では、コレクションが変更されるたびにPDFを自動的に再生成するために、ObservableCollectionクラスのCollectionChangedイベントを購読します。 これは、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が再生成され、新しいエントリが含まれます。
また、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
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()
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
以下は、IronPDFを使用してObservableCollectionの請求書項目からPDFを生成する方法の例です。
このクラスは請求書の項目を表し、項目名、数量、価格、合計価格のプロパティを持っています。
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
この例では、いくつかの請求書アイテムを含む 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
}
}
ここでは、PDFを生成するための関数を作成します。 この関数はObservableCollection内のデータを使用し、それをHTMLに変換します。そして、そのHTMLをIronPDFを使用してPDFとしてレンダリングします。
public void GenerateInvoicePDF(ObservableCollection<InvoiceItem> items)
{
var pdf = new ChromePdfRenderer(); // Initialize IronPDF's HtmlToPdf 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 HtmlToPdf 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 HtmlToPdf 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
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
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 HtmlToPdf 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 HtmlToPdf 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);
}
}
CONVERTER NOT RUNNING
出力
Pixabay から追加アップロード
またはここに画像をドラッグアンドドロップします
代替テキストをクリア
大規模なObservableCollectionインスタンスを扱う場合、パフォーマンスが問題になることがあります。 コレクションが変更されるたびにPDFを再生成することは、多くのアイテムがある場合、リソース集約型になる可能性があります。 これを軽減するために、更新をバッチ処理したり、ページネーションのような手法を使用してPDF生成プロセスの過負荷を避けることを検討してください。
PDFのレンダリングを効率的に行うために、次のヒントを心に留めておいてください。
C# の ObservableCollection と IronPDF を組み合わせることで、アプリケーションのデータにおけるリアルタイムの変更を反映した動的な PDF を簡単に生成できます。 請求書、レポート、その他のドキュメントを生成する場合でも、このアプローチを使用すると、基になるコレクションが変更されるたびにPDFコンテンツを自動的に更新できます。
ObservableCollectionの統合により、アプリケーションは最小限の労力で常に最新の状態に保たれ、IronPDFが高品質なPDFのレンダリングを手間なく処理します。 この記事で説明されているベストプラクティスとパフォーマンスのヒントに従うことで、.NETアプリケーション向けにシームレスなPDF生成体験を作成できます。
IronPDFを試してみたいですか? 豊富なドキュメントセクションも必ず確認してください。