使用node-html-pdf模块下载生成的PDF

我正在使用node-html-pdf模块从我创build的ejs模板生成一个PDF文件,生成后它会保存在我的服务器上。

现在这个工作完美,但我真正需要的是当我点击一个button,它会生成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如何工作(或做)。 我希望也许有人能把我指向正确的方向? 或者至less说明这是完全错误的,我应该看看另一个解决scheme。

更新

我现在试图检查@雷米的链接,但没有运气(没有发生,甚至没有一个错误,当我运行的代码),所以我已经用我的新代码(上面)更新我的职位。

我也尝试了@itaylorweb的答案,但结果相同,没有任何反应。

我做了这样的https://stackoverflow.com/a/7288883/2045854或https://stackoverflow.com/a/11944984/2045854

第1步:读取您的PDF作为一个stream

第2步:pipe它到一个响应

问候

雷米

查看node-html-pdf文档,您最有可能在下面使用:您也可以设置您的响应标题:

 res.setHeader('Content-type', 'application/pdf'); pdf.create(html).toStream(function(err, stream){ stream.pipe(res); }); 

我刚刚开发了一个使用html-pdf模块的function。

以下是我的代码示例:

 pdf.create(html).toBuffer(function (err, buffer) { if (err) return res.send(err); res.type('pdf'); res.end(buffer, 'binary'); }); 

或者你可以像这样使用Stream:

 pdf.create(html).toStream(function (err, stream) { if (err) return res.send(err); res.type('pdf'); stream.pipe(res); }); 

希望它会帮助你。