使用jsPdf Autotable时出错

Getting error while using jsPdf Autotable

本文关键字:出错 Autotable jsPdf 使用      更新时间:2023-09-26

我试图将数据打印到PDF中,所以我使用了jsPdf,当时数据没有正确对齐到我的PDF表中。所以我在很多网站上搜索,他们推荐我使用jsPdf-Auto表。这里的问题出现了,在注入jsPdf-Auto表之前,每件事都很好(没有对齐),但在我插入之后

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.16/jspdf.plugin.autotable.js"></script>

这是我的index.html收到错误,

未捕获引用错误:未定义jsPDF(jsPDF.plugin.autotable.js:10)

您需要在jspdf自动表插件之前包含jspdf库。有关详细信息,请参阅文档。您可能还想要最新版本。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<!-- EDIT: For now, add this line between the libraries -->
<!-- The reason being that jspdf includes a version of requirejs which -->
<!-- jspdf-autotable currently is not expecting. You can also use version < 2.0.21 -->
<script>if (window.define) delete window.define.amd;</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.28/jspdf.plugin.autotable.js"></script>
<script>
var columns = ["ID", "Name", "Country"];
var rows = [
   [1, "Shaw", "Tanzania"],
   [2, "Nelson", "Kazakhstan"],
   [3, "Garcia", "Madagascar"]
];
var doc = new jsPDF('p', 'pt');
doc.autoTable(columns, rows);
doc.save('table.pdf');
</script>

这不是直接相关的,但对于那些试图在Angular cli创建的Angular 4项目中使用它并获得doc.autoTable的人来说,它不是一个函数。将jspdf和jspdf.plugin.autotable包含在脚本数组中的.angular-cli.json文件中

"scripts": [
    "../node_modules/jspdf/dist/jspdf.min.js",
     "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.src.js"
  ],

然后在要使用自动表格的组件中,首先导入jspdf和jspdf自动表格

import * as jsPDF from 'jspdf';
import * as jpt from 'jspdf-autotable';

然后按以下方式使用在进行doc.autotable调用之前,您必须声明jpt变量

let doc = new jsPDF('p', 'pt');    jpt; 
doc.autoTable(this.columns, this.data);
doc.text(20, 20, 'Hello world!');
doc.text(20, 40, 'This is client-side Javascript, pumping out a PDF.');
// Save the PDF
doc.save('Test.pdf');