Renderizar tabela a partir da fonte de dados
Aspose.PDF permite que você crie a tabela com DataSource a partir de DataSet, Data Table, arrays e objetos IEnumerable usando a classe PdfLightTable.
A classe Table é usada para processar tabelas. Esta classe nos dá a capacidade de criar tabelas e colocá-las no documento, usando Rows e Cells . Portanto, para criar a tabela, você precisa adicionar o número necessário de linhas e preenchê-las com o número apropriado de células.
O seguinte exemplo cria a tabela 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" );
}
Ao inicializar o objeto Table, as configurações mínimas de aparência foram usadas:
Exportando dados de um array de objetos
A classe Table fornece métodos para interagir com fontes de dados ADO.NET - ImportDataTable e ImportDataView . O primeiro método importa dados do DataTable, o segundo do DataView.
Premetendo que esses objetos não são muito convenientes para trabalhar no modelo MVC, nos limitaremos a um breve exemplo. Neste exemplo (linha 50), o método ImportDataTable é chamado e recebe como parâmetros uma instância de DataTable e configurações adicionais, como a flag de cabeçalho e a posição inicial (linhas/colunas) para a saída dos dados.
.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 ) }
};
}