javascriptinputjspdf-autotable

How to add input field values in jsPDF Autotable dynamically?


I'm creating a month schedule as HTML table with three columns where the first column is the date of the day, the second column is an input field value and third column are phone numbers.

var pdf = new jsPDF({
    orientation: 'p',
    unit: 'mm',
    format: 'a4',
    putOnlyUsedFonts: true
});
var elem = document.getElementById("table-");
var res = pdf.autoTableHtmlToJson(elem);
pdf.autoTable(res.columns, res.data, {
    startY: 30,
    tableWidth: 'auto',
    theme: 'grid',
    headStyles: {
        fillColor: '#a9a6a6',
        textColor: '#000000'
    },
    columnStyles: {
        0: { cellWidth: 15 }
    }
});
pdf.save(`Test.pdf`);

This creates the first and third column correctly, but doesn't display the input field values in the second column. Those values are stored in localStorage and can be loaded from there, but I don't know how to add them to the autotable.


Solution

  • I found and modified a function from the Autotable GitHub examples and it works now.

    function dynamicRows(rowCount) {
        rowCount = rowCount || 10
        var body = []
        for (var j = 1; j <= rowCount; j++) {
            body.push({
                datum: '//content here',
                Mitarbeiter: localStorage.getItem('key name'),
                id: j
            })
        }
        return body
    }
    

    And then the function that creates the Autotable

    function createAutotable(month, year) {
        var pdf = new jsPDF({
            orientation: 'p',
            unit: 'mm',
            format: 'a4',
            putOnlyUsedFonts: true
        });
    
        const monthNumber = moment().month(month).format('M');
        const daysInMonth = moment(`${year}-${monthNumber}`, 'YYYY-MM').daysInMonth();
    
        var body = dynamicRows(daysInMonth);
        body.forEach(function (row) {
            row[0] = row.datum;
            row[1] = row.Mitarbeiter;
            row[2] = row.id;
        });
        pdf.autoTable({
            startY: 30,
            tableWidth: 'auto',
            theme: 'grid',
            head: [
                //headers here
            ],
            body: body
        });
        pdf.save('test.pdf');
    }