Nodejs pdfkit导出并支持中文

博客提供了msyh.ttf中文字体下载链接,可用于pdfkit导出PDF时解决中文显示问题,还给出了其他参考链接https://zhuanlan.zhihu.com/p/35753622 。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

var express = require('express');
var router = express.Router();
const PdfKit = require("pdfkit");
const fs = require("fs");
const { Writable } = require("stream");//引入stream中间件内置的写入流方法
router.get('/test/pdf', (req, res, next) => {
    const doc = new PdfKit();//初始化pdf对象
    const writeStream = new Writable();//初始化写入流对象
    const _chunkArr = [];//定义流数组
    writeStream._write = (chunk, encoding, callback) => {//流数据,编码格式,回调函数
        _chunkArr.push(chunk);//每次写入存在数组中
        callback(null);//默认返回null,没有异常
    };
    writeStream.on("finish", () => {//监听事件完成触发
        res.set("Content-Type", "application/pdf");//设置响应文本类型
        res.set("Content-Disposition", 'attachment; filename="test pdf-' + '.pdf"');//设置文件名称
        res.end(Buffer.concat(_chunkArr), "binary");
    }); 
    doc.pipe(writeStream);//pipe写入目标流
    //如果你想把文件保存在本地,则使用以下方式
    /**
     * const writeBuf = fs.createWriteStream("output.pdf");//建立可写流,并生成文件
     * doc.pipe(writeBuf);//将文件写入目标流
     */
    doc.font(`${__dirname}/msyh.ttf`)//设置字体样式,默认的pdfkit不支持中文,所以需要单独引入这个中文字体包,微软雅黑
        .fillColor("#FF0000")//设置文字颜色
        .fontSize(30)//设置文字大小
        .text("人物信息");//内容

    doc.fontSize(12)
        .fillColor("#000000")
        .text("姓名: 疾风剑豪")
        .text("年龄: 22岁")
        .text("场次: 9999")
        .text("家庭住址: 峡谷之巅");
    doc.image(`${__dirname}/cat.png`, { width: 1000, height: 1000 });
    doc.end();//触发完成
});

module.exports = router;

在这里插入图片描述
msyh.ttf 中文字体下载链接

//其他参考链接
https://zhuanlan.zhihu.com/p/35753622

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值