i am struggling to display the PDF in the browser, although i am getting Base64 code and using onlinetool() i can see the code convert into the correct PDF file that is stored in the backed. After that i convert to blob Object and then it doesnt seems to open in the adobe reader when i click on the button.
// when the button is pressed, it will call the API to get the PDF document const headers = new Headers(); headers.append("content-type", "application/json"); headers.append("responseType", "arraybuffer"); const options = { method: "POST", headers, credentials: "include", body: JSON.stringify(invoice_Object), // body: "My HTML String", }; const newRequest = new Request("", options); (async () => { const invoice_Call = await fetch(newRequest) .then((res) => { return text1 = res.text(); }) .then((data) => { generateFile(data, invoice_Name);// here data is the actual item that i am looking to display as PDF document }); })(); };- Then it will open the PDF document in adobe reader, here the console
contentshows the correct Base64 code i think as seen when i use the code on online tool to convert to PDF document. So i am not sure if i am doing something wrong here generating the blob object and display as pdf.
let generateFile = (content, fileName) => { console.log("content", content); // here at console if i copy the code and use online tool() 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(); };- Backend code
fs.readFile(`${__dirname}\\` + `${Invoice_No_Actual}` + `.pdf`, (err, data) => { if (err) res.status(500).send(err); else { res.contentType("application/pdf"); res.send(`data:application/pdf;base64,${new Buffer.from(data).toString("base64")}`); } }); }- BI have also
uploadedthebase64 codethat i am getting when console logging at pastebin, - Error when opening the PDF document after i click the button
1 Answer
Your response type needs to be arraybuffer in order to create a blob out of it. Keep the content type of the blob as it is (application/pdf):
const headers = new Headers(); headers.append("content-type", "application/json"); headers.append("responseType", "arraybuffer");Edit: Please see my comments down below, it seems like you are parsing invalid base64
6