I manage to find an answer for this.
It's a combination of this and this.
But just to give an overview/key codes. In my react application, I have this (make a post request to my API server):
<Button
onClick={(e) => {
const { _id } = record;
fetch(`/api/pdf`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
filename: "test",
content: "Testing Content"
}),
}).then(async res => {
if (res.status === 200) {
const blob = await res.blob();
const file = new Blob(
[blob],
{type: 'application/pdf'}
);
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
}
})
>
Download
</Button>
And in the API server (node express application), I have this:
const postMethod = () => async (req, res, next) => {
const doc = new PDFDocument()
let filename = req.body.filename
// Stripping special characters
filename = encodeURIComponent(filename) + '.pdf'
// Setting response to 'attachment' (download).
// If you use 'inline' here it will automatically open the PDF
res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"')
res.setHeader('Content-type', 'application/pdf')
const content = req.body.content
doc.y = 300
doc.text(content, 50, 50)
doc.pipe(res)
doc.end()
}