Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid image error using dataUrl in pdfmake

I'm using pdfmake to generate a PDF doc in an angular app, and just trying to add an image to the output using a dataURL (following the pdfmake docs.

        var docDefinition = {
          content: [
            {
              table: {
                widths: ['*'],
                body: [
                  [{text: 'Table text goes here', style: 'tableCellPadded'}]
                ]
              },
            },
            {
              image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJgAAACHCAYAAADqQ...AABJRU5ErkJggg==",
              width: 152
            }
            '...various other text lines go here...'
          ],
          styles: {
            header: {
              bold: true,
              fontSize: 14
            },
            tableCellPadded: {
              margin: [0, 15, 0, 15],
              bold: true,
              fontSize: 14
            },
            note: {
              fontSize: 16,
              bold: true,
              italics: true
            }
          }
        };

However, when I attempt to print out the doc, I get this error in my console:

invalid image, images dictionary should contain dataURL entries (or local file paths in node.js)

As best as I can tell, I have the item entered correctly in the doc definition object, and my dataURL is valid (I've tested it in my browser). Is there something else I'm missing?

Thanks.

like image 899
wonder95 Avatar asked Apr 11 '17 18:04

wonder95


2 Answers

OK, I'm chalking this one up to an ID-10-T error. My line with the base64 encoded URL is working fine. I found another line farther down in my doc definition object where I wasn't referring to the image properly, and that one was throwing the error.

like image 90
wonder95 Avatar answered Nov 10 '22 03:11

wonder95


you can try like this. and it will work fine. Don't forget to vote up

getBase64ImageFromURL(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;
  });
}
async createPdf() {
  var docDefinition = {
    content: [
      {
        image: await this.getBase64ImageFromURL("../../assets/ribbonLogo1.png")
       },
like image 2
Satyajit Behera Avatar answered Nov 10 '22 04:11

Satyajit Behera