如何将 svg/png 中的图表发送到 PDFMake

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

我正在使用 Apex 图表显示来自 API 的数据。我想生成图表的 PDF 报告并包含其图像。我应该怎么做?

这是我的 stackblitz 演示:

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

您需要将图表转换为图像,然后才能将生成的图像插入到 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.

下面是生成图像的方法,此方法 returns 一个承诺,解析为图像数据 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;
       });
  }

接下来就可以调用这个方法插入PDF格式的图片了:

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

检查此 fiddle:https://stackblitz.com/edit/angular-yuayja?file=src/app/app.component.ts