Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download generated PDF using node-html-pdf module

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.

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.
        }
    });
});

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.

Update

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).

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

like image 338
Backer Avatar asked Jul 07 '15 09:07

Backer


1 Answers

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

Below is my code sample:

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

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.

like image 68
Fantasy Shao Avatar answered Sep 18 '22 14:09

Fantasy Shao