How do I send a chart in svg/png to PDFMake

Issue

I am using Apex Charts to show my data from API. I want to generate a PDF report of my chart and include its image. How should I do it?

This is my stackblitz demo:

https://stackblitz.com/edit/angular-wvjrwz?file=src/app/app.component.ts

Solution

You will need to convert your chart to an image and then you can insert the generated image in to the PDF.

Since you are using apex chart, which generates an SVG element that
represents the chart, you can use this element to create an Image out
of it. Please note that you need to pass correct selector of that
chart. Here I am passing .apexcharts-svg as the selector.

Below is how you can generate an image, this method returns a promise, which resolves to the image data url.

getBase64Image() {
    return new Promise((resolve, reject) => {
         const img = new Image();
         const svgElement: SVGGraphicsElement =
         document.querySelector('.apexcharts-svg');
         const imageBlobURL = 'data:image/svg+xml;charset=utf-8,' +
            encodeURIComponent(svgElement.outerHTML);
         img.onload = ()=> {
            var canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            const dataURL = canvas.toDataURL('image/png');
            resolve(dataURL);
         };
         img.onerror = (error) => {
           reject(error);
         };
         img.src = imageBlobURL;
       });
  }

next you can call this method to insert the image in PDF:

  async showPdf() {
    const docDefinition = {
      content: [
        {
          text: 'PDF Generated with Image from Chart',
          fontSize: 20,
        },
        {
          image: await this.getBase64Image(),
        },
      ],
    };
    pdfMake.createPdf(docDefinition).open();
  }

Check this fiddle: https://stackblitz.com/edit/angular-yuayja?file=src/app/app.component.ts

Answered By – Ritesh Waghela

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published