【发布时间】:2015-09-24 17:00:16
【问题描述】:
我正在使用node-html-pdf 模块从我创建的ejs 模板生成PDF 文件,生成后,它会保存在我的服务器上。
现在这很完美,但我真正需要的是当我单击一个按钮时,它会生成 PDF 并下载文件,而不是保存它。
您可以在下面看到我必须生成并保存文件的代码:
var html = null;
ejs.renderFile('./templates/participants.ejs', {users: req.body.users, course: req.body.course, organization: req.body.organization}, function (err, result) {
if (result) {
html = result;
}
else {
res.end('An error occurred');
console.log(err);
}
});
pdf.create(html).toStream(function(err, stream){
var file = 'c:' + stream.path;
// var file = full path to tmp file (added 'c:' because I'm testing locally right now)
res.setHeader('Content-type', 'application/pdf');
res.setHeader('Content-disposition', 'attachment; filename=' + file);
res.download(file, req.body.course.name + '.pdf', function(err){
if (err) {
// Handle error, but keep in mind the response may be partially-sent
// so check res.headersSent
} else {
// decrement a download credit, etc.
}
});
});
我想也许我可以用.toStream 或.toBuffer 代替.toFile,但我对此并不陌生,在文档中它并没有真正解释.toStream 和.toBuffer 的工作原理(或确实)。我希望也许有人可以指出我正确的方向?或者至少判断这是否完全错误,我应该看看另一种解决方案。
更新
我现在尝试检查 @Remy 的链接,但没有运气(当我运行代码时没有任何反应,甚至没有错误),所以我用我的新代码更新了我的帖子(上图)。
我也尝试过@itaylorweb 答案,但结果相同,没有任何反应。
【问题讨论】:
标签: javascript node.js pdf pdf-generation