paint-brush
Five Simple Steps to Convert Dashboard Charts Into PDFsby@maksymmostovyi
184 reads

Five Simple Steps to Convert Dashboard Charts Into PDFs

by Maksym Mostovyi January 8th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Learn to quickly export dashboard charts to PDF using jsPDF with a few lines of JavaScript code.

Company Mentioned

Mention Thumbnail
featured image - Five Simple Steps to Convert Dashboard Charts Into PDFs
Maksym Mostovyi  HackerNoon profile picture

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!