푸터 콘텐츠로 바로가기
.NET 도움말

C# ObservableCollection (개발자를 위한 동작 방식)

C#에서, ObservableCollection은 항목이 추가, 제거 또는 변경될 때 자동으로 리스너에게 알리는 강력한 데이터 구조입니다. 이는 UI 또는 보고서에서 실시간 변경 사항을 반영해야 할 때와 같은 동적 데이터 수집 시나리오에 특히 유용합니다. IronPDF와 함께 사용할 때 이 강력한 컬렉션을 활용하여 실시간 데이터를 기반으로 동적 PDF를 생성할 수 있습니다.

IronPDF는 C#에서 PDF를 생성할 수 있는 강력한 라이브러리입니다. HTML을 PDF로 변환하는 기능을 통해 송장, 보고서 또는 다른 문서를 실시간 데이터를 기반으로 쉽게 생성할 수 있습니다. 이 기사에서는 ObservableCollection 클래스를 IronPDF와 통합하여 데이터 바인딩을 활용하여 데이터가 변경될 때 동적으로 업데이트되는 PDF를 생성하는 방법을 보여드리겠습니다.

ObservableCollection 이해하기

ObservableCollection이란 무엇인가?

ObservableCollection은 C#의 클래스이며, 항목이 추가, 제거 또는 수정될 때 알림을 제공하는 INotifyCollectionChanged 인터페이스를 구현합니다. 이는 WPF와 같은 UI 응용 프로그램에서 데이터 바인딩에 일반적으로 사용되며, 컬렉션의 변경 사항이 UI의 업데이트를 자동으로 촉발합니다. List와 같은 다른 컬렉션과 달리, ObservableCollection은 내장된 이벤트 알림을 제공하여 데이터가 실시간으로 반영되어야 하는 시나리오에 완벽합니다.

ObservableCollection은 컬렉션 전체의 변경 사항을 자동으로 처리하여 응용 프로그램에서 동적 데이터 컬렉션을 관리하고 표시하는 것을 용이하게 합니다.

일반 사용 사례

  • UI 구성 요소와의 바인딩: 예를 들어, WPF에서는 ListView, DataGrid 및 ComboBox와 같은 컨트롤에 데이터를 바인딩하는 데 ObservableCollection이 자주 사용됩니다. 기본 컬렉션이 변경되면 UI가 자동으로 업데이트됩니다.
  • 실시간 업데이트: 데이터가 자주 변경될 때, ObservableCollection은 UI가 항상 동기화되도록 보장합니다. 예를 들어 새로운 데이터 항목이 실시간으로 컬렉션에 추가되고 보고서가 이에 따라 업데이트되는 실시간 보고서에 사용할 수 있습니다.
  • 동적 변경: 사용자가 데이터를 추가, 삭제 또는 수정할 수 있는 응용 프로그램의 경우, ObservableCollection을 사용하여 UI 또는 다른 구성 요소에 이러한 변경 사항을 자동으로 반영할 수 있습니다.

IronPDF와 함께 작업하기

IronPDF 개요

C# ObservableCollection (개발자를 위한 작동 방법): 그림 1

이 기사의 시작 부분에서 언급한 것처럼, IronPDF은 .NET PDF 생성 라이브러리로서 PDF 문서를 쉽게 생성, 수정 및 렌더링할 수 있게 해줍니다. 다른 일부 PDF 라이브러리와 달리, IronPDF는 HTML을 PDF로 변환, 워터마크 추가, 기존 PDF 조작 등과 같은 PDF 작업을 단순화하는 풍부한 기능 세트를 제공합니다.

IronPDF는 HTML, 이미지 및 일반 텍스트를 포함하여 다양한 데이터 소스에서 PDF를 렌더링할 수 있게 하여 특히 동적 데이터를 표시해야 할 때 유용합니다. IronPDF의 API를 사용하여 상세한 레이아웃, 표, 이미지, 스타일을 포함한 고품질의 PDF를 생성할 수 있습니다.

