Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables Export PDF with 100% Width

I am attempting to export my tables to PDF with a 100% width. I have tried the following but I have been unsuccessful

var settings={};
settings.buttons = [
    {
        extend:'pdfHtml5',
        text:'Export PDF',
        orientation:'landscape',
        customize : function(doc){ 
            doc.styles['table'] = { width:100% }
        }
    }
];
$('.dTable').dataTable(settings);
like image 244
Douglas Cottrell Avatar asked Feb 26 '16 03:02

Douglas Cottrell


Video Answer


2 Answers

Found an easier and quicker way to do it.

{
  extend: 'pdf',
  customize: function (doc) {
    doc.content[1].table.widths = 
        Array(doc.content[1].table.body[0].length + 1).join('*').split('');
  }
}

What happens here is as so:

doc.content[1].table.widths is an array of widths for each column, and if each of them is a '*' it means that the table will fit 100% of the page with the columns distributed evenly.

Array(doc.content[1].table.body[0].length + 1) creates an array in the length of all the columns of my table.

.join('*') creates a string from all the cells in the array with a '*' for each.

.split(''); splits it back into an array.

Hope I helped someone along the way.

like image 176
Rabbi Shuki Gur Avatar answered Sep 18 '22 15:09

Rabbi Shuki Gur


After digging and digging I found that you simply need to add a width of '*' for each of the columns. I created a simple function in order to create an array based on the number of td tags and included a colspan check.

var tbl = $('.dTable');
var settings={};
settings.buttons = [
    {
        extend:'pdfHtml5',
        text:'Export PDF',
        orientation:'landscape',
        customize : function(doc){
            var colCount = new Array();
            $(tbl).find('tbody tr:first-child td').each(function(){
                if($(this).attr('colspan')){
                    for(var i=1;i<=$(this).attr('colspan');$i++){
                        colCount.push('*');
                    }
                }else{ colCount.push('*'); }
            });
            doc.content[1].table.widths = colCount;
        }
    }
];
$('.dTable').dataTable(settings);
like image 35
Douglas Cottrell Avatar answered Sep 21 '22 15:09

Douglas Cottrell