9

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.

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Looking at the node-html-pdf docs you would most likely what to utilise below: You could also set your response header:

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

Comments

0

I have done it like this https://stackoverflow.com/a/7288883/2045854 or https://stackoverflow.com/a/11944984/2045854

Step 1: read your PDF as a stream

Step 2: pipe it to a response

Regards

Remy

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.