IronPDF 설정

IronPDF를 시작하려면 NuGet을 통해 라이브러리를 설치해야 합니다. 패키지 매니저 콘솔에서 다음 명령을 실행하여 프로젝트에 추가할 수 있습니다:

Install-Package IronPdf

설치된 후 IronPDF를 초기화하고 강력한 기능을 사용할 수 있습니다. 이 기사에서는 ObservableCollection에서 동적 데이터를 기반으로 PDF를 생성하는 데 중점을 둘 것입니다.

IronPDF와 ObservableCollection 통합하기

사용 사례: ObservableCollection에서 동적으로 PDF 생성하기

ObservableCollection에 저장된 항목 목록에서 송장 PDF를 생성해야 하는 시나리오를 상상해 보십시오. 컬렉션에 항목이 추가되거나 제거될 때마다, PDF는 데이터를 반영하기 위해 자동으로 다시 생성되어야 합니다.

이 작업을 위해 ObservableCollection은 송장의 항목을 쉽게 관리하는 방법을 제공하며, IronPDF는 송장을 PDF 형식으로 생성하고 내보낼 수 있게 합니다.

PDF 콘텐츠에 데이터 바인딩하기

ObservableCollection의 데이터를 PDF에 바인딩하려면 컬렉션을 통해 반복하여 항목을 PDF 콘텐츠에 추가해야 합니다. IronPDF은 데이터를 구조화된 형식으로 표현하기 쉽게 테이블 생성, 텍스트 추가, 레이아웃 사용자 정의 방법을 제공합니다.

예를 들어, 여러 항목이 있는 송장이 있다면 ObservableCollection을 반복하고 각 항목을 문서의 테이블이나 목록에 추가하여 동적으로 PDF를 생성할 수 있습니다. IronPDF는 글꼴, 테두리 조정 및 로고나 바코드와 같은 이미지를 포함할 수 있는 고도의 사용자 정의를 허용합니다.

예제 하나: ObservableCollection을 사용하여 PDF 생성하기

작동 방식을 보여주는 간단한 예제를 살펴봅시다. Person 클래스로 표현된 사람들의 컬렉션이 있고, 이 사람들의 세부 사항을 반영하는 PDF를 생성하려고 합니다. 새로운 사람이 컬렉션에 추가될 때마다, PDF는 자동으로 업데이트될 것입니다.

Person 클래스 예제

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를 자동으로 재생성합니다. 사람 객체의 추가 또는 제거와 같은 변화에 대응해야 하는 경우에 유용합니다.

// 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가 새 항목을 포함하여 재생성됩니다.

나이 속성 바인딩

사람의 나이 속성을 UI 또는 응용 프로그램의 다른 부분과 같은 외부 시스템에 바인딩하여 변경 사항을 자동으로 반영할 수 있습니다.

다음은 사람 클래스에서 나이 속성이 어떻게 바인딩될 수 있는지 예제입니다:

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

예제 2: 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 및 총계를 계산하는 속성을 가진 송장 항목을 나타냅니다.
  • ObservableCollection: 송장 항목의 목록을 저장하는 데 사용됩니다. 컬렉션은 항목이 추가되거나 제거될 때의 변경 사항을 자동으로 리스너에게 알립니다.
  • GenerateInvoicePDF: 이 메소드는 송장을 나타내는 HTML 콘텐츠를 생성하고 IronPDF를 사용하여 이를 PDF로 변환합니다.
  • CollectionChanged: CollectionChanged이벤트가 핸들링되어 컬렉션 변경 시 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는 INotifyCollectionChanged 인터페이스를 구현하는 C#의 클래스입니다. 이 클래스는 항목이 추가, 제거 또는 수정될 때 알림을 제공하므로 실시간 업데이트가 필요한 UI 애플리케이션의 데이터 바인딩에 이상적입니다.

C#에서 동적 데이터를 PDF로 생성하려면 어떻게 해야 하나요?

