I ended up to decode the pdf first and then send it to the browser as binary as follows:
(For simplicity I use node-http
here but the functions are available in express
as well)
const http = require('http');
http
.createServer(function(req, res) {
getEncodedPDF(function(encodedPDF) {
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="filename.pdf"'
});
const download = Buffer.from(encodedPDF.toString('utf-8'), 'base64');
res.end(download);
});
})
.listen(1337);
What drove me nuts here was the testing with Postman:
I was using the Send Button instead of the Send and Download Button to submit the request:
Using the Send button for this request causes that the pdf file becomes corrupted after saving.
res.write(fileBase64String, 'base64')
? – Wendelinres.end(fileBase64String, 'base64')
, which will both write the data and close the response. – Wendelin