You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将svg/png格式的Apex Charts图表传入PDFMake生成PDF报告

Angular环境下Apex Charts导出到PDFMake生成含图表PDF的实现方案

1. 前置依赖安装

确保项目中已引入所需依赖,执行以下安装命令:

npm install apexcharts ng-apexcharts pdfmake --save

在Angular模块中引入NgApexchartsModule完成Apex Charts的初始化配置。

2. 获取Apex Charts的导出资源

Apex Charts自带导出API,无需额外引入DOM转图工具,通过组件内的ChartComponent实例即可调用:

  • 首先在组件代码中声明图表引用:
    import { ChartComponent } from "ng-apexcharts";
    @ViewChild("chart") chart: ChartComponent;
    

导出为PNG格式(兼容性更好)

调用异步方法dataURI()直接获取PNG的Base64编码:

this.chart.dataURI().then(({ imgURI }) => {
  // imgURI 为png格式的base64地址,可直接传入PDFMake
})

导出为SVG格式(清晰度更高)

调用sync()方法获取SVG字符串,转成Base64后即可使用:

const svgStr = this.chart.svg();
const svgBase64 = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgStr)));

3. 组装PDF并导出

将拿到的图片Base64填入PDFMake的文档定义中即可生成含图表的PDF:

import * as pdfMake from "pdfmake/build/pdfmake";
import * as pdfFonts from "pdfmake/build/vfs_fonts";
// 初始化PDFMake默认字体
(pdfMake as any).vfs = pdfFonts.pdfMake.vfs;

generatePdfReport() {
  this.chart.dataURI().then(({ imgURI }) => {
    const docConfig = {
      content: [
        { text: '业务数据报告', fontSize: 18, bold: true, margin: [0, 0, 0, 15] },
        { text: '指标趋势图', fontSize: 14, margin: [0, 10, 0, 8] },
        // 插入图表,可自定义width适配页面宽度
        { image: imgURI, width: 520 }
      ]
    };
    // 触发PDF下载
    pdfMake.createPdf(docConfig).download('业务数据报告.pdf');
  })
}

4. 常见问题适配

  • 导出图表空白:需监听Apex Charts的chartRendered事件,确认图表渲染完成后再执行导出逻辑
  • 中文显示乱码:需提前为PDFMake配置支持中文的字体资源,将字体转为vfs格式注入即可
  • 图片清晰度不足:优先选择SVG格式导出,矢量图不会出现缩放模糊问题

内容的提问来源于stack exchange,提问作者goodboidoggy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:06:06