React中用jsPDF+pdf-autotable生成阿英双语PDF失败求助
问题排查与修复方案
针对你用jsPDF和pdf-autotable生成含阿拉伯语+英语PDF的问题,从代码里能看出几个关键问题,以下是修复后的代码和对应说明:
核心问题点与修复
- 字体注册参数错误:
addFont的第一个参数必须是你添加到VFS的文件名(即'Amiri-Regular.ttf'),而非字体名 - 字体样式配置错误:
headStyles和bodyStyles里应该用font指定字体名,fontStyle是用来设置加粗/斜体这类样式的 - 阿拉伯语RTL方向缺失:阿拉伯语是从右到左书写,需要手动设置文本方向和单元格对齐方式
修复后的完整代码
const exportToPdf = (demographicsInfo) => { const pdf = new jsPDF(); const lineHeight = 10; let currentY = lineHeight; // 正确注册字体:VFS文件名、字体名、字体样式 pdf.addFileToVFS('Amiri-Regular.ttf', amiriFont); pdf.addFont('Amiri-Regular.ttf', 'Amiri', 'normal'); // 全局设置字体 pdf.setFont('Amiri', 'normal'); pdf.autoTable({ startY: currentY, head: [['Key', 'Value']], headStyles: { font: "Amiri", // 用font指定字体名 halign: 'left' // 英语表头左对齐 }, bodyStyles: { font: "Amiri", // 针对阿拉伯语内容设置右对齐,英语内容自动适配 halign: (data) => typeof data.cell.raw === 'string' && /[\u0600-\u06FF]/.test(data.cell.raw) ? 'right' : 'left' }, body: Object.keys(demographicsInfo).map((key) => [key, demographicsInfo[key]]), }); pdf.save('exportedData.pdf'); };
额外注意事项
- 确保
amiriFont变量确实是正确的Base64编码内容,没有截断或格式错误 - 如果阿拉伯语文字仍显示异常,可尝试在
autoTable的didParseCell钩子中手动处理:
didParseCell: (data) => { if (/[\u0600-\u06FF]/.test(data.cell.raw)) { data.cell.text = pdf.splitTextToSize(data.cell.raw, data.cell.width); data.cell.halign = 'right'; } }
内容的提问来源于stack exchange,提问作者imLohith
相关产品推荐
相关产品推荐

