Five Simple Steps to Convert Dashboard Charts Into PDFs

Written by maksymmostovyi | Published 2024/01/08
Tech Story Tags: front-end-development | web | charts | data-visualization | javascript | javascript-tutorial | javascript-development | javascript-data-visualization

TLDRLearn to quickly export dashboard charts to PDF using jsPDF with a few lines of JavaScript code.via the TL;DR App

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:

  1. Identifying the chart element.
  2. Transforming it into an image.
  3. Initializing jsPDF with a chosen orientation.
  4. Incorporating the image into the PDF in PNG format with appropriate dimensions.
  5. Finalizing the PDF.

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!


Written by maksymmostovyi | Software engineer with expertise in JavaScript, Angular, and React. One of my key skills is Data Visualisation.
Published by HackerNoon on 2024/01/08