如何在jsPDF autotable中使tableEL内<strong>包裹的单元格加粗?
解决方法:让jsPDF Autotable识别内的标签实现加粗
要让autotable识别里的标签并在PDF中显示加粗效果,你可以利用autotable的didParseCell回调钩子,在解析单元格时检查内容是否包含加粗标签,然后手动设置单元格的字体样式并清理标签文本。
修改后的核心配置
在你的doc.autoTable配置中添加didParseCell回调:
doc.autoTable({ html: tableEl.querySelector('table'), startY: 50, margin: { top: 10 }, didParseCell: function(data) { // 获取单元格的原始HTML内容 const cellHtml = data.cell.raw; // 检查是否包含<strong>标签 if (cellHtml.includes('<strong>')) { // 移除<strong>和</strong>标签,只保留文本内容 data.cell.text = cellHtml.replace(/<\/?strong>/g, ''); // 设置该单元格字体为加粗 data.cell.styles.fontStyle = 'bold'; } } });
完整代码
$(document).ready(function() { $('#download_PDF').click(function() { const table = localStorage.getItem('table'); const tableEl = document.createElement('div'); tableEl.innerHTML = table.trim(); const filename = 'test.pdf'; const doc = new jsPDF(); doc.autoTable({ html: tableEl.querySelector('table'), startY: 50, margin: { top: 10 }, didParseCell: function(data) { const cellHtml = data.cell.raw; if (cellHtml.includes('<strong>')) { data.cell.text = cellHtml.replace(/<\/?strong>/g, ''); data.cell.styles.fontStyle = 'bold'; } } }); doc.save(filename); }); });
原理说明
didParseCell是autotable的生命周期钩子,每个单元格解析完成后都会触发,允许你修改单元格的内容和样式。data.cell.raw存储了单元格的原始HTML内容,通过检查是否包含<strong>标签判断是否需要加粗。- 用正则表达式移除标签文本,避免PDF中显示
<strong>字样。 - 设置
fontStyle = 'bold'调用jsPDF默认的加粗字体样式,实现文本加粗效果。
内容的提问来源于stack exchange,提问作者Storm1
相关产品推荐
相关产品推荐

