convert image to base64 in react for makePdf

Viewed 32

I'm trying to convert an image into base64 in react js to use in makePDF as a logo, when i create only with text it worked well but when i try the use an image return me the error, I am using this function:

        const getEmergencyFoundImg = urlImg => {
          var img = new Image();
          img.src = urlImg;
          img.crossOrigin = 'Anonymous';
        
          var canvas = document.createElement('canvas'),
            ctx = canvas.getContext('2d');
        
          canvas.height = img.naturalHeight;
          canvas.width = img.naturalWidth;
          ctx.drawImage(img, 0, 0);
        
          var b64 = canvas.toDataURL('image/png').replace(/^data:image.+;base64,/, '');
          return b64;
        };

and I'm calling this in the docDefinition like that:

    {
        image: getEmergencyFoundImg('./logoLM.png') 
    },

but when i create the pdf i get an error and only open a new tab without the document

Uncaught (in promise) Invalid image: File 'data:,' not found in virtual file system
Images dictionary should contain dataURL entries (or local file paths in node.js)

already tried other functions to convert that I found on searchs but none of that worked and always return this error.

And tried with link of image and de .png.

already try with this function too:

     const getBase64StringFromDataURL = (dataURL) =>
        dataURL.replace('data:', '').replace(/^.+,/, '');


        const getEmergencyFoundImg = urlImg => {
          var img = new Image();
          img.src = urlImg;
          img.crossOrigin = 'Anonymous';
        
          var canvas = document.createElement('canvas'),
          ctx = canvas.getContext('2d');
          console.log(canvas)

          const dataURL = canvas.toDataURL('image/png', 0.5);
          console.log(dataURL);

          const base64 = getBase64StringFromDataURL(dataURL);
          console.log(base64);
          return base64
        };
0 Answers
Related