使用node-html-pdf模块下载生成的PDF
Download generated PDF using node-html-pdf module
我使用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的答案,但同样的结果,什么也没有发生。
我刚刚使用html-pdf
模块开发了一个功能。
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);
});
看看node-html-pdf文档,你最有可能在下面使用:你也可以设置你的响应头:
res.setHeader('Content-type', 'application/pdf');
pdf.create(html).toStream(function(err, stream){
stream.pipe(res);
});
我已经这样做了https://stackoverflow.com/a/7288883/2045854或https://stackoverflow.com/a/11944984/2045854
步骤1:以流形式读取PDF
步骤2:将其管道传输到响应
对
雷米相关文章:
- 如何使用javascript或html下载PDF格式的填写表单
- 在提交时打开thankyou.html+下载PDF
- 如何在不在本地下载的情况下将url中提供的文件(pdf/doc)转换为json/string/base64格式
- 下载HTML5/Javascript MOBILE应用程序中的PDF文件
- 下载所选语言的pdf文件
- CSV、PDF、Excel文件在dataTables的导出扩展中作为blob下载
- 如何在网络上下载pdf
- 使用window.print内容以pdf格式下载网页
- 将数据库中的数据转换为可下载的PDF文件
- 如何使用HtmlUnit下载PDF文件
- 如何使用JQuery禁用pdf文件下载选项
- 使用javascript压缩并下载多个PDF文档
- 如何创建和下载PDF和docx格式的文件,该文件将从AngularJS中的表中的数据创建
- 下载pdf格式不正确
- 将屏幕截图显示为pdf下载链接
- 如何通过ajax调用将pdf下载到nodejs服务器
- jsPDF输出PDF下载
- 自动为PDF下载添加唯一编号
- 当点击按钮时,强制PDF下载
- Laravel快速推送PDF下载