Search code examples
typescriptpdfmake

How to convert a image to base64 from a url typescript and store it in a string


I am using pdfmake and I would like to add my compagny logo in de pdf.

 getDocumentDefinition() {
    sessionStorage.setItem('resume', 'name');
    return {
      content: [
        {
          text: 'RESUME',
          bold: true,
          fontSize: 20,
          alignment: 'center',
          margin: [0, 0, 0, 20]
        },
        {
            image: getBase64FromUrl('https://localhost:44344/assets/images/logo.png'),
            width: 100,
            height: 100,
            alignment: 'left'
        },
      }
    };

Here is the function I would like to have in typescript I have tried many diffrent ways to create a base64 stream/string from a url but not of the solution work for me. The page is blank with the solution I have tried. How can a make it work for pdfmake. Thank you for your help.

function getBase64FromUrl(url) : string {

//Do some magic
//Return result

}

Solution

  • I found this solution online it worked for me.

    getBase64FromUrl(url) {
      return new Promise((resolve, reject) => {
        var img = new Image();
        img.setAttribute("crossOrigin", "anonymous");
    
        img.onload = () => {
          var canvas = document.createElement("canvas");
          canvas.width = img.width;
          canvas.height = img.height;
    
          var ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0);
    
          var dataURL = canvas.toDataURL("image/png");
    
          resolve(dataURL);
        };
    
        img.onerror = error => {
          reject(error);
        };
    
        img.src = url;
      });
    }