jspdf-autotable - 创建具有固定列宽确定表格宽度的 jsPDF-Autotable
问题描述
我需要呈现一个从通常的数据呈现方式转置的表格(即在所需的表格中,每条记录由一列表示,每个字段由一行表示)。
我希望除第一列(标题列)之外的每一列都具有相同的宽度。
溢出的列将位于上表下方的新表中(见下文)。
对于最终表格(通常与位于其上方的表格的列数不同),列的宽度应该相同。
因此,在下面的代码段生成的 .PDF 中,2 个表格应该如此对齐(注意单元格的确切数量会有所不同):
+-----+----+----+----+----+----+----+----+----+----+----+
|Day | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
+-----+----+----+----+----+----+----+----+----+----+----+
+-----+----+----+----+----+
|Day | 11 | 12 | 13 | 14 |
+-----+----+----+----+----+
// generating the data for the table
const cols = 14;
const headers = (new Array(cols + 1)).fill(0).map((x,i) => (i).toString());
headers[0] = 'DAY #:';
const today = new Date();
const data = [headers.map((x, i) => {
const date = new Date(today);
date.setDate(date.getDate() + i);
return date.toLocaleDateString(navigator.languages);
}),
headers.map((x, i) => (1 - i / cols).toPrecision(3)),
];
data[0][0] = "Date:"
data[1][0] = "Dose:"
// splitting the table data at 10 columns + rowHeader wide
const maxCols = 10;
const tables = [];
const tableCount = Math.ceil(cols/maxCols)
for (let i = 0; i < tableCount; ++i) {
const slicePos = 1 + i * maxCols;
const mapColsInRange = (d) => [d[0]].concat(d.slice(slicePos, slicePos + maxCols));
tables.push({
headers: mapColsInRange(headers),
data: data.map(mapColsInRange),
});
}
// creating the tables
const doc = new jsPDF('l', 'mm', 'a4');
for (const t of tables) {
doc.autoTable({
theme: 'grid',
head: [ t.headers ],
body: t.data,
pageBreak: 'avoid',
styles: { halign: 'center', cellWidth: 21 },
columnStyles: { 0: { halign: 'left', fontStyle: 'bold', cellWidth: 34 }},
});
}
doc.save('test.pdf');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.1.4/jspdf.plugin.autotable.min.js"></script>
如何使用 jsPDF-autoTable 选项对齐列?
解决方案
添加 autotable 选项tableWidth: 'wrap'
是解决方案
推荐阅读
- c++ - Is there a way to return a vector more efficiently
- aframe - 什么是核心:架构:警告 Aframe 中组件/系统 B 的未知属性 A?
- java - Spring Data JPA 的 @Modifying 是否有任何用途而不指定它的属性?
- api - VueJS - 我如何在 vue-select 中使用 API 的响应
- jpa - 如何在 Spring Data 中使用 @OneToOne 向字段添加新记录?
- r - 我无法安装 survminer 软件包
- blazor - 在服务器中使用与客户端项目相同的布局
- spring - 使用 Spring MVC 按字段将传入的 JSON 分解为对象
- java - JPDA 修改监听器,某种 JVMHotRedeployListener
- python - 如何使用函数使我的代码更加优化?