color disappears when converting html to pdf with pdfkit.from_file

Viewed 308

I am using a styler to add color to a pandas dataframe, then I save it as html, and here's the outcome: enter image description here

The colors are here in the html version but when I convert the file to PDF they are lost. enter image description here

What am I doing wrong?

Here is reproducible code:

import pandas as pd
import pdfkit

# CREATE A DUMMY DF
d = {'population': [60, 46, 10], 'language': ['it', 'es', 'el']}
df = pd.DataFrame(data=d,index=['Italy','Spain','Greece'])

# ADD SOME COLORS
s = df.style.bar(subset=['population'], color=['#2ECC71'])

# WRITE AN HTML FILE
f = open('dummy.html','w')
f.write(s.render())
f.close()

# CONVERT THE FILE TO A PDF
pdfkit.from_file('dummy.html', 'dummy.pdf')
1 Answers

Figured it out. Partially. I had to add !important every time I was setting a background. Example|:

enter image description here

My code now looks like that:

import pandas as pd
import pdfkit

# CREATE A DUMMY DF
d = {'population': [60, 46, 10], 'language': ['it', 'es', 'el']}
df = pd.DataFrame(data=d,index=['Italy','Spain','Greece'])

# ADD SOME COLORS
s = df.style.bar(subset=['population'], color=['#2ECC71'])

# GET THE HTML STRING
my_html_string = s.render()

# ADD !important TO ALL THE BACKGROUND STATEMENTS
# locate all of them:
import re
p = re.compile('background: (.*);')
unique_bg_statements = list(set(p.findall(my_html_string)))
for bs in unique_bg_statements:
    my_html_string = my_html_string.replace(bs,bs+" !important") #add !important

# replace transparent with white:
my_html_string = my_html_string.replace("transparent","white")


# WRITE AN HTML FILE
f = open('dummy.html','w')
f.write(my_html_string)
f.close()

The pdf looks closer to what I need:

enter image description here

Related