首页 文章

jsPDF-AutoTable生成一个包含空单元格的PDF表格

提问于
浏览
0

我想从HTML表格下面生成一个pdf,我正在使用jsPdf-AutoTable . 我正在获取PDF如下图所示 . 该表由正确的行数组成,其中没有任何数据 . 如何生成此表的pdf . 我也在这张 table 上使用Datatable.js .

enter image description here

HTML表格标记和下面给出的Javascript .

<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 回答

  • 2

    这是因为您正在从表数据创建对象 . 您应该从数据创建一个数组 .

    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;
    }
    

    检查工作小提琴https://jsfiddle.net/shakee93/dh8e7gjc/

相关问题