JSPDF自动表:根据列数设置动态字体大小



我需要打印一个包含20多列的大表。有没有一种方法可以在不扭曲观点的情况下实现这一点。

我尝试过根据表格的列数设置字体大小,但无法实现:

doc.autoTable({
styles: {
cellPadding: 0.5,
overflow: 'visible',
cellWidth: 'wrap'
},
columnStyles: {
columnWidth: 'auto'
},
margin: {
left: 5,
right: 5
},
tableLineWidth: 0.5,
head: headers as any,
body: body,
didDrawCell: (data) => {
if (this.length > 5) { // Number of columns
doc.autoTable({
styles: {
fontSize: 1
}
});
}
},
didDrawPage: (data) => {
console.log(data);
}
});

或者还有其他更好的方法可以实现这一点,因为目前无论我尝试什么,如果我显示所有列,并且如果我包装columnWidthcellWidth,则只显示指定宽度内包含的元素,则我的视图都会失真。

现在我可以通过计算fontSize upFront并将其作为样式对象中的值来完成

exportAsPDF(data: Array<any>, fileName: string) {
const headers: Array<Array<string>> = this.setPDFHeader(data);
const fontSize: number = this.calculateFontSize(headers[0].length);
const body: Array<Array<string>> = this.setPDFBody(data);
const doc = new jsPDF();

doc.autoTable({
styles: {
cellPadding: 0.5,
fontSize: fontSize
},
headStyles: {
fillColor: '#3f51b5',
textColor: '#fff',
halign: 'center'
},
bodyStyles: {
halign: 'center'
},
margin: {
left: 5,
right: 5
},
tableLineWidth: 1,
head: headers as any,
body: body
});
doc.save(fileName);
}

setPDFHeader(data: Array<any>): Array<Array<string>> {
return [
Object.keys(data[data.length - 1]).map(
(item) => `${item.charAt(0).toUpperCase()}${item.substr(1, item.length)}`
)
];
}

setPDFBody(data: Array<any>): Array<Array<string>> {
return data.map((item) => {
const keys = Object.keys(item);
const values = [];
keys.forEach((key) => {
values.push(item[key]);
});
return values;
});
}

calculateFontSize(count: number): number {
return count ? tableWidth / count : count;
}

最新更新