Renderizar tabla desde la fuente de datos
Aspose.PDF permite crear la tabla con DataSource desde DataSet, Data Table, arreglos y objetos IEnumerable utilizando la clase PdfLightTable.
La clase Table se utiliza para procesar tablas. Esta clase nos da la capacidad de crear tablas y colocarlas en el documento, utilizando Rows y Cells . Así que, para crear la tabla, necesitas agregar el número requerido de filas y llenarlas con el número apropiado de celdas.
El siguiente ejemplo crea la tabla 4x10.
.NET Core 3.1
Copy
private static void AddTable ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_WorkingDocuments ();
using ( var document = new Aspose . Pdf . Document ())
{
var page = document . Pages . Add ();
var table = new Aspose . Pdf . Table
{
ColumnWidths = "25% 25% 25% 25%" ,
DefaultCellPadding = new Aspose . Pdf . MarginInfo ( 10 , 5 , 10 , 5 ),
Border = new Aspose . Pdf . BorderInfo ( Aspose . Pdf . BorderSide . All , . 5 f, Aspose . Pdf . Color . Green ),
DefaultCellBorder = new Aspose . Pdf . BorderInfo ( Aspose . Pdf . BorderSide . All , . 2 f, Aspose . Pdf . Color . Green ),
};
for ( var rowCount = 0 ; rowCount < 10 ; rowCount ++)
{
var row = table . Rows . Add ();
for ( int i = 0 ; i < 4 ; i ++)
{
row . Cells . Add ( $"Cell ({i + 1 } , {rowCount + 1 } )" );
}
}
page . Paragraphs . Add ( table );
document . Save ( dataDir + "AddTable_out.pdf" );
}
}
.NET 8
Copy
private static void AddTable ( )
{
var dataDir = RunExamples . GetDataDir_AsposePdf_WorkingDocuments ();
using var document = new Aspose . Pdf . Document ();
var page = document . Pages . Add ();
var table = new Aspose . Pdf . Table
{
ColumnWidths = "25% 25% 25% 25%" ,
DefaultCellPadding = new Aspose . Pdf . MarginInfo ( 10 , 5 , 10 , 5 ),
Border = new Aspose . Pdf . BorderInfo ( Aspose . Pdf . BorderSide . All , . 5 f, Aspose . Pdf . Color . Green ),
DefaultCellBorder = new Aspose . Pdf . BorderInfo ( Aspose . Pdf . BorderSide . All , . 2 f, Aspose . Pdf . Color . Green ),
};
for ( var rowCount = 0 ; rowCount < 10 ; rowCount ++)
{
var row = table . Rows . Add ();
for ( int i = 0 ; i < 4 ; i ++)
{
row . Cells . Add ( $"Cell ({i + 1 } , {rowCount + 1 } )" );
}
}
page . Paragraphs . Add ( table );
document . Save ( dataDir + "AddTable_out.pdf" );
}
Al inicializar el objeto Table, se utilizaron los ajustes mínimos de apariencia:
ColumnWidths - ancho de las columnas (por defecto).
DefaultCellPadding - los campos predeterminados para la celda de la tabla.
Border - atributos del marco de la tabla (estilo, grosor, color).
DefaultCellBorder - atributos del marco de la celda (estilo, grosor, color).
Exportando datos desde un arreglo de objetos
La clase Table proporciona métodos para interactuar con fuentes de datos ADO.NET - ImportDataTable y ImportDataView . El primer método importa datos desde el DataTable, el segundo desde el DataView.
Premitiendo que estos objetos no son muy convenientes para trabajar en la plantilla MVC, nos limitaremos a un breve ejemplo. En este ejemplo (línea 50), se llama al método ImportDataTable y recibe como parámetros una instancia de DataTable y configuraciones adicionales como la bandera de encabezado y la posición inicial (filas/columnas) para la salida de datos.
.NET Core 3.1
Copy
private static void AddTable ( )
{
using ( var document = new Aspose . Pdf . Document
{
PageInfo = new Aspose . Pdf . PageInfo { Margin = new Aspose . Pdf . MarginInfo ( 28 , 28 , 28 , 42 ) }
})
{
var table = new Aspose . Pdf . Table
{
ColumnWidths = "25% 25% 25% 25%" ,
DefaultCellPadding = new Aspose . Pdf . MarginInfo ( 10 , 5 , 10 , 5 ),
Border = new Aspose . Pdf . BorderInfo ( Aspose . Pdf . BorderSide . All , . 5 f, Aspose . Pdf . Color . Green ),
DefaultCellBorder = new Aspose . Pdf . BorderInfo ( Aspose . Pdf . BorderSide . All , . 2 f, Aspose . Pdf . Color . Green ),
};
var configuration = new ConfigurationBuilder ()
. SetBasePath ( Directory . GetCurrentDirectory ())
. AddJsonFile ( "config.json" , false )
. Build ();
var connectionString = configuration . GetSection ( "connectionString" ). Value ;
if ( string . IsNullOrEmpty ( connectionString ))
{
throw new ArgumentException ( "No connection string in config.json" );
}
var resultTable = new DataTable ();
using ( var conn = new SqlConnection ( connectionString ))
{
const string sql = "SELECT * FROM Tennats" ;
using ( var cmd = new SqlCommand ( sql , conn ))
{
using ( var adapter = new SqlDataAdapter ( cmd ))
{
adapter . Fill ( resultTable );
}
}
}
table . ImportDataTable ( resultTable , true , 1 , 1 );
document . Pages [ 1 ]. Paragraphs . Add ( table );
using ( var streamOut = new MemoryStream ())
{
document . Save ( streamOut );
return new FileContentResult ( streamOut . ToArray (), "application/pdf" )
{
FileDownloadName = "demotable2.pdf"
};
}
}
}
.NET 8
Copy
private static void AddTable ( )
{
using var document = new Aspose . Pdf . Document
{
PageInfo = new Aspose . Pdf . PageInfo { Margin = new Aspose . Pdf . MarginInfo ( 28 , 28 , 28 , 42 ) }
};
var table = new Aspose . Pdf . Table
{
ColumnWidths = "25% 25% 25% 25%" ,
DefaultCellPadding = new Aspose . Pdf . MarginInfo ( 10 , 5 , 10 , 5 ),
Border = new Aspose . Pdf . BorderInfo ( Aspose . Pdf . BorderSide . All , . 5 f, Aspose . Pdf . Color . Green ),
DefaultCellBorder = new Aspose . Pdf . BorderInfo ( Aspose . Pdf . BorderSide . All , . 2 f, Aspose . Pdf . Color . Green ),
};
var configuration = new ConfigurationBuilder ()
. SetBasePath ( Directory . GetCurrentDirectory ())
. AddJsonFile ( "config.json" , false )
. Build ();
var connectionString = configuration . GetSection ( "connectionString" ). Value ;
if ( string . IsNullOrEmpty ( connectionString ))
{
throw new ArgumentException ( "No connection string in config.json" );
}
var resultTable = new DataTable ();
using var conn = new SqlConnection ( connectionString );
const string sql = "SELECT * FROM Tennats" ;
using var cmd = new SqlCommand ( sql , conn );
using var adapter = new SqlDataAdapter ( cmd );
adapter . Fill ( resultTable );
table . ImportDataTable ( resultTable , true , 1 , 1 );
document . Pages [ 1 ]. Paragraphs . Add ( table );
using var streamOut = new MemoryStream ();
document . Save ( streamOut );
return new FileContentResult ( streamOut . ToArray (), "application/pdf" )
{
PageInfo = new Aspose . Pdf . PageInfo { Margin = new Aspose . Pdf . MarginInfo ( 28 , 28 , 28 , 42 ) }
};
}