使用 pdfkit.from_file 将 html 转换为 pdf 时颜色消失

问题描述

我正在使用样式器为 Pandas 数据框添加颜色,然后将其另存为 html,结果如下:

enter image description here

颜色在 html 版本中,但是当我将文件转换为 PDF 时,它们丢失了。

enter image description here

我做错了什么?

这是可重现的代码

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')

解决方法

想通了。部分。每次设置背景时,我都必须添加 !important。示例|:

enter image description here

我的代码现在看起来像这样:

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()

pdf 看起来更接近我需要的:

enter image description here