tys
tys

Reputation: 3

Can't force the pdf download with express.js

I'm using express.js with pdfkit, trying to generate a pdf and force a download in a webbrowser.

I defined static location where the pdf is stored, but when I want to read this location and download the file nothing happens. I've tried also setting headers, but that didn't work.

I've read that that may have something to do with the ports on which server and front-end is running. In my case these are: 4200 (Angular) and 8080 (Node.js)

Here is fragment of the server code:

var downl = doc.pipe(fs.createWriteStream('C:/Users/Martyna/Desktop/test pdfow/out.pdf') );

doc.end();

downl.on('finish', function() {
    res.download('C:/Users/Martyna/Desktop/test pdfow/out.pdf', 'out.pdf');
})

Upvotes: 0

Views: 2383

Answers (2)

Aref.T
Aref.T

Reputation: 49

You can do it simply with just reading file and sending it as a response. this code works for me!

fs.readFile('C:/Users/Martyna/Desktop/test pdfow/out.pdf',(err,data)=>{
if(err){
  consol.log(err);
}else {
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=your_file_name_for_client.pdf');

res.send(data)
}
})  

Upvotes: -1

Sanjay Achar
Sanjay Achar

Reputation: 408

You need to add the below headers to your response. To have the file downloaded rather than viewed

Content-Type: application/pdf
Content-Disposition: attachment; filename="You_File_Name.pdf"

To indicate to the browser that the file should be viewed in the browser:

Content-Type: application/pdf
Content-Disposition: inline; filename="You_File_Name.pdf"

Upvotes: 2

Related Questions