I have a node API that consumes a module that returns a file buffer.
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
await createReport(null, 'Employee', (buffer) => {
console.log('buffer: ', buffer)
res.setHeader('Content-Type', 'application/pdf')
res.setHeader('Content-Disposition', 'attachment; filename=Employee.pdf')
res.send(buffer)
})
}
It's a PDF file Buffer is being returned from the module as
<Buffer 25 50 44 46 2d 31 2e 34 0a 31 20 30 20 6f 62 6a 0a 3c 3c 0a 2f 54 69 74 6c 65 20 28 fe ff 29 0a 2f 43 72 65 61 74 6f 72 20 28 fe ff 29 0a 2f 50 72 6f ... 99171 more bytes>
What I am missing here? I need to download this Pdf file as an attachment.
You need to trigger the download from your frontend, for example:
fetch('/report', {
method: 'GET',
})
.then((response) => response.blob())
.then((blob) => {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'Employee.pdf'
document.body.appendChild(a)
a.click()
a.remove()
})