0
votes

I want to generate a pdf from below HTML table, and I’m using jsPdf-AutoTable for that. I’m getting a PDF as below image. The table consist of correct number of rows without any data in it. How to get generate the pdf our of this table.? I'm also using Datatable.js on this table.

enter image description here

HTML Table markup and Javascript given below.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>
<script src="https://github.com/MrRio/jsPDF/blob/master/dist/jspdf.debug.js"> </script>
<script src="https://github.com/simonbengtsson/jsPDF-AutoTable/blob/master/dist/jspdf.plugin.autotable.src.js"> </script>

// this function generates the pdf using the table
function generate() {
  var columns = ["productid", "productname", "unit", "unitprice"];
  var data = tableToJson($("#products-table").get(0), columns);
  var doc = new jsPDF('p', 'pt');
  doc.autoTable(columns, data);
  doc.save("table.pdf");
}

// This function will return table data in an Array format
function tableToJson(table, columns) {
  var data = [];
  // 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[columns[j]] = tableRow.cells[j].innerHTML;
    }
    data.push(rowData);
  }
  return data;
}
<table id="products-table" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th>ProductId</th>
        <th>ProductName</th>
        <th>Unit</th>
        <th>UnitPrice</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
      </tr>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
      </tr>
    </tbody>
  </table>

  <a href="#" onclick="generate()" id="generate-report-button" class="btn">Run Code</a>
1

1 Answers

2
votes

It is because you are creating objects from table data. You should create an array from the data.

function tableToJson(table, columns) {
  var data = [];
  // go through cells
  for (var i = 1; i < table.rows.length; i++) {
    var tableRow = table.rows[i];

    // create an array rather than an object
    var rowData = [];
    for (var j = 0; j < tableRow.cells.length; j++) {
        rowData.push(tableRow.cells[j].innerHTML)
    }
    data.push(rowData);
  }

  return data;
}

check working fiddle https://jsfiddle.net/shakee93/dh8e7gjc/