PDFMake - make PDF from dynamical content (an arra

2019-09-04 15:01发布

问题:

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?

回答1:

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'}
    })
};