Petr Bečka Petr Bečka - 1 month ago 13
Javascript Question

PDFMake - make PDF from dynamical content (an array)

I'm having trouble creating PDF file, where I can put a data from array dynamically, with for loop for example. Length of the array can be different every time so there is no way I'll just write for one size of array.

There is example what I'm able to do:

var stuff = [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccc',
'ddddddddddddddddddd'
]
var dd = {
content:
[
{text: stuff[0], pageBreak: 'after'},
{text: stuff[1], pageBreak: 'after'},
{text: stuff[2], pageBreak: 'after'},
{text: stuff[3], pageBreak: 'after'}
]
}


But I'd love to do something like that:

var stuff = [
'aaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbb',
'ccccccccccccccccccc',
'ddddddddddddddddddd'
]

var dd = {
content:
[
for(var i=0;i<stuff.length;i++){
{text: stuff[i], pageBreak: 'after'}
}
]
}


I know that the second piece of code makes no sence but it shows what I want to do.

Is there any way how to do achieve that?

Answer

You could use Array#map, like this

var stuff = [
    'aaaaaaaaaaaaaaaaaaa',
    'bbbbbbbbbbbbbbbbbbb',
    'ccccccccccccccccccc',
    'ddddddddddddddddddd'
];

var dd  = {
    content: stuff.map(function(item) {
        return { text: item, pageBreak: 'after'}
    })
};
Comments