You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Julia中正确将DataFrame保存为PDF文件?

解决方案:DataFrame 转 PDF 的可靠方法

1. 直接用 matplotlib 生成PDF表格

无需中转LaTeX,直接绘制表格并导出,适合结构简单的DataFrame:

import pandas as pd
import matplotlib.pyplot as plt

# 示例DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Score': [85.5, 90.0, 78.0]
})

fig, ax = plt.subplots(figsize=(8, 2))
ax.axis('tight')
ax.axis('off')
# 生成表格
table = ax.table(cellText=df.values, colLabels=df.columns, loc='center')

# 优化样式
table.auto_set_font_size(False)
table.set_fontsize(10)
table.scale(1.2, 1.2)

# 保存为PDF
plt.savefig('dataframe.pdf', bbox_inches='tight')

2. 用 tabulate 生成规范LaTeX代码再编译

tabulate输出的LaTeX结构标准,配合TeX环境编译不会变形:

import pandas as pd
from tabulate import tabulate

df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Score': [85.5, 90.0, 78.0]
})

# 生成带booktabs格式的LaTeX代码(更美观的表格线)
latex_code = tabulate(df, headers='keys', tablefmt='latex_booktabs')

# 写入完整LaTeX文档
with open('table.tex', 'w') as f:
    f.write(f"""
\\documentclass{{article}}
\\usepackage{{booktabs}}
\\begin{{document}}
{latex_code}
\\end{{document}}
""")

# 命令行执行编译(需提前安装TeX环境):pdflatex table.tex

3. 先转HTML再用 pdfkit 生成PDF

适合需要保留复杂样式的DataFrame,支持自定义CSS:

import pandas as pd
import pdfkit

df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Score': [85.5, 90.0, 78.0]
})

# 将DataFrame转为HTML表格
html_table = df.to_html(index=False, classes='table table-striped')

# 构建完整HTML内容
html_content = f"""
<html>
<head>
    <style>
        .table {{ width: 100%; border-collapse: collapse; }}
        .table th, .table td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        .table th {{ background-color: #f2f2f2; }}
    </style>
</head>
<body>
    {html_table}
</body>
</html>
"""

# 转换为PDF(需提前安装wkhtmltopdf工具)
pdfkit.from_string(html_content, 'dataframe.pdf')

PrettyTables 使用修复

如果坚持用PrettyTables,确保正确构造表格并生成LaTeX:

import pandas as pd
from prettytable import PrettyTable

df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Score': [85.5, 90.0, 78.0]
})

pt = PrettyTable()
pt.field_names = df.columns.tolist()
# 逐行添加数据
for row in df.itertuples(index=False):
    pt.add_row(row)

# 生成LaTeX代码
latex_code = pt.get_string(format='latex')

# 写入LaTeX文档并编译
with open('pretty_table.tex', 'w') as f:
    f.write(f"""
\\documentclass{{article}}
\\begin{{document}}
{latex_code}
\\end{{document}}
""")

内容的提问来源于stack exchange,提问作者Anand Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:23:25