1👍
✅
There are a couple ways to generate images from a Chart.js chart from Python.
-
Use toBase64Image from the Chart.js API to generate an image of your chart and send it to your server to be emailed. This solution requires a client to load every chart before it needs to be emailed (can’t be done in Django only).
-
Use pyppeteer, a Python driver for Puppeteer, which is a headless browser. In this case, you may load your page containing the chart and then screenshot it:
browser = await launch()
page = await browser.newPage()
await page.goto('http://example.com/path/to/chart')
await page.screenshot({'path': 'chart.png'})
await browser.close()
This should work just fine but is a somewhat heavyweight solution, and requires that you render locally on the web server unless you set up some worker infrastructure.
- Use a web service like QuickChart to handle the rendering for you (note that I built this, but it’s open source and can be self-hosted). This works by taking your Chart.js config and sending it to a web service:
import json
from urllib.parse import quote
import requests
# Set up the chart.js config. This can either be a string or python dict.
chart_config = {
'type': 'bar',
'data': {
'labels': ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
'datasets': [{
'label': 'Retweets',
'data': [12, 5, 40, 5]
}, {
'label': 'Likes',
'data': [80, 42, 215, 30]
}]
}
}))
# Convert the python dict to a string and URL-encode it
encoded_config = quote(json.dumps(chart_config))
# Download chart
chart_url = f'https://quickchart.io/chart?c={encoded_config}'
f = requests.get(chart_url, stream=True)
if r.status_code == 200:
with open('/tmp/chart.png', 'wb') as f:
for chunk in r:
f.write(chunk)
There is also a Python client that you may use.
Source:stackexchange.com