3

I have a base 64 string that is coming from an API call. I am testing with a sample base64 string and I am trying to convert it to pdf or an image to view in my react.js website.

I've tried many solutions, but nothing seems to work. I found a react js package that is called base64topdf I installed it and tried to decode the base64 string to PDF, but it gives me this error "TypeError: fs.writeFileSync is not a function"

I don't know what i am doing wrong.

How can I convert a base64 string to a PDF or an image in reactjs?

Documentation to the package https://www.npmjs.com/package/base64topdf

Here is my code:

 const base64 = require('base64topdf');

 const base64STR = "JVBERi0xLjQKJeLjz9M...." //base64 string

 const decodedBase64 = base64.base64Decode(base64STR, 'waybill');

 console.log(decodedBase64)
motionless570
  • 925
  • 1
  • 10
  • 26

3 Answers3

4

try this <embed src={`data:application/pdf;base64,${base64STR}`} />

AKAA
  • 136
  • 4
3

You cannot use this package, since it is written for Node.js not for web development. If you go inside the package source code you will see that it is using the fs module or file system.

https://github.com/rpsankar001/base64topdf/blob/master/index.js#L3


For the web, you can use something like this:

function downloadPDF(pdf) {
    const linkSource = `data:application/pdf;base64,${pdf}`;
    const downloadLink = document.createElement("a");
    const fileName = "file.pdf";

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();
}

Worth mentioning, React has an upcoming feature called Server Components, that will allow you to use server-side code with React. It seems that in the near future you will be able to use the package.

See: https://reactjs.org/blog/2020/12/21/data-fetching-with-react-server-components.html

Abraham
  • 8,525
  • 5
  • 47
  • 53
-1

It seems that the functions base64Decode and base64Encode should be used in NodeJS only, your React env should not be able to access fs or Buffer.

Look at he file here: https://github.com/rpsankar001/base64topdf/blob/master/index.js

Also this package seems very empty, I would prefer const decodedBase64 = atob("JVBERi0xLjQKJeLjz9M...."); //base64 string

karkael
  • 431
  • 2
  • 9