Search code examples
loopsdatatableseachpdfmake

DataTables + PDFmake = color PDF table cells?


I am trying to print a PDF file from the array table below where every cell with the word "Software Engineer" is colored blue, and cells with "London" is colored red. Would like to do this with a loop, scanning through all rows or columns one by one (not a specific row or column). However I simply cannot get it to work, and am starting to give up. I guess it has something to do with the each() method?

each()

Table I am using

var editor; // use a global for the submit and return data rendering in the examples

$(document).ready(function() {
    editor = new $.fn.dataTable.Editor( {
        ajax: "../php/staff.php",
        table: "#example",
        fields: [ {
                label: "First name:",
                name: "first_name"
            }, {
                label: "Last name:",
                name: "last_name"
            }, {
                label: "Position:",
                name: "position"
            }, {
                label: "Office:",
                name: "office"
            }, {
                label: "Extension:",
                name: "extn"
            }, {
                label: "Start date:",
                name: "start_date",
                type: "datetime"
            }, {
                label: "Salary:",
                name: "salary"
            }
        ]
    } );

    $('#example').DataTable( {
        dom: "Bfrtip",
        ajax: "../php/staff.php",
        columns: [
            { data: null, render: function ( data, type, row ) {
                // Combine the first and last names into a single table field
                return data.first_name+' '+data.last_name;
            } },
            { data: "position" },
            { data: "office" },
            { data: "extn" },
            { data: "start_date" },
            { data: "salary", render: $.fn.dataTable.render.number( ',', '.', 0, '$' ) }
        ],
        select: true,
        buttons: [
            { extend: "create", editor: editor },
            { extend: "edit",   editor: editor },
            { extend: "remove", editor: editor }
        ]
    } );
} );

Solution

  • Take a look at this example, it changes cells in the PDF if the age is below 40. Something like this would also work for you.

    The key part of the code is this:

    buttons: [
      {
        extend: "pdfHtml5",
        customize: function(doc) {
          age = table.column(3).data().toArray();
          for (var i = 0; i < age.length; i++) {
            if (age[i] < 40) {
              doc.content[1].table.body[i+1][3].fillColor = 'blue';
            }
          }
        }
      }
    ]