从 node.js 向客户端发送 pdfkit 文档时出错
Error in sending pdfkit doc from node.js to client
我正在尝试将 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 作为我的后端框架。
当我尝试将文件写入服务器时,它会正常工作。但是我需要发送文件而不存储在服务器中。
我觉得问题在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)); at the start doc
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();
我正在尝试将 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 作为我的后端框架。 当我尝试将文件写入服务器时,它会正常工作。但是我需要发送文件而不存储在服务器中。
我觉得问题在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)); at the start doc
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();