jsPDF-Autotable Example to Customize Header Cell inside Tables in PDF Document Using Javascript Full Project For Beginners

 

 

Since nobody answered I used my workaround solution using drawHeaderCell hook with code like below. I tested it on many tables and it works fine (in production I used dynamically generated table with different headers). The only real drawback that you cannot change color of the 1st header, but hopefully I don’t need to do this.

 

 

index.html

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Acroform Text Field in PDF Document</title>
</head>
<body>
    
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script>
<script>
    var doc = new jsPDF()
    var columns = ['ID','Name','Address','Age'];
            var rows = [
            [1,'John','Vilnius',22],
            [2,'Jack','Riga',25]
            ];

            var doc = new jsPDF('p', 'pt');

            doc.setFontSize(20);
            doc.text(30, 30, 'Table'); 

            doc.autoTable(columns, rows, {
                margin: { top: 50, left: 20, right: 20, bottom: 0 },
                drawHeaderCell: function (cell, data) {
                    if (cell.raw === 'ID') {//paint.Name header red
                        cell.styles.fontSize= 15;
                       cell.styles.textColor = [255,0,0];
                    } else {
                        cell.styles.textColor = 255;
                        cell.styles.fontSize = 10;

                    }
                },
                   createdCell: function (cell, data) {
                    if (cell.raw === 'Jack') {
                       cell.styles.fontSize= 15;
                       cell.styles.textColor = [255,0,0];
                    } 
                }
            });

            doc.save('output.pdf');
</script>
</html>

Leave a Reply