【问题标题】:Error in sending pdfkit doc from node.js to client将 pdfkit 文档从 node.js 发送到客户端时出错
【发布时间】:2021-09-02 07:02:23
【问题描述】:

我正在尝试将使用 node.js 中的 pdfkit 生成的 pdf 文件发送到客户端。

如果我的 pdf 包含任何图像,那么我的代码将给出以下错误。否则(没有任何图像),此代码将正常工作

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

这是我的代码

var doc = new PDFDocument({
              bufferPages: true,
            }),
    svg = mySvg;

SVGtoPDF(doc, svg, 0, 0);
let buffers = [];

doc.on("data", buffers.push.bind(buffers));
doc.on("end", () => {
    let pdfData = Buffer.concat(buffers);
    ctx.res
    .writeHead(200, {
        "Content-Length": Buffer.byteLength(pdfData),
        "Content-Type": "application/pdf",
        "Content-disposition": "attachment;filename=file.pdf",
    })
    .end(pdfData);
});
doc.end();

我使用strapi 作为我的后端框架。 当我尝试将文件写入服务器时,它会正常工作。但我需要发送文件而不存储在服务器中。

【问题讨论】:

    标签: node.js strapi pdfkit


    【解决方案1】:

    我认为 doc.pipe(ctx.res) 中的问题。尝试在.end(pdfData)

    之后添加
    res.writeHead(200, {
      'Content-Type': 'application/pdf',
      'Access-Control-Allow-Origin': '*',
      'Content-Disposition': `attachment; filename=${fileName}`,
    });
    
    doc.pipe(ctx.res);
    doc.end();
    
    

    对我来说它工作正常,但在 3-4 次下载后响应超时。将 doc.on("data", buffers.push.bind(buffers)); 移到起始文档处

    let buffers = [];
    doc.on('data', buffers.push.bind(buffers));
    
    /* doc body here */
    doc.text('pdf');
    doc.text('pdf2');
    doc.text('pdf3');
    
    doc.on('end', () => {
        const pdfData = Buffer.concat(buffers);
        res.writeHead(200, {
          'Content-Length': Buffer.byteLength(pdfData),
          'Content-Type': 'application/pdf',
          'Content-disposition': `attachment; filename=${filename}.pdf`,
          'Access-Control-Allow-Origin': '*',
        }).end(pdfData);
      });
    
    doc.end();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-16
      • 2015-10-07
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      相关资源
      最近更新 更多