如何在jspdf-autotable中实现表头文本旋转?
实现表格表头内文本旋转的方案
方案1:使用jsPDF-autoTable插件(推荐)
如果用jsPDF配合autoTable生成表格,直接通过配置项就能实现表头文本旋转,无需手动计算位置:
const doc = new jsPDF(); doc.autoTable({ head: [['旋转表头1', '旋转表头2', '普通表头']], body: [ ['数据行1列1', '数据行1列2', '数据行1列3'], ['数据行2列1', '数据行2列2', '数据行2列3'] ], // 全局设置表头文本旋转角度 headerStyles: { textRotation: 90 }, // 可选:调整旋转表头的列宽,避免文本溢出 columnStyles: { 0: { cellWidth: 35 }, 1: { cellWidth: 35 } } }); doc.save('带旋转表头的表格.pdf');
你也可以给单独的表头列设置旋转,比如只让第一列表头旋转:
columnStyles: { 0: { cellWidth: 35, textRotation: 90 } }
方案2:原生手动绘制表格
如果不依赖插件,需要先绘制表头单元格边框,再计算单元格中心坐标,在该位置旋转文本,确保文本在表头内部:
const doc = new jsPDF(); const startX = 20; const startY = 20; const colWidths = [40, 40, 60]; const rowHeight = 25; // 绘制表头单元格边框 doc.rect(startX, startY, colWidths[0], rowHeight); doc.rect(startX + colWidths[0], startY, colWidths[1], rowHeight); doc.rect(startX + colWidths[0] + colWidths[1], startY, colWidths[2], rowHeight); // 绘制旋转的表头文本(单元格内居中) doc.text('旋转表头1', startX + colWidths[0]/2, startY + rowHeight/2, { angle: 90, align: 'center', baseline: 'middle' }); doc.text('旋转表头2', startX + colWidths[0] + colWidths[1]/2, startY + rowHeight/2, { angle: 90, align: 'center', baseline: 'middle' }); // 普通表头文本 doc.text('普通表头', startX + colWidths[0] + colWidths[1] + colWidths[2]/2, startY + rowHeight/2, { align: 'center', baseline: 'middle' }); // 绘制数据行示例 let currentY = startY + rowHeight; doc.rect(startX, currentY, colWidths[0], rowHeight); doc.text('数据1', startX + colWidths[0]/2, currentY + rowHeight/2, { align: 'center', baseline: 'middle' }); doc.save('手动绘制旋转表头.pdf');
关键注意点
- 使用autoTable时,
textRotation支持0-360的角度值,插件会自动适配单元格布局 - 手动绘制时,必须基于单元格的中心坐标定位文本,同时设置
align: 'center'和baseline: 'middle',才能保证旋转后的文本在表头内居中显示
内容的提问来源于stack exchange,提问作者Sk Sakil Ahmed.
相关产品推荐
相关产品推荐

