To be honest, I googled a lot to learn something to fit in my context and after to consume, to read, and let some hairs on the way(Lol) I found a solution! (Inspired by Al Scoot)
There are some approaches to serve a PDF file through a Rest Express API, for example download method: send.download(filePath).
But when you need to serve a file in memory the problem becomes hard to solve and there aren't many developers talking about it.
const getPdfFile = async (req, res) => {
const { data } = await axios.get('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');
res.header('Content-disposition', 'attachment; filename=my-pdf.pdf');
res.header('Content-Type', 'application/pdf');
return res.send(data);
};
The problem is how axios handles the data response. How axios doesn't know what is coming it considers the return
as String but in this case, we need a Buffer.
We need to tell axios what's the content it's receiving and after that, the magic happens:
const getPdfFile = async (req, res) => {
const { data } = await axios.get('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', { responseType: 'arraybuffer' });
res.header('Content-disposition', 'attachment; filename=my-pdf.pdf');
res.header('Content-Type', 'application/pdf');
return res.send(data);
};