图表导出
Graphic Walker 通过 IGWHandler ref 提供编程式的图表导出功能。可以导出单个图表,也可以遍历工作簿中的所有图表。
设置
通过 React ref 访问导出 API:
import { useRef } from 'react';
import { GraphicWalker } from '@kanaries/graphic-walker';
import type { IGWHandler } from '@kanaries/graphic-walker';
function App() {
const gwRef = useRef<IGWHandler>(null);
return (
<GraphicWalker
ref={gwRef}
data={data}
fields={fields}
/>
);
}导出当前图表
使用 exportChart() 导出当前显示的图表:
async function handleExport() {
if (!gwRef.current) return;
// Export as SVG (default)
const svgResult = await gwRef.current.exportChart('svg');
// Export as data URL (base64 PNG)
const pngResult = await gwRef.current.exportChart('data-url');
}导出结果结构
IChartExportResult 包含:
| 属性 | 类型 | 说明 |
|---|---|---|
mode | 'svg' | 'data-url' | 导出格式 |
title | string | 图表名称 |
nCols | number | 分面列数 |
nRows | number | 分面行数 |
charts | Array | 图表面板数组 |
charts[].data | string | SVG 标记或 data URL 字符串 |
charts[].width | number | 图表宽度 |
charts[].height | number | 图表高度 |
charts[].canvas() | Function | 返回 canvas/SVG DOM 元素 |
container() | Function | 返回图表容器元素 |
chartType | string | 几何类型 |
导出所有图表
使用 exportChartList() 遍历工作簿中的所有图表。它返回一个 AsyncGenerator:
async function exportAll() {
if (!gwRef.current) return;
for await (const item of gwRef.current.exportChartList('svg')) {
console.log(`Exporting chart ${item.index + 1} of ${item.total}`);
console.log('Title:', item.data.title);
console.log('SVG:', item.data.charts[0]?.data);
// item.hasNext tells you if more charts follow
}
}下载为 SVG 文件
async function downloadSVG() {
if (!gwRef.current) return;
const result = await gwRef.current.exportChart('svg');
const svgData = result.charts[0]?.data;
if (!svgData) return;
const blob = new Blob([svgData], { type: 'image/svg+xml' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${result.title || 'chart'}.svg`;
link.click();
URL.revokeObjectURL(url);
}下载为 PNG 文件
async function downloadPNG() {
if (!gwRef.current) return;
const result = await gwRef.current.exportChart('data-url');
const dataUrl = result.charts[0]?.data;
if (!dataUrl) return;
const link = document.createElement('a');
link.href = dataUrl;
link.download = `${result.title || 'chart'}.png`;
link.click();
}检查渲染状态
在导出之前,可以检查图表是否已准备就绪:
async function safeExport() {
if (!gwRef.current) return;
// Wait for idle status
if (gwRef.current.renderStatus !== 'idle') {
await new Promise<void>(resolve => {
const dispose = gwRef.current!.onRenderStatusChange(status => {
if (status === 'idle') {
dispose();
resolve();
}
});
});
}
return gwRef.current.exportChart('svg');
}导出前切换图表
在导出之前切换到指定的图表标签页:
// Export the third chart
gwRef.current.openChart(2); // 0-indexed
// Wait for render, then export
const result = await safeExport();