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;
//其他参考链接
https://zhuanlan.zhihu.com/p/35753622