[Chartjs]-How to generate chartjs charts to pdf using laravel?

4👍

Your best bet is probably to render the chart as an image with a Javascript-enabled renderer, and then add that image to your PDF.

Option 1: If you want to stick with headless rendering, you may need to add a --no-stop-slow-scripts option in addition to the Javascript delay (could also check out Puppeteer, an alternative renderer).

Option 2: Use a service that renders charts to image or PDF.
QuickChart is an open-source web service that does this (I am one of its maintainers).

For example, take your Chart.js config:

$chartConfig = '{
  "type": "bar",
  "data": {
    "labels": [2012, 2013, 2014, 2015, 2016],
    "datasets": [{
      "label": "Users",
      "data": [120, 60, 50, 180, 120]
    }]
  }
}';

Pack it into a URL with the /chart endpoint:

$chartUrl = 'https://quickchart.io/chart?w=500&h=300&c=' . urlencode($chartConfig);

And then include the resulting URL as an image in your wkhtmltopdf page:

<img src="https://quickchart.io/chart?w=500&h=300&c=%7B%0A++%22type%22%3A+%22bar%22%2C%0A++%22data%22%3A+%7B%0A++++%22labels%22%3A+%5B2012%2C+2013%2C+2014%2C+2015%2C+2016%5D%2C%0A++++%22datasets%22%3A+%5B%7B%0A++++++%22label%22%3A+%22Users%22%2C%0A++++++%22data%22%3A+%5B120%2C+60%2C+50%2C+180%2C+120%5D%0A++++%7D%5D%0A++%7D%0A%7D" />

This will render your chart without any Javascript.

If you want an even simpler way and you’re ok with a PDF that shows only the chart, add &format=pdf to the URL and the service will directly generate a PDF of your chart: example PDF

Note that you can self-host the chart render web service if necessary.

Leave a comment