Skip to content
  • System
  • Light
  • Dark
  • High contrast

Exporting charts

Export lives in its own entry, @eekodigital/raster/export, so apps that don’t export don’t bundle it (about 0.9 KB). Give the chart a ref and pass the element to exportSVG or exportPNG:

@eekodigital/raster/export
// target: the chart (its ref) or any element containing it. Filename defaults to "chart.svg".
function exportSVG(target: Element | null, filename?: string): void;
// Filename defaults to "chart.png", scale to 2.
function exportPNG(target: Element | null, filename?: string, scale?: number): Promise<void>;
Visitors this week

Line chart, 4 points. Mon to Thu. Values from 120 to 240.

050100150200250MonTueWedThu
Show data table
Data for Visitors this week
PeriodVisitors
Mon120
Tue180
Wed150
Thu240
import { useRef } from "react";
import { LineChart } from "@eekodigital/raster";
import { exportPNG, exportSVG } from "@eekodigital/raster/export";

export function VisitorsChart() {
  const chart = useRef<HTMLDivElement>(null);
  return (
    <LineChart
      ref={chart}
      series={series}
      categories={days}
      title="Visitors this week"
      actions={
        <>
          <button type="button" onClick={() => exportSVG(chart.current, "visitors.svg")}>
            Download SVG
          </button>
          <button type="button" onClick={() => exportPNG(chart.current, "visitors.png", 3)}>
            Download PNG
          </button>
        </>
      }
    />
  );
}

actions puts the buttons on the same row as Show data table. Every SVG chart takes a ref: it points at the chart’s figure (or, for Gauge and Sparkline, its root element). LinearGauge is HTML, not SVG, so it can’t be exported.

  • The chart’s <svg> is cloned, and the computed fill, stroke, font and opacity of every element are written onto the clone as attributes. That resolves --raster-* custom properties and the stylesheet, so the file looks the same outside your app, in the theme that was active when you exported.
  • exportPNG draws that SVG onto a canvas at scale times its on-screen size (2 by default, for sharp output on high-density screens) and downloads the result.
  • Only the <svg> is exported. The legend and tooltip are HTML outside it and aren’t included. Donut and Gauge centre content is HTML inside a <foreignObject>: it’s kept in SVG exports, but some browsers leave it out of PNGs.

Raster 4 removes the exportRef prop, so charts no longer carry export code. Swap it for a ref and call the functions:

const exportRef = useRef<ChartExportHandle>(null);
<LineChart exportRef={exportRef} … />
exportRef.current?.exportPNG("chart.png", 3);
import { exportPNG } from "@eekodigital/raster/export";
const chart = useRef<HTMLDivElement>(null);
<LineChart ref={chart} … />
exportPNG(chart.current, "chart.png", 3);