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

使用PDFKIT和bwip-js生成条形码写入PDF时报stream.push after EOF错误求解

问题根因

你的错误来源于异步操作的时序问题:roshan()函数内部的条形码生成是异步任务,调用roshan()后代码不会等待任务执行完成,会直接执行后续的doc.end()关闭PDF输出流。等条形码生成完成、尝试往已关闭的流中写入图片内容时,就会触发stream.push() after EOF报错。
你删除doc.end()后不会触发写入关闭流的错误,但生成的PDF缺少文件尾部的必要结构,属于不完整文件,因此无法正常打开。

解决方法

等待所有异步写入操作全部完成后,再调用doc.end()关闭流即可,修改代码如下:

const PDFDocument = require('pdfkit');
const fs = require('fs');
const bwipjs = require('bwip-js');
// 建议将模块引用提到顶部,避免重复加载
const cdigit = require('cdigit');

// Create a document
const doc = new PDFDocument();

// Pipe its output somewhere, like to a file or HTTP response
doc.pipe(fs.createWriteStream('output.pdf'));

// Fit the image within the dimensions
doc.image('logo.jpg', 585, 5, {fit: [30, 30]})
  
//text containing name of the corp
doc
.fontSize(7)
.text("SpaceCode Solutions", 200, 40, {
  width: 410,
  align: 'right'
});

async function generateBarcode(text) {
  return new Promise((resolve, reject) => {
      bwipjs.toBuffer({
          bcid: 'code128',
          text,
          scale: 5,
          height: 10,
          includetext: false,
          textxalign: 'center'
      }, (err, png) => {
          if (err) reject(err);
          else resolve(png);
      });
  });
}

let unitId = 5;
let unitIdCheck = "Aman";
let x = 50;
let y = 90;

function checkTextSum(data) {
  let mChar = cdigit.mod37_2.generate(data);
  return mChar.charAt(mChar.length - 1);
}

async function roshan(){
  const barcode = await generateBarcode("=" + unitId);
  doc.image(barcode, x, y, {width: 200});
}

// 等待异步操作完成后再关闭文档
roshan()
.then(() => doc.end())
.catch(err => {
  console.error('PDF生成失败:', err);
  // 出错时也关闭流,避免文件句柄泄漏
  doc.end();
});

如果后续有多个异步生成的内容需要插入到PDF中,要保证所有异步任务都执行完成后再调用doc.end()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:54:03