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

Download generated PDF using node-html-pdf module

本文关键字:PDF 下载 node-html-pdf 模块 使用      更新时间:2023-09-26

我使用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:将其管道传输到响应

雷米