Convert Pandas DataFrames to images using IMGKit

Andy Lane
Andy Lane
Dec 4, 2017 · 2 min read

Pandas is a wonderful Python tool for data analysis, and from time to time it’s nice to be able to integrate some Pandas tables into printed or PDF data products.

One simple approach is to generate CSS-styled HTML versions of Pandas DataFrames and “print” them to images. It’s possible to do this using IMGKit with minimal code, and it’s convenient because it leverages any existing knowledge of CSS layouts and styling that you may have.

What’s also convenient is that you get relatively bug-tested and predictable WebKit rendering — the same engine behind Chrome and Safari web page rendering — when your tables are output. This means that things like multi-line cells in tables, control over padding and advanced rules like alternating line colors should be dealt with somewhat elegantly.


(for recent Debian-like distros; for other environments see the project’s home page)
apt install wkhtmltopdf

pip install imagekit

Building the table

  1. First, build your dataset as a Pandas DataFrame. I used the biostats.csv sample CSV file from here:

2. Next, define a string containing some CSS to style your table. Note the triple quotes for pasting in multi-line string literals.

3. Concatenate the CSS and table data into a single file

4. Render the HTML to a file

5. Finally, marvel at the result

Image for post
Image for post

You can find a slightly nicer version of this approach in Jupyter Notebook form in the Github repo:

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store