I'm using ApexCharts to render graphs on user selection. I'm using React hooks. I want to have a button that will generate a PDF file from the current ( or multiple) graph. I have checked jsPDF and there is an example how to do that , but I'm unable to access my current rendered graph in order to create the PDF document. How can I access the current graph in order to create a PDF document while using hooks and dynamically rendering the graphs ?
Here is my code :
const defaultChartOptions = {
chart: {
id: '',
animations: {
enabled: false,
},
toolbar: {
export: {
csv: {
filename: '',
},
svg: {
filename: '',
},
png: {
filename: '',
},
},
},
},
dataLabels: {
enabled: false,
},
stroke: {
curve: 'smooth',
},
title: {
text: '',
align: 'center',
},
xaxis: {
type: 'datetime',
categories: [],
},
yaxis: {
labels: {
formatter: (val) => formatLabels(val),
},
},
noData: {
text: 'No data selected...',
},
markers: {
size: 0,
},
tooltip: {
x: {
format: 'dd/MM/yy HH:mm',
},
},
series: [],
};
const [options, setOptions] = useState(defaultChartOptions);
useEffect(() => {
if (storeId) {
const exportFileName = `${
data.number
}_store_${storeId}_${job.replaceAll(' ', '_')}`;
setOptions({
chart: {
...options.chart,
id: exportFileName,
toolbar: {
export: {
csv: {
filename: exportFileName,
},
svg: {
filename: exportFileName,
},
png: {
filename: exportFileName,
},
},
},
},
series: storeData[storeId].graphData.series,
xaxis: {
...options.xaxis,
categories: storeData[storeId].graphData.options.xaxis.categories,
},
title: {
...options.title,
text: exportFileName,
},
});
}
}, [storeId]);
And the Graph and Button :
<Button
label="Export to PDF"
size="small"
secondary
onClick={() => {
// How to get the chart by ID here in order to create the PDF doc ?
console.log(window); // OK
console.log(options.chart.id); // OK
console.log(window.ApexCharts.getChartByID(options.chart.id)); // <-- returns undefined
console.log(window.Apex._chartInstances); // <-- returns empty []
// const dataURL = chart.dataURI().then(({ imgURI, blob }) => {
// const { jsPDF } = window.jspdf;
// const pdf = new jsPDF();
// pdf.addImage(imgURI, 'PNG', 0, 0);
// pdf.save('pdf-chart.pdf');
// });
// console.log(dataURL);
}}
/>
<Chart
options={options}
series={options.series}
height="500px"
width="99%"
type="area"
/>