Search code examples
javascriptjspdf-autotable

javascript pdf table generation


I am trying to create a pdf table in javascript. I am using jspdf-autotable library.

This piece of code works fine. The row item data is hard coded. 1 header row, and 2 rows of items, with 3 cells get created

pdf.autoTable({
    startY: finalY + 20,
    head: [['Date', 'Invoice No.', 'Description']],,
    //body: [data.itemrow],
    body: [
                ["Value A", "Value B", "Value C"],
                 ["Value A", "Value B", "Value C"],
            ],

})

Now, i try to dynamically pass in the row data by doing body: [data.itemrow] I create a array. I do

 let itemrow = [];
let item = [];
item[0] = "1";
item[1] = "2";
item[2] = "3";
itemrow.push(item);

The problem is, 1,2,3 gets compressed into the first column. It doesn't get spread out to all the 3 columns. how do u do it? Later I will be dynamically creating this array to pass in data read in from the db.


Solution

  • Part of code you shared here just looks fine, maybe it's the way you are adding the row to the doc

    The item here you create is itself a row, so when you add this to itemrow array it creates array of rows

    So either you can set this itemrow as your body, which is array of rows Or, you can add item inside your body array

    doc.autoTable({
        startY: finalY + 20,
        head: [['Date', 'Invoice No.', 'Description']],
        body: [
            item
        ],
    });
    

    OR

    doc.autoTable({
        startY: finalY + 20,
        head: [['Date', 'Invoice No.', 'Description']],
        body: itemrow,
    });