Skip to content

服务端生成PDF文件(支持中文)

PDFKit 添加支持中文的字体

背景:因为 PDFKit 默认字体不支持中文字符。

解决方案:所以需要添加特定的字体文件(嵌入到代码中去)。

1. 找字体文件

找到需要嵌入到字体文件:比如,https://github.com/820465323/msyh.ttf。

2. 字体嵌入(具体代码)

js
const doc = new PDFDocument({ size: 'A4', margin: 40 });
// 注册中文字体(我是直接把字体文件放在 controllers 文件夹里面)
doc.registerFont('SourceHanSansCN', path.resolve(__dirname, './msyh.ttf'));
doc.font('SourceHanSansCN');

res.setHeader('Content-Type', 'application/pdf; charset=utf-8');
res.setHeader('Content-Disposition', 'attachment; filename=chinese_words.pdf');
doc.pipe(res);

// 标题
doc.fontSize(18).text(`第 ${unit} 单元 汉字练习表`, { align: 'center' });
doc.moveDown(2);
// 其他代码(略)

3. 参考网址

https://bbs.itying.com/topic/67ab92a536bb8501316d7733