Including charts in your PDF
External services
For simple charts, the fastest way to insert charts is to use external tools that will do the work for you.
Here we will provide an example using QuickChart but the same principles apply to any online service.
<img
src="https://quickchart.io/chart?width=500&height=300&c={
type: 'bar',
data: {
labels: ['January', 'February', 'March', 'April', 'May'],
datasets: [
{ label: 'Dogs', data: [50, 60, 70, 180, 190] },
{ label: 'Cats', data: [100, 200, 300, 400, 500] }
]
}
}">
Using dynamic data
You can use your dynamic data to generate the chart URL.
Using the example above, let’s move the series to the template’s sample data.
{
"labels": ["January", "February", "March", "April", "May"],
"series": [
{ "label": "Dogs", "data": [50, 60, 70, 180, 190] },
{ "label": "Cats", "data": [100, 200, 300, 400, 500] }
]
}
We can now use those data in our HTML. In order to get the data formatted as expected we will leverage the json
custom filter:
<img
src="https://quickchart.io/chart?width=500&height=300&c={
type: 'bar',
data: {
labels: {{labels | json | url_encode}},
datasets: {{series | json | url_encode}}
}
}">
Notice we also use the url_encode
filter since the data will be inserted directly in a URL.
Custom charts
For more complex scenarios you can use any JS library that can be accessed using an URL. Most of the libraries you can use provide a CDN version.
The following example will use ApexCharts as it’s free. Alternatives like uvCharts, Chart.js or D3.js are completely fine too.
<div id="chart"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script type="text/javascript">
let options = {
chart: {
type: 'bar',
height: 380,
width: '100%',
animations: { enabled: false },
toolbar: { show: false }
},
series: [
{ name: 'Dogs', data: [50, 60, 70, 180, 190] },
{ name: 'Cats', data: [100, 200, 300, 400, 500] }
],
axis: {
categories: ['January', 'February', 'March', 'April', 'May']
}
};
let chart = new ApexCharts(document.querySelector('#chart'), options);
chart.render();
</script>
Using dynamic data
The dynamic data passed to your document at generation will be avaiable in JavaScript using the $docPayload
variable. You can use it to make your chart dynamic:
<div id="chart"></div>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script type="text/javascript">
let options = {
chart: {
type: 'bar',
height: 380,
width: '100%',
animations: { enabled: false },
toolbar: { show: false }
},
series: $docPayload.series,
axis: { categories: $docPayload.labels }
};
let chart = new ApexCharts(document.querySelector('#chart'), options);
chart.render();
</script>
Legacy charts
The legacy PDF rendering engine included a superset of Chart.js v2.3 named monkeyCharts. The new rendering engine does not as it created confusion and did not offer much more than services like QuickChart.