You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pdfKit中生成Base64字符串?当前返回PDF Blob而非Base64

问题

希望获取PDF的Base64编码字符串而非Blob格式,但当前实现无效,前端接收到的是PDF Blob。代码实现如下:

const pdfName = "cv123.pdf";
const pdfPath = path.join('data', pdfName)
const pdfDoc = new PDFDocument();
pdfDoc.pipe(fs.createWriteStream(pdfPath, {encoding: "base64"}));
pdfDoc.pipe(res)
pdfDoc.text("TEST").fontSize(20)
pdfDoc.end();
解决方案

问题根源在于:直接pipe(res)会返回PDF二进制数据流(即Blob),而给本地文件流设置base64编码仅作用于本地写入,不影响响应内容。

修改方案如下:

  • 先捕获PDF文档的二进制数据,再转换为Base64字符串
  • 响应时设置正确的Content-Type,告知前端返回的是文本格式的Base64

修改后的代码:

const pdfDoc = new PDFDocument();
const dataChunks = [];

// 收集PDF二进制数据块
pdfDoc.on('data', chunk => dataChunks.push(chunk));
pdfDoc.on('end', () => {
  // 合并数据并转Base64
  const base64Str = Buffer.concat(dataChunks).toString('base64');
  // 设置响应头
  res.setHeader('Content-Type', 'text/plain');
  // 返回Base64字符串
  res.send(base64Str);
});

// 生成PDF内容
pdfDoc.text("TEST").fontSize(20);
pdfDoc.end();

如果不需要保存本地PDF文件,可删除与fs.createWriteStream相关的代码,减少不必要的磁盘IO。若需保存本地,可在end事件内完成文件写入,避免重复pipe操作。

内容的提问来源于stack exchange,提问作者Pentium3k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:35:23