In this guide, I'll demonstrate the surprisingly straightforward process of exporting charts from a Dashboard using a popular open-source JavaScript library and a few lines of code.
I began by designing a basic dashboard featuring three types of charts: a line chart, a bar chart, and a pie chart. While I opted for ChartJS for this project, other libraries like D3 or ECharts are also viable choices. Each chart widget in the dashboard includes a header button, which initiates the export process. Here's a glimpse of the dashboard setup:
The second phase involves setting up the export feature. For this, I selected jsPDF, a versatile open-source JavaScript library that facilitates the conversion of charts to PDF format.
This library is compatible with any JavaScript framework, though my example uses plain JavaScript.
We can integrate jsPDF into a project via CDN. The export functionality activates upon clicking the export button. The process is broken down into the following five steps:
The corresponding code snippet is as follows:
window.jsPDF = window.jspdf.jsPDF;
const exportChart = (id, dimensions) => {
const chartEl = document.getElementById(id);
const image = chartEl.toDataURL('image/png', 1.0);
const pdf = new jsPDF('landscape');
pdf.addImage(image, 'PNG', ...dimensions);
pdf.save('chart.pdf');
}
To streamline the process, I encapsulated these steps into a single function, eliminating redundant code. This function requires just the element's id and its dimensions as inputs. You can find the complete dashboard implementation on my GitHub page.
As evident, the implementation is concise, requiring just five lines of code. However, this example is quite basic. In a more complex scenario, we might need to add text, titles, pagination, etc. This can be achieved by consulting the jsPDF documentation.
I hope this brief tutorial proves useful. The best way to understand it is by trying it out yourself. Happy coding!