Pruebe en producción sin marcas de agua.
Funciona donde lo necesite.
Obtén 30 días de producto totalmente funcional.
Ténlo en funcionamiento en minutos.
Acceso completo a nuestro equipo de asistencia técnica durante la prueba del producto
En C#, la ObservableCollection
IronPDF es una biblioteca robusta para generar PDFs en C#. Con sus capacidades de conversión de HTML-a-PDF, es fácil crear PDFs de alta calidad, ya sea que necesite generar facturas, informes u otros documentos basados en datos en tiempo real. En este artículo, te mostraremos cómo integrar la clase ObservableCollection con IronPDF, aprovechando la vinculación de datos para generar un PDF que se actualiza dinámicamente a medida que los datos cambian.
La clase ObservableCollection
La ObservableCollection maneja automáticamente los cambios en toda la colección, lo que facilita la gestión y visualización de una colección de datos dinámica en su aplicación.
Añadir desde PixabaySubir
o arrastre y suelte una imagen aquí
Agregar texto alternativo de la imagen
Como mencionamos al comienzo de este artículo, IronPDF es una biblioteca de generación de PDF para .NET que facilita la creación, modificación y renderización de documentos PDF. A diferencia de algunas otras bibliotecas de PDF, IronPDF ofrece un conjunto completo de funciones que simplifican el trabajo con PDFs, como la conversión de HTML a PDF, la adición de marcas de agua, la manipulación de PDFs existentes y más.
IronPDF también permite a los desarrolladores renderizar PDFs a partir de diferentes fuentes de datos, incluyendo HTML, imágenes y texto plano, lo cual puede ser especialmente útil cuando necesitas presentar datos dinámicos. Con la API de IronPDF, puedes generar PDFs de alta calidad, incluyendo diseños detallados, tablas, imágenes y estilos.
Para comenzar con IronPDF, necesitas instalar la biblioteca a través de NuGet. Puede agregarlo a su proyecto ejecutando el siguiente comando en la Consola del Administrador de Paquetes:
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
Una vez instalado, puedes inicializar IronPDF y utilizar sus potentes características. En este artículo, nos enfocaremos en generar PDFs a partir de datos dinámicos en un ObservableCollection.
Imaginemos un escenario en el que necesitas generar un PDF de factura a partir de una lista de artículos almacenados en un ObservableCollection. A medida que se agregan o eliminan elementos de la colección, el PDF debe regenerarse automáticamente para reflejar el estado actual de los datos.
Para esta tarea, ObservableCollection proporciona una forma fácil de gestionar los elementos en la factura, mientras que IronPDF nos permitirá generar y exportar la factura a un formato PDF.
Para vincular los datos en un ObservableCollection a un PDF, necesitas recorrer la colección y agregar sus elementos al contenido del PDF. IronPDF proporciona métodos para crear tablas, agregar texto y personalizar el diseño, lo que facilita la representación de los datos en un formato estructurado.
Por ejemplo, si tiene una factura con varios artículos, puede generar dinámicamente el PDF recorriendo el ObservableCollection y agregando cada artículo a una tabla o lista en el documento. IronPDF permite un alto nivel de personalización, incluyendo el ajuste de fuentes, bordes e incluso la inclusión de imágenes como logotipos o códigos de barras.
Veamos un ejemplo sencillo para demostrar cómo funciona esto. Supongamos que tienes una colección de personas (representadas por la clase Persona), y deseas generar un PDF que refleje los detalles de estas personas. Cada vez que se añada una nueva persona a la colección, el PDF se actualizará automáticamente.
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
En este caso, la clase Person contiene propiedades básicas como Nombre y Edad. Usaremos esta clase junto con ObservableCollection para generar dinámicamente un 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
}
}
Esta ObservableCollection contiene una colección de objetos Person, cada uno con un Nombre y una Edad. Cuando se añade o elimina un elemento, se activan los controladores de eventos, que utilizaremos para actualizar el PDF dinámicamente.
En este ejemplo, nos suscribimos al evento CollectionChanged de la clase ObservableCollection para regenerar automáticamente el PDF cada vez que la colección cambie. Esto es útil si necesita responder a cambios como agregar o eliminar un objeto Persona.
// 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
Puedes agregar una nueva persona a la colección, y la colección completa activará el controlador de eventos para regenerar el PDF. Este enfoque maneja automáticamente los cambios en la lista completa de personas.
// 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
})
Cada vez que agregue una nueva persona a la colección, el PDF se regenerará, incluyendo la nueva entrada.
También puedes vincular la propiedad age de una Persona a algún sistema externo (como la interfaz de usuario u otras partes de la aplicación) para reflejar automáticamente los cambios.
Aquí tienes un ejemplo de cómo se vincularía la propiedad Age en la clase Person:
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
Demostremos el uso de binding age a un elemento de la interfaz de usuario, actualizando el valor de la edad y observando cómo se reflejan los cambios en la colección:
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()
Ahora que hemos configurado el ObservableCollection y agregado controladores de eventos, es hora de centrarnos en generar un PDF que refleje la colección dinámica de personas.
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
Aquí tienes un ejemplo de cómo generar un PDF a partir de una ObservableCollection de elementos de factura utilizando IronPDF:
Esta clase representa un artículo en la factura, con propiedades para el nombre del artículo, cantidad, precio y precio total.
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
Este ejemplo inicializa un ObservableCollection que contiene varios elementos de factura. Puede agregar, eliminar o modificar dinámicamente los elementos en esta colección.
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
}
}
Aquí, creamos una función para generar el PDF. Esta función utiliza los datos en la ObservableCollection y los convierte en HTML, que luego se representa como un PDF usando IronPDF.
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
Debido a que ObservableCollection notifica automáticamente los cambios, puedes regenerar fácilmente el PDF cada vez que se actualice la colección. Por ejemplo, si se añade o elimina un artículo, se puede regenerar el PDF con los datos actualizados.
A continuación, se muestra cómo puede suscribirse al evento CollectionChanged y regenerar el PDF cada vez que la colección cambie:
// 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
Ahora puede probar añadiendo nuevos elementos a la ObservableCollection y observando cómo el PDF se regenera automáticamente.
// 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
Salida
Añadir desde PixabaySubir
o arrastre y suelte una imagen aquí
Texto alternativo claro
Cuando se trabaja con grandes instancias de ObservableCollection, el rendimiento puede convertirse en una preocupación. Regenerar un PDF cada vez que la colección cambia puede ser intensivo en recursos si hay un gran número de elementos. Para mitigar esto, considere agrupar las actualizaciones o utilizar técnicas como la paginación para evitar sobrecargar el proceso de generación de PDF.
Para garantizar que la renderización de PDF sea eficiente, tenga en cuenta los siguientes consejos:
Al combinar ObservableCollection de C# con IronPDF, puedes generar fácilmente PDFs dinámicos que reflejen cambios en tiempo real en los datos de tu aplicación. Ya sea que esté generando facturas, informes u otros documentos, este enfoque le permite actualizar automáticamente el contenido del PDF cada vez que la colección subyacente cambie.
La integración de ObservableCollection garantiza que su aplicación esté siempre actualizada con un esfuerzo mínimo, mientras que IronPDF se encarga del trabajo pesado de renderizar PDFs de alta calidad. Al seguir las mejores prácticas y los consejos de rendimiento discutidos en este artículo, puedes crear una experiencia de generación de PDF fluida para tus aplicaciones .NET.
¿Quieres probar IronPDF tú mismo? Descargue la documentación extensa para ver más de esta biblioteca en acción.