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

如何通过JS代码将HighchartsReact图表导出为PNG/SVG/IMG格式

解决Highcharts React图表导出为图片的问题

核心前提:加载导出模块

Highcharts的导出功能(包括getSVG()、exportChart())依赖官方的exporting模块,必须先导入并初始化,否则相关方法会不存在。

import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
// 导入导出相关模块
import exportingModule from 'highcharts/modules/exporting';
import exportDataModule from 'highcharts/modules/export-data';

// 初始化模块,绑定到Highcharts实例
exportingModule(Highcharts);
exportDataModule(Highcharts);

方法一:用Highcharts内置导出方法(最简单)

直接调用图表实例的exportChart()方法,一键导出为指定格式(png/jpg/svg等),无需手动处理SVG转图片:

const App = () => {
  const chartComponent = useRef(null);

  const printChartAsImage = () => {
    const chart = chartComponent.current.chart;
    // 调用内置导出方法,指定格式和文件名
    chart.exportChart({
      type: 'image/png', // 可选格式:image/png, image/jpeg, application/pdf, image/svg+xml
      filename: 'my-highcharts-chart'
    });
  };

  return (
    <>
      <button onClick={printChartAsImage}>导出为PNG</button>
      <HighchartsReact
        highcharts={Highcharts}
        options={chartOptions}
        ref={chartComponent}
      />
    </>
  );
};

方法二:手动处理SVG转图片(自定义场景)

如果需要自定义导出逻辑(比如生成base64图片、嵌入到其他组件),可以用getSVG()获取SVG字符串后转成图片:

const printChartAsImage = () => {
  const chart = chartComponent.current.chart;
  if (!chart) return;

  // 获取图表的SVG字符串
  const svgString = chart.getSVG();
  // 将SVG转为Blob对象
  const svgBlob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });
  const svgUrl = URL.createObjectURL(svgBlob);

  const img = new Image();
  img.onload = () => {
    // 创建Canvas绘制图片
    const canvas = document.createElement('canvas');
    canvas.width = chart.chartWidth;
    canvas.height = chart.chartHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);

    // 转为PNG格式的base64链接
    const pngUrl = canvas.toDataURL('image/png');
    // 创建下载链接并触发下载
    const downloadLink = document.createElement('a');
    downloadLink.href = pngUrl;
    downloadLink.download = 'custom-chart.png';
    downloadLink.click();

    // 释放URL资源,避免内存泄漏
    URL.revokeObjectURL(svgUrl);
    URL.revokeObjectURL(pngUrl);
  };
  img.src = svgUrl;
};

常见问题说明

  • 若提示getSVG()不存在:100%是未加载exporting模块,检查导入和初始化代码;
  • chartComponent.current.chart是真实的Highcharts图表实例,并非Highcharts-React的包装实例,只要模块加载正确,就能调用所有Highcharts原生方法;
  • 支持的导出格式:image/png、image/jpeg、application/pdf、image/svg+xml,对应exportChart()的type参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:01:34