IronPDF를 사용하면 C#의 ObservableCollection를 활용하여 동적 데이터에서 PDF를 생성할 수 있습니다. 컬렉션이 업데이트되면 현재 데이터 상태를 반영하도록 PDF를 자동으로 다시 생성할 수 있습니다.

PDF 생성에 ObservableCollection을 사용하는 이점은 무엇입니까?

ObservableCollection는 실시간 데이터 추적이 가능하므로 실시간 데이터 변경 사항을 반영해야 하는 PDF를 생성할 때 유용합니다. IronPDF와 함께 사용하면 데이터의 모든 업데이트가 PDF 출력에 즉시 반영됩니다.

C#에서 ObservableCollection에서 PDF로 데이터를 바인딩하려면 어떻게 해야 하나요?

ObservableCollection의 항목을 반복하면서 IronPDF의 메서드를 사용하여 이를 테이블이나 목록과 같은 구조화된 요소로 PDF에 추가하여 데이터를 PDF로 바인딩할 수 있습니다. 이는 PDF 내용이 항상 데이터와 동기화되도록 보장합니다.

C#에서 ObservableCollection으로 PDF를 생성하는 가장 일반적인 사용 사례는 무엇입니까?

가장 일반적인 사용 사례는 항목의 ObservableCollection에서 송장을 생성하는 것입니다. 항목이 컬렉션에 추가되거나 컬렉션에서 제거될 때 PDF 송장을 다시 생성하여 현재 항목 목록을 정확하게 반영하여 최신 문서화를 보장할 수 있습니다.

IronPDF는 C#에서 HTML을 PDF로 변환하는 방법은 무엇입니까?

IronPDF는 RenderHtmlAsPdfRenderHtmlFileAsPdf와 같은 메서드를 사용하여 HTML을 PDF로 변환할 수 있습니다. 이는 개발자가 웹 페이지나 HTML 문자열에서 PDF를 생성할 수 있도록 하여 동적 콘텐츠 렌더링을 용이하게 합니다.

PDF 생성을 위한 큰 ObservableCollections 작업 시 고려해야 할 사항은 무엇입니까?

큰 컬렉션을 다룰 때는 성능 문제를 방지하기 위해 페이지 나누기, 업데이트 배치 및 레이아웃 최적화를 고려하세요. IronPDF의 캐싱 및 렌더링 최적화는 큰 데이터를 효율적으로 관리하는 데 도움이 될 수 있습니다.

IronPDF가 .NET 애플리케이션에서 생산성을 어떻게 향상시킬 수 있습니까?

IronPDF는 정밀한 레이아웃 사용자 정의, HTML을 PDF로 변환, 다양한 데이터 소스와의 통합과 같은 PDF 생성을 위한 강력한 기능을 제공하여 생산성을 향상시킵니다. 복잡한 PDF 작업을 단순화하여 개발자가 핵심 애플리케이션 로직에 집중할 수 있도록 합니다.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.

제이콥은 맨체스터 대학교에서 토목공학 학사 학위(BEng)를 최우등으로 취득했습니다(1998~2001). 1999년 런던에서 첫 소프트웨어 회사를 설립하고 2005년 첫 .NET 컴포넌트를 개발한 후, 마이크로소프트 생태계 전반에 걸쳐 복잡한 문제를 해결하는 데 전문성을 발휘해 왔습니다.

그의 대표 제품인 IronPDF 및 Iron Suite .NET 라이브러리는 전 세계적으로 3천만 건 이상의 NuGet 설치 수를 기록했으며, 그의 핵심 코드는 전 세계 개발자들이 사용하는 다양한 도구에 지속적으로 활용되고 있습니다. 25년의 실무 경험과 41년의 코딩 전문성을 바탕으로, 제이콥은 차세대 기술 리더들을 양성하는 동시에 기업 수준의 C#, Java, Python PDF 기술 혁신을 주도하는 데 주력하고 있습니다.

아이언 서포트 팀

저희는 주 5일, 24시간 온라인으로 운영합니다.
채팅
이메일
전화해