jsPDF与AutoTable无法正常工作-可能是JavaScript问题

3

我有一个简单的表格例子,想要将其下载为PDF文件。我按照AutoTable文档中的设置步骤进行操作:https://github.com/simonbengtsson/jsPDF-AutoTable

我不知道如何创建实际的下载超链接,因此尝试了使用JavaScript,但是出现了“ReferenceError: $未定义”的错误。

我更喜欢使用标准的超链接。

我的代码如下:

<table id="myTable">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

<button id="downloadPdf">Download Table as PDF</button>

<script src="js/jspdf.min.js"></script>
<script src="js/jspdf.plugin.autotable.js"></script>

<script>
$("#downloadPdf").click(function(){
    var doc = new jsPDF()
    doc.autoTable({ html: '#myTable' })
    doc.save('table.pdf')
})
</script>

如果你使用 $ 符号,你需要导入 jQuery。 - Nishant
1个回答

3
您需要导入jQuery文件,下面是一个可行的示例 - https://jsfiddle.net/nishantj/bja0fnve/ 它可以下载PDF文件并按照预期工作。使用了涉及脚本的CDN版本。

$("#downloadPdf").click(function(){
    var doc = new jsPDF()
    doc.autoTable({ html: '#myTable' })
    doc.save('table.pdf')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script>
<table id="myTable">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>
<button id="downloadPdf">Download Table as PDF</button>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接