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

Time:09-23

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

CodePudding user response:

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

  • Related