使用pdfkit生成pdf文件并将其发送到nodejs-expressjs中的浏览器 [英] Generate pdf file using pdfkit and send it to browser in nodejs-expressjs
问题描述
我正在使用pdfkit生成pdf文件,我想将此pdf文件发送到浏览器.
但我收到消息"TypeError: listener must be a function",
另外,我不需要的文件在我的父目录中生成.
有人可以解释我如何生成pdf文件并将其发送到浏览器而不将其存储在父目录中吗?
我在这里使用expressjs.
I am using pdfkit to generate pdf file and i want to send this pdf file to browser.
But i am getting message "TypeError: listener must be a function",
Also, file is getting generate in my parent directory which i don't want.
Can anyone explain me how to generate pdf file and send it to browser without storing it at parent directory?
I am using expressjs here.
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.write
is the line causing the trouble, which is also a deprecated method so don't use it. Instead, use pipe to tell your doc where to stream the information, and remember to close it using doc.end()
, i.e., like so:
doc = new PDFDocument();
doc.pipe( fs.createWriteStream('out.pdf') );
// rest of the code goes here...
doc.end();
请注意,将doc.pipe()
放在顶部并不重要,这对我来说很有意义(您可以将其放在doc.end()
之前或之后.没关系,这样就可以了).最后,请注意,您可以使用pipe
直接流式传输到响应,无需先创建文件然后下载,即:
Note that it's not important that doc.pipe()
be at the top, it just makes sense to me (you can put it before or after doc.end()
. It doesn't matter, it'll work just fine). Finally, note that you can use pipe
to stream directly to a response, there's no need to create the file first and then download it, i.e.:
doc.pipe( fs.createWriteStream(res) )
这篇关于使用pdfkit生成pdf文件并将其发送到nodejs-expressjs中的浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!