i am struggling to display the PDF as attachment in ReactJS. i have managed to bring the base64 to the fornt end but after i try to create the blob object it doesnt work and although it goes to the Acrobate reader but shows the error. any suggestions please as how cna i convert base64 to pdf correctly.
- NodeJS baackend code responding to API call
let token = req.cookies.access_token;
if (token) {
let Invoice_No_Actual = req.body.invoice_Name;
res.set("Content-disposition", "attachment; filename=" + `${__dirname}\\` + `${Invoice_No_Actual}` + `.pdf`);
res.contentType("application/pdf");
res.send(`data:application/pdf;base64,${new Buffer.from(data).toString("base64")}`);
}
});
- Frontend code API call
const headers = new Headers();
headers.append("content-type", "application/json");
headers.append("responseType", "application/pdf");
const options = {
method: "POST",
headers,
credentials: "include",
body: JSON.stringify(invoice_Object),
// body: "My HTML String",
};
const newRequest = new Request("http://localhost:5000/api/invoice-only", options);
(async () => {
const invoice_Call = await fetch(newRequest)
.then((res) => {
return text1 = res.text();
})
.then((data) => {
generateFile(data, invoice_Name);
});
})();
};
- generateFile() function call after receiving the response
let generateFile = (content, fileName) => {
console.log("content", content); // here at console if i copy the code and use online tool(https://base64.guru/converter/decode/pdf) it shows the correct pdf
const blob = new Blob([content], { type: "application/pdf" });
console.log(blob);
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
};
*Below error comes up when try to open the pdf