Umair_007
Umair_007

Reputation: 143

base64 to PDF in ReactJS using API call

i am struggling to display the PDF in the browser, although i am getting Base64 code and using onlinetool(https://base64.guru/converter/decode/pdf) 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("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);// here data is the actual item that i am looking to display as PDF document
            });
        })();
      };

   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();
       };

     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")}`);
          }
        });
      }

enter image description here

Upvotes: 0

Views: 9213

Answers (2)

Shreya Haridas
Shreya Haridas

Reputation: 82

you can convert the base64 to blob

Easiest way, use the Fetch API to convert base64 to blob.

here's the code...

    const pdfstr = await fetch(pdf);   \\pdf is the base64 string
    const blobFromFetch= await pdfstr.blob();

  
    var blob = new Blob([blobFromFetch], {type: "application/pdf"});
    
    const blobUrl = URL.createObjectURL(blob);
  

  window.open(blobUrl,"_blank");

hope it helps!

Upvotes: 1

feedy
feedy

Reputation: 1150

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

Upvotes: 1

Related Questions