[英]Angular: Typescript: Uncaught TypeError: Cannot set property 'autoTable' of undefined
我正在尝试使用 angular 和 jspdf-autotable 导入一个简单的表。 但我不能,这是错误
jspdf.plugin.autotable.js:1023 Uncaught TypeError: Cannot set property 'autoTable' of undefined
at Object.<anonymous> (jspdf.plugin.autotable.js:1023)
at __webpack_require__ (jspdf.plugin.autotable.js:39)
at jspdf.plugin.autotable.js:103
at jspdf.plugin.autotable.js:106
at webpackUniversalModuleDefinition (jspdf.plugin.autotable.js:12)
at Object../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js (jspdf.plugin.autotable.js:19)
at __webpack_require__ (bootstrap:84)
at Module../src/app/components/zone-list/zone-list.component.ts (zone-list.component.ts:12)
at __webpack_require__ (bootstrap:84)
at Module../src/app/app-routing.module.ts (app-routing.module.ts:3)
对于package.json :
"jspdf": "^2.1.0",
"jspdf-autotable": "^2.3.5",
对于.ts :
这是进口:
import jsPDF from 'jspdf';
var autoTable = require('jspdf-autotable');
这里是下载 function:
var head = [['ID', 'Country', 'Rank', 'Capital']]
var data = [
[1, 'Denmark', 7.526, 'Copenhagen'],
[2, 'Switzerland', 7.509, 'Bern'],
[3, 'Iceland', 7.501, 'Reykjavík'],
[4, 'Norway', 7.498, 'Oslo'],
[5, 'Finland', 7.413, 'Helsinki'],
]
const doc = new jsPDF()
autoTable(doc, {
head: head,
body: data,
didDrawCell: (data) => {
console.log(data.column.index)
},
})
doc.save('table.pdf')
告诉我哪里出了问题?
如果你更换会发生什么
var autoTable = require('jspdf-autotable')
与此: import autoTable from 'jspdf-autotable'
?
解决方案:不要使用jspdf,使用pdfmake [https://www.npmjs.com/package/pdfmake]
(当有更好的工具、更好的功能和更简单的编码方式时,你为什么要使用有缺陷的工具?
当然,我明白了——没有图书馆是 100% 完美的。 但是当我们谈论一个特殊的功能或目的时,一些库比其他库更容易出错。 如:我的情况是html表到typescript中的PDF。我也试过jspdf-autotable但没有运气)
我的工作现在更简单了,我不需要像 html2canvas 这样的其他截图工具来获取我所有的表格截图,我不再需要担心我的截图,图像大小调整。 此外,我在 PDF 中有一个实际的表,这意味着我可以从我的 PDF 复制数据,它不再只是一个图像。
让我们开始吧。
安装 pdfmake:
(我的案例是为 Angular 安装的)
npm i pdfmake --save
typescript 代码:
导入它:
import pdfMake from "../../../../node_modules/pdfmake/build/pdfmake";
import pdfFonts from "../../../../node_modules/pdfmake/build/vfs_fonts";
pdfMake.vfs = pdfFonts.pdfMake.vfs;
写入 function:
现在只要写一个function下载PDF你想触发你PDF下载按钮
peopleExportToPdf() {
let docDefinition = {
content: [
{
table: {
body: [
[{ text: 'SL#', bold: true }, { text: 'Name', bold: true }, { text: 'Age', bold: true }],
[{ text: 'Bold value', bold: true }, 'Val 2', 'Val 3'],
]
}
}]
}
docDefinition.content[0].table.body.pop(); //remove the unnecessary 2nd row
let slno: number = 1;
for (let p of this.people) {
docDefinition.content[0].table.body.push([{ text: slno.toString(), bold: true }, p.name, p.age.toString()]);
slno = slno +1;
}
pdfMake.createPdf(docDefinition).download('Report.pdf');
}
3个头:
礼貌:
我从以下两个链接获得了帮助:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.