要实现html网页,excel文件转成pdf格式的文档,在 python 中要借助 pdfkit
这个库,而pdfkit
这个库底层依赖 wkhtmltopdf
软件,好在wkhtmltopdf
这个软件是跨平台的,提供了不同平台的安装包。
wkhtmltopdf 软件的安装
- Debian/Ubuntu 平台
sudo apt-get install wkhtmltopdf
- Redhat/CentOS
sudo yum install wkhtmltopdf
- MacOS
下载链接: https://pan.baidu.com/s/14MIsf6c3_biq8rWG9iRwAQ 提取码: retm
安装python依赖包
pip install pdfkit
检测(wkhtmltopdf)是否安装成功
which wkhtmltopdf
# 如果能显示路径说明安装成功
image.png
如何转换
# 将 excel文件转换成 pdf
def excel_to_pdf(path):
# lazy import pandas
import pandas as pd
import pdfkit
# 表格标题居中显示
pd.set_option('colheader_justify', 'center')
df = pd.read_excel(path)
html_string = '''
<html>
<link rel="stylesheet" type="text/css" href="table_style.css"/>
<body>
{table}
</body>
</html>.
'''
with open('export_df.html', 'w') as f:
f.write(html_string.format(table=df.to_html(classes='default', index=False)))
options = {
'encoding': "UTF-8",
'no-outline': None
}
pdfkit.from_file('export_df.html', 'export_pdf.pdf', options=options)
css样式文件 注意文件名: table_style.css
.default {
font-size: 11pt;
font-family: Arial;
border-collapse: collapse;
border: 0px solid silver;
}
.default td, th {
padding: 0px;
border-style:none;
text-align:center;
vertical-align:middle
}
.default tr:nth-child(even) {
background: #E0E0E0;
}
.default tr:hover {
background: silver;
cursor: pointer;
}
🎉🎉🎉