用pycharm对医学.dbf文件转化成.pdf文件,代码如下:
import dbfread
import pandas as pd
import matplotlib
matplotlib.use('Agg') # 设置后端
import matplotlib.pyplot as plt
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.styles import getSampleStyleSheet
# 读取.dbf文件
table = dbfread.DBF('D:\pythonProject\mmse.dbf')
# 转换为DataFrame
df = pd.DataFrame(table)
def df_to_pdf(df, filename):
# 初始化canvas
c = canvas.Canvas(filename, pagesize=letter)
# 设置字体
plt.rcParams['font.family'] = 'Arial' # 更换为支持所需字形的字体
# 设置字体大小等样式
font_name = 'Helvetica'
style_sheet = getSampleStyleSheet()
normal_style = style_sheet['Normal']
normal_style.fontName = font_name
data_style = normal_style.clone(name="data_style")
data_style.fontSize = 10
# 计算表格布局
table_data = []
for idx, row in df.iterrows():
table_data.append([str(val) for val in row])
[max([len(str(x)) for x in col]) * 0.75 for col in df.columns]
# 在PDF上绘制表格
table_height = len(df.index) * 15
table_top = 750 - table_height
c.drawString(30, table_top + 10, " ".join(df.columns))
y = table_top
for row in table_data:
c.drawString(30, y, " ".join(row))
y -= 20
# 保存PDF
c.save()
# 调用函数将DataFrame写入PDF
df_to_pdf(df, 'mmse.pdf')
# 保存图形到文件中
plt.savefig("table.png", bbox_inches='tight', pad_inches=0)
运行之后显示没有错误,但是pdf文件里面是空的,想问问大家应该怎样修改呀?