使用node-html-pdf模块下载生成的PDF [英] Download generated PDF using node-html-pdf module

查看:240
本文介绍了使用node-html-pdf模块下载生成的PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using node-html-pdf module to generating a PDF file from an ejs template I've created, which after it is generated, it gets saved on my server.

现在这非常有效,但我真正需要的是当我点击一个按钮时,它会生成PDF并下载文件,而不是保存它。

Now this works perfectly, but what I really need is when I click a button, it generates the PDF and downloads the file, instead of saving it.

下面你可以看到代码我必须生成并保存文件:

Below you can see the code I have to generate and save the file:

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 的工作原理(或确实如此)。我希望也许有人可以指出我正确的方向?或者至少告诉我这是否完全错误,我应该看看另一个解决方案。

I thought that maybe I could you .toStream or .toBuffer instead of .toFile, but I'm quit new at this and in the documentation it doesn't really explain how .toStream and .toBuffer works (or does). I hope maybe somebody could point me in the right direction? Or at least tell if this is totally wrong and I should look at another solution.

更新

我现在已经尝试检查@Remy的链接但没有运气(没有任何反应,甚至没有错误,当我运行代码时),所以我用我的新代码更新了我的帖子(上图)。

I have now tried to checked out @Remy's links but without luck (nothing happens, not even an error, when i run the code), so I have updated my post with my new code (above).

我也试过@itaylorweb回答,但结果相同,没有任何反应。

I have also tried @itaylorweb answer, but with same result, nothing happens.

推荐答案

我刚刚使用 html-pdf 模块开发了一个功能。

I've just developed a feature using html-pdf module.

以下是我的代码示例:

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

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

Or you could use Stream like this:

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

希望它能为您提供帮助。

Hope it will help you.

这篇关于使用node-html-pdf模块下载生成的PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