[英]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.