3

i am struggling to display the PDF as attachment in ReactJS. i have managed to bring the base64 to the front end but after i try to create the blob object it doesn't work and although it goes to the Acrobat reader but shows the error. any suggestions please as how can i convert base64 to pdf correctly.

I have also uploaded the base64 code that i am getting when console logging at pastebin, https://pastebin.com/W4zEXyPy

Note: As when i try to repair at https://base64.guru/ it shows invalid strings and character(data:application/pdf;), i have tried to use content.slice(29); so it will start from JVB...(rather from data:application/pdf;base64,JVBERi0xL........) but getting the same error. Link to pic of Repair Base64 atbase64guru

Error: not decoded properly

  • 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 Front End- 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

        let content1= content.slice(29);// content1 is correct base64 as if i use it online tool it correctly generate the PDF document
        const blob = new Blob([content1], { type: "application/pdf" });
        console.log(blob);
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
      };

1
  • After i i use .slice method the string output when i use online tool is generate the correct PDF, so i think the problem is after it when i create the blob object but not sure exactly. Commented Aug 4, 2020 at 12:52

1 Answer 1

1

A simple console.log(content.slice(29)) could reveal your mistake. The problem is that the content1 variable contains a string that begins with "VBE…" while it must begin with "JVBE…". So, your mistake is that the slice() function discards too many characters.

Sign up to request clarification or add additional context in comments.

1 Comment

@umair Can you please share your final working code. I'm running into the exact same issue. My PDF is getting generated and downloaded but I cant open it. I get the same error you reported. I'm also using content.slice(0) and getting the full content into the blob.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.