[英]ExpressJS and PDFKit - generate a PDF in memory and send to client for download
[英]Generate pdf file using pdfkit and send it to browser in nodejs-expressjs
我正在使用 pdfkit 生成 pdf 文件,我想将此 pdf 文件发送到浏览器。
但我收到消息"TypeError: listener must be a function",
此外,文件正在我不想要的父目录中生成。
谁能解释我如何生成pdf文件并将其发送到浏览器而不将其存储在父目录中?
我在这里使用 expressjs。
var PDFDocument = require('pdfkit');
var fs=require('fs');
doc = new PDFDocument();
doc.moveTo(300, 75)
.lineTo(373, 301)
.lineTo(181, 161)
.lineTo(419, 161)
.lineTo(227, 301)
.fill('red', 'even-odd');
var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in...';
doc.y = 320;
doc.fillColor('black')
doc.text(loremIpsum, {
paragraphGap: 10,
indent: 20,
align: 'justify',
columns: 2
});
doc.write('out.pdf');
res.download('out.pdf');
doc.write
是引起问题的行,这也是一个不推荐使用的方法,所以不要使用它。 相反,使用管道告诉您的文档在哪里传输信息,并记住使用doc.end()
关闭它,即,像这样:
doc = new PDFDocument();
doc.pipe( fs.createWriteStream('out.pdf') );
// rest of the code goes here...
doc.end();
请注意, doc.pipe()
位于顶部并不重要,这对我来说很有意义(您可以将它放在doc.end()
之前或之后。没关系,它会工作得很好)。 最后,请注意,您可以使用pipe
直接流式传输到响应,无需先创建文件然后下载它,即:
doc.pipe( fs.createWriteStream(res) )
所以改为尝试使用
doc.pipe(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.