score:4

Accepted answer

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.


Related Query

More Query from same tag