0

I am creating a PDF file from HTML using html-pdf. Now I want to download the file on button click on HTML. I know how to ForceDownload a File. Now I want to know how I can force download the PDF file generated.

PDF generation Code:

var fs = require('fs'); var pdf = require('html-pdf'); var html = fs.readFileSync('PDF.html', 'utf8'); var options = { "height": "9in", // allowed units: mm, cm, in, px "width": "8in" ,orientation : "portrait","header": { "height": "5mm",border: { "top": "2in", // default is 0, units: mm, cm, in, px "right": "1in", "bottom": "2in", "left": "1.5in" }, "base": "", },}; pdf.create(html).toStream(function(err, stream){ stream.pipe(fs.createWriteStream('foo.pdf')); }); 

File Download Code:

var http = require('http'); http.createServer(function (req, res) { var text_ready = "This is a content of a txt file." res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=file.txt'}); res.end( text_ready ); }).listen(8080, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8080/'); 

Is there a way I can combine both of these? Or a better way to download the PDF file generated without saving it? I got both of them to work separately. I am pretty new to Node.js.

1 Answer 1

2

You can pipe your pdf to response since responce implements Writable Stream :

'use strict'; var http = require('http'); var fs = require('fs'); var pdf = require('html-pdf'); http.createServer(function (req, res) { fs.readFile('./PDFFormat.html', 'utf8', function (err, html) { if (err) { //error handling } pdf.create(html).toStream(function (err, stream) { if (err) { //error handling } res.writeHead(200, { 'Content-Type': 'application/force-download', 'Content-disposition': 'attachment; filename=file.pdf' }); stream.pipe(res); }); }); }).listen(8080, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8080/'); 
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain a little bit with a small example. I am new to this.
I updated my comment. Hope this helps. Check the node documentation as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.