Search code examples
javascriptangularjsjspdfpdfmake

is it possible repeat rows of table in pdf file with pdfmake.js


Is it possible torepeat rows in table generated in pdf with pdfmake.min.js? I am creating a PDF file. in which I need to repeat row of table according my api response, which is an array of object.

var dd = {content: [
                    {   
                     table: {
                        body: [
                               [ 'Col1', 'Col2', 'Col3'],
                               [ '1', '2', '3'],
                               [ '1', '2', '3']
                              ]
                            }
                    }
                   ]
         };

This is the simple way of creating table with pdfmake. my question is can we use any alternative(like ng-repeat) to repeat large data in table's rows? I got the best way to generate pdf is with pdfmake. suggest me how to repeat table rows.


Solution

  • So I assume you are creating your pdf like: pdfMake.createPdf(dd).open();

    where the dd variable is basically just a simple javascript object. You can extend that any way you want with arrays, and whatnot, for example:

    var
      body = [],
      content = [],
      dd = {
        'content' : content 
      };
    
    body.push(['col1', 'col2', 'col3']);
    
    var secondRow = [];
    
    // Push numbers 0, 1, 2
    for (var i = 0; i < 3; i++) {
      secondRow.push("i is:" + i);
    }
    
    body.push(secondRow);
    
    // ...
    // Manipulate the 'body' any way you want.
    // ...
    
    // Lets push the manipulated body into the 'content'
    // which is already inside the 'dd'.
    content.push({
      'table' : {
        'body' : body
      }
    });
    
    // Now with all the manipulated data, create the pdf.
    pdfMake.createPdf(dd).open();
    

    So the point is, to manipulate this js object the way you want, when you are all set and done, call the createPdf.

    If you paste my script into pdfmake-playground, you can see what I mean.