Search code examples
javascripthtmlangularjspdfjspdf

HTML table to pdf using javascript


I have created an appliction for downloading a html table to pdf using javascript i used jsPDF plugin. The application is working fine but the problem is that the table is not proper. The width of the table as well as the header is not properly alligned. I am using angularjs for creating the table.

Can anyone please give me some suggestion for this problem

JSFiddle

function demoFromHTML() {
    var pdf = new jsPDF('p', 'pt', 'letter');
    source = $('#customers')[0];
    specialElementHandlers = {
        '#bypassme': function (element, renderer) {
            return true
        }
    };
    margins = {
        top: 4,
        bottom: 4,
        left: 4,
        width: 522
    };
    pdf.fromHTML(
    source, // HTML string or DOM elem ref.
    margins.left, // x coord
    margins.top, { // y coord
        'width': margins.width, // max width of content on PDF
        'elementHandlers': specialElementHandlers
    },

    function (dispose) {
        pdf.save('Test.pdf');
    }, margins);
}

Solution

  • I guess you currently have to do that manually (fiddle):

    function demoFromHTML() {
        var pdf = new jsPDF('p', 'pt', 'letter');
    
        pdf.cellInitialize();
        pdf.setFontSize(10);
        $.each( $('#customers tr'), function (i, row){
            $.each( $(row).find("td, th"), function(j, cell){
                var txt = $(cell).text().trim() || " ";
                var width = (j==4) ? 40 : 70; //make 4th column smaller
                pdf.cell(10, 50, width, 30, txt, i);
            });
        });
    
        pdf.save('sample-file.pdf');
    }