Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a pdf file from Node/Express app to the browser

In my Node/Express app I have the following code, which suppose to read a PDF document from a file, and send it to the browser:

var file = fs.createReadStream('./public/modules/datacollectors/output.pdf', 'binary'); var stat = fs.statSync('./public/modules/datacollectors/output.pdf'); res.setHeader('Content-Length', stat.size); res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf'); res.pipe(file, 'binary'); res.end();  

I do not get any errors, but I do not get the file in my browser either. What am I doing wrong?

like image 573
Eugene Goldberg Avatar asked Jun 28 '15 23:06

Eugene Goldberg


People also ask

How do you send a PDF through the app?

Send your documents with PDF software.Open the Acrobat app. Navigate to the PDF you wish to send. Tap the send icon on the top right portion of the screen. In the new dialog box, you have the option to share via email, or you can send a copy via AirDrop, Messages, or other third-party apps such as WhatsApp.


1 Answers

You have to pipe from Readable Stream to Writable stream not the other way around:

var file = fs.createReadStream('./public/modules/datacollectors/output.pdf'); var stat = fs.statSync('./public/modules/datacollectors/output.pdf'); res.setHeader('Content-Length', stat.size); res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf'); file.pipe(res); 

Also you are setting encoding in wrong way, pass an object with encoding if needed.

like image 88
hassansin Avatar answered Sep 22 '22 19:09

hassansin