【问题标题】:Download generated PDF using node-html-pdf module使用 node-html-pdf 模块下载生成的 PDF
【发布时间】: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


    【解决方案1】:

    我刚刚使用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);
    });
    

    希望对你有所帮助。

    【讨论】:

      【解决方案2】:

      查看 node-html-pdf 文档,您很可能会使用以下内容: 您还可以设置响应标头:

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

      【讨论】:

        【解决方案3】:

        我已经这样做了 https://stackoverflow.com/a/7288883/2045854https://stackoverflow.com/a/11944984/2045854

        第 1 步:以流的形式阅读您的 PDF

        第 2 步:将其传递给响应

        问候

        雷米

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-01-13
          • 2017-12-07
          • 1970-01-01
          • 2011-12-17
          • 1970-01-01
          • 1970-01-01
          • 2015-11-15
          • 1970-01-01
          相关资源
          最近更新 更多