8

I got struck for the last two days, to set a column width for generating PDF using jsPDF.

I am able to generate pdf using jsPDF lib from html table, but i am getting problem of overlapping columns. Because I want to display 20 columns in the sheet. I have changed the options portrait to landscape and set the width 5000 in exporting script options as well as html table width.

Please help me, to set the pdf column width from jsPDF. Thanks

user3428816
  • 1,241
  • 3
  • 16
  • 32

1 Answers1

22

I had same problem 4 days back and was able to fix it.. I have provided sample code below for you to understand..

I am assuming that the requirement is to export a html table (mentioned below as table1, that has 3 or more rows) to PDF format. To which we will be setting cell/column width and additionally font and font types for those 3+ rows..

First row would be Header - so bold is applied.. I have applied different styles for 2nd and 3rd rows for understanding styles available.. If you want to apply different column width, for each of the columns - you can do that as well..

Hope the following code is readable and self explanatory. Let me know if you have any questions

 $(document).on("click", "#btnExportToPDF", function () { 

        var table1 = 
        tableToJson($('#table1').get(0)),
        cellWidth = 35,
        rowCount = 0,
        cellContents,
        leftMargin = 2,
        topMargin = 12,
        topMarginTable = 55,
        headerRowHeight = 13,
        rowHeight = 9,

         l = {
         orientation: 'l',
         unit: 'mm',
         format: 'a3',
         compress: true,
         fontSize: 8,
         lineHeight: 1,
         autoSize: false,
         printHeaders: true
     };

    var doc = new jsPDF(l, '', '', '');

    doc.setProperties({
        title: 'Test PDF Document',
        subject: 'This is the subject',
        author: 'author',
        keywords: 'generated, javascript, web 2.0, ajax',
        creator: 'author'
    });

    doc.cellInitialize();

   $.each(table1, function (i, row)
    {

        rowCount++;

        $.each(row, function (j, cellContent) {

            if (rowCount == 1) {
                doc.margins = 1;
                doc.setFont("helvetica");
                doc.setFontType("bold");
                doc.setFontSize(9);

                doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
            }
            else if (rowCount == 2) {
                doc.margins = 1;
                doc.setFont("times ");
                doc.setFontType("italic");  // or for normal font type use ------ doc.setFontType("normal");
                doc.setFontSize(8);                    

                doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i); 
            }
            else {

                doc.margins = 1;
                doc.setFont("courier ");
                doc.setFontType("bolditalic ");
                doc.setFontSize(6.5);                    

                doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);  // 1st=left margin    2nd parameter=top margin,     3rd=row cell width      4th=Row height
            }
        })
    })

doc.save('sample Report.pdf');  })




function tableToJson(table) {
var data = [];

// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
    headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}

// go through cells
for (var i=1; i<table.rows.length; i++) {

    var tableRow = table.rows[i];
    var rowData = {};

    for (var j=0; j<tableRow.cells.length; j++) {

        rowData[ headers[j] ] = tableRow.cells[j].innerHTML;

    }

    data.push(rowData);
}       

return data; }
Vinu
  • 336
  • 2
  • 7
  • You are welcome gco. I am glad that it helped you :) and thank you for voting – Vinu Jun 19 '14 at 20:26
  • @Vinu What version of jsPDF will allow all those options? The one i'm using only allows the following `function jsPDF(orientation, unit, format, compressPdf) { /** String orientation, String unit, String format, Boolean compressed */` – Ryan Gill Jun 20 '14 at 18:44
  • 1
    @RyanGill, I was using some older version and I could not find the exact version from JSPdf files used in my project!! But function is same as what you have mentioned **function jsPDF(orientation, unit, format, compressPdf) {}** – Vinu Jun 24 '14 at 17:05
  • 1
    @Vinu Hi! How can I make that run when I click a button? – user3771102 Sep 26 '14 at 10:00
  • Uncaught TypeError: Cannot read property '0' of undefined -->function tableToJson(table) --> for (var i=0; i – empugandring Feb 24 '15 at 07:37
  • Hi Empugandring, Do you have a table defined in your page and are you passing that to ---- tableToJson($('#table1').get(0))? – Vinu Feb 24 '15 at 09:57
  • Thanks for the code, was looking for something similar from past 2 days. :) – Mahavir Nahata Mar 13 '15 at 09:47
  • this works so good with rows,,, can it be modified for columns because some of the content is being overlapped with another columns... Email column needs huge cell width, , please let me know where to modify this code – Sudhir Belagali Jan 19 '16 at 07:53
  • @Vinu is it possible reduce the pdf top space in jsPDF? – ShaMoh Apr 17 '17 at 06:43
  • I am getting table is not defined in `tableToJson(table)` function . Can anyone help me @SudhirBelagali – Pushprajsinh Chudasama Jan 06 '20 at 09:46