DataTables & PDFmake

Darshan picture Darshan · Nov 6, 2015 · Viewed 8.5k times · Source

I'm trying to work with DataTables Export feature, where I am able to export as CSV, xlxs, pdf. Now my current requirement is to export a custom pdf (change the font size, color, etc.). In the DataTable documentation it states, that we can integrate it with PDFmake, which I am unable to do so.

If anyone could please help in a way to integrate/use PDFmake with DataTables it would be really helpful.

Thanks in advance.

I'm initialising the DataTables

var table = $('#Table').DataTable( {
  lengthChange: true,
  buttons: [
    'copyHtml5',
    {
      extend: 'csvHtml5',
      title:  'FileName'
    },
    {
      extend: 'excelHtml5',
      title:  'FileName'
    },
    {
      extend: 'pdfHtml5',
      orientation: 'landscape',
      title:  'FileName',
      //download: 'open',
      pageSize: 'A3'
    }
  ]
});

I have all the necessary JS and CSS files required, how do I link the PDFMake in this?

Answer

misha130 picture misha130 · Nov 22, 2015

You can access the PdfMake object when you declare the DataTables and change the font like this:

window.pdfMake.fonts = {
        alef: {
            normal: 'Alef-Bold.ttf',
            bold: 'Alef-Bold.ttf',
            italics: 'Alef-Bold.ttf"',
            bolditalics: 'Alef-Bold.ttf',
        }
    };

This code assigns the custom font Alef to be used. A font that I assigned as the vfs.

(See https://github.com/bpampuch/pdfmake/wiki/Custom-Fonts---client-side if you are interested in how to make this)

For other customizations what you need is the customize option in the Button.

See here: https://datatables.net/reference/button/pdfHtml5

Here is an example of how to initialize the new font in the DataTable

 $("table").DataTable({
            buttons: [
                {
                    extend: 'pdf', className: 'btn green btn-outline',  text: 'Export PDF',
                    customize: function (doc) {
                        doc.defaultStyle = 
                            {
                                font: 'alef'
                            }

                          }
                       } 
                   ]
               });