I'm working with pdfmake to generate pdf with javascript. I'm trying to build a table dynamically but not works ,this my attempt
$.ajax({
type: "POST",
url: myURL,
success:function(data){
/* data has a format like :
*[{"peaje":"Peaje 1","ruta":"Ruta 1","fechaCruce":"2014-10-18","hora":"15:42","valor":"5000"},{"peaje":"Peaje 1","ruta":"Ruta 1","fechaCruce":"2014-10-18","hora":"14:21","valor":"7000"},{"peaje":"Peaje 1","ruta":"Ruta 1","fechaCruce":"2014-09-19","hora":"11:58","valor":"17000"}]
*/
var peajes = JSON.parse( data );
var body = [];
var titulos = new Array( 'PEAJE', 'RUTA', 'FECHA CRUCE', 'HORA', 'VALOR' );
body.push( titulos );
for (key in peajes)
{
if (peajes.hasOwnProperty(key))
{
var peaje = peajes[key];
var fila = new Array();
fila.push( peaje.peaje.toString() );
fila.push( peaje.ruta.toString() );
fila.push( peaje.fechaCruce.toString() );
fila.push( peaje.hora.toString() );
fila.push( peaje.valor.toString() );
body.push(fila);
}
}
console.log( body );
var docDefinition = {
content: [
{
table: {
headerRows: 1,
widths: [ '*', 'auto', 100, '*' ],
body: body
}
}]
};//end docDefinition
pdfMake.createPdf(docDefinition).open();
}//end success
});
This is the example of the library http://pdfmake.org/#/gettingstarted
I don't know what am I doing wrong?
For multiple rows, here is an example
var externalDataRetrievedFromServer = [
{ name: 'Bartek', age: 34 },
{ name: 'John', age: 27 },
{ name: 'Elizabeth', age: 30 },
];
function buildTableBody(data, columns) {
var body = [];
body.push(columns);
data.forEach(function(row) {
var dataRow = [];
columns.forEach(function(column) {
dataRow.push(row[column].toString());
})
body.push(dataRow);
});
return body;
}
function table(data, columns) {
return {
table: {
headerRows: 1,
body: buildTableBody(data, columns)
}
};
}
var dd = {
content: [
{ text: 'Dynamic parts', style: 'header' },
table(externalDataRetrievedFromServer, ['name', 'age'])
]
}