准备:
python3
pip3 install imgkt html-table
下载安装wkhtmltoimg:wkhtmltopdf.org/downloads.h…
然后就是直接上代码
import imgkit
from HTMLTable import HTMLTable
"""
Author:joker_cc
"""
# 标题
table = HTMLTable(caption='监控数据表')
# 表头行
table.append_header_rows((
('IP', 'CPU(%)','内存(%)','磁盘(%)'),
))
# 数据行
table.append_data_rows((
('192.168.24.21', 50, 18, 30),
('192.168.24.22', 90, 10, 40),
('192.168.24.23', 60, 12, 25),
))
# 标题样式
table.caption.set_style({
'font-size': '15px',
})
# 表格样式,即<table>标签样式
table.set_style({
'border-collapse': 'collapse',
'word-break': 'keep-all',
'white-space': 'nowrap',
'font-size': '14px',
})
# 统一设置所有单元格样式,<td>或<th>
table.set_cell_style({
'width': "250px",
'border-color': '#000',
'border-width': '1px',
'border-style': 'solid',
'padding': '5px',
})
# 表头样式
table.set_header_row_style({
'color': '#fff',
'background-color': '#48a6fb',
'font-size': '18px',
})
# 覆盖表头单元格字体样式
table.set_header_cell_style({
'padding': '15px',
})
# 调小次表头字体大小
table[1].set_cell_style({
'padding': '8px',
'font-size': '15px',
})
# 遍历数据行,如果CPU>80,标红背景颜色
for row in table.iter_data_rows():
if row[1].value > 80:
row.set_style({
'background-color': '#ffdddd',
})
body = table.to_html()
# html的charset='UTF-8'必须加上,否则中文会乱码
html = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body>{0}</body></html>".format(body)
# 生成图片
config = imgkit.config(wkhtmltoimage=r"D:\Users\user\Software\wkhtmltopdf\bin\wkhtmltoimage.exe")
imgkit.from_string(html, 'out.jpg',config=config)
就是这么简单~