我需要从表格生成 PDF 报告,并且我正在使用 jsPDF 和 jsPDF-autotable。 我知道用 jsPDF 生成 PDF 文件非常简单,我相信我正在按照 jsPDF 文档页面上提到的确切步骤进行操作,但到目前为止我还没有取得任何成功。我也遇到过许多类似的问题,但似乎没有一个对我有用。
这是我在 html head 标签中导入 jsPDF 和 jsPDF-autotable 的方法:
<!-- Js PDF -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.0/jspdf.umd.min.js"></script>
<!-- Js PDF Auto Table -->
<script src="https://cdn.jsdelivr.net/npm/jspdf-autotable@3/dist/jspdf.plugin.autotable.min.js"></script>
这是我应该触发 JavaScript 函数的按钮的 html 代码:
<div class="col text-end">
<button type="button" class="btn btn-secondary" id="btnGenerateReport" onclick="prepareReport()">
Generate Report
</button>
</div>
这里是 JavaScript 函数,它应该只根据表格生成一个 PDF 文件:
function prepareReport() {
var doc = new jsPDF();
doc.autoTable({ html: '#reportTable' });
doc.save(stationSelected + '_' + dateSelected + '.pdf');
}
这是我收到的控制台错误:
reports.js:180 Uncaught ReferenceError: jsPDF is not defined
at prepareReport (reports.js:180)
at HTMLButtonElement.onclick (reports:213)
如果能得到所有帮助,我将不胜感激。 谢谢。
最佳答案
问题出在您的函数中:
function prepareReport() {
var doc = new jsPDF();
doc.autoTable({ html: '#reportTable' });
doc.save(stationSelected + '_' + dateSelected + '.pdf');
}
在查看 jsPDF project repo 之后,像您一样使用标签导入此模块, 将全局变量导出为 jspdf
,而不是 jsPDF
。
所以正确的工作版本应该是:
function prepareReport() {
var doc = new jspdf.jsPDF();
doc.autoTable({ html: '#reportTable' });
doc.save(stationSelected + '_' + dateSelected + '.pdf');
}
请注意,仅此代码是不够的,因为未定义stationSelected
和dateSelected
。您还应该为这些值提供定义。
直播codepen工作示例。
关于javascript - 未捕获的 ReferenceError : jsPDF is not defined with version 2. 3.0 和纯 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66338033/