Python 将 df 导出为 pdf - 在 PDFKit 中调整缩放以实现动态 HTML 表格宽度,类似于 Google Sheets 适合宽度

问题描述 投票:0回答:1

TLDR - 我的目标是模仿 python 中“缩放 - 适合宽度”的 google Sheet 导出为 pdf 功能。

我正在尝试构建一个自动化程序,将各种数据帧导出到 pdf 文件。 每个 df 包含不同数量的列,有些列很多(~30-40),有些列少得多。

我通过使用 to_html() 函数将 df 转换为 html,然后使用 pdfkit 库来实现此目的。

pdfkit.from_string(df.to_html(), "table.pdf", options={'zoom': '0.3',})

但是,我无法将缩放设置为特定值,因为不同的表格需要不同的缩放值才能正确适应页面。

如果您要转到 Google 表格并将表格导出为 pdf,您将能够选择“缩放 - 适合宽度”,这正是我想要做的。

我认为它不在 html 级别,因为如果我在浏览器中查看原始 html,它看起来不错。

我怎样才能实现这个目标?

python pdf pdfkit
1个回答
0
投票

执行此操作的一种方法是使用报告实验室 这是我写的关于这个主题的一些基本代码

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib import colors
import pandas as pd

def export_df_to_pdf(df, filename):
    # Calculate the width of the DataFrame table
    col_widths = [len(str(col)) for col in df.columns]
    table_width = sum(col_widths)

    # Calculate scaling factor to fit to width of the page
    page_width, page_height = letter
    max_table_width = page_width - 100  # Adjust as needed
    scaling_factor = max_table_width / table_width

    # Scale the DataFrame table
    scaled_df = df.copy()
    scaled_df.columns = [str(col)[:int(col_widths[i]*scaling_factor)] for i, col in enumerate(df.columns)]

    # Create PDF
    doc = SimpleDocTemplate(filename, pagesize=letter)
    elements = []

    # Convert DataFrame to list of lists for ReportLab Table
    data = [scaled_df.columns.tolist()] + scaled_df.values.tolist()

    # Create Table object
    table = Table(data)

    # Apply table style
    style = TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
                        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                        ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
                        ('GRID', (0, 0), (-1, -1), 1, colors.black)])

    table.setStyle(style)

    # Add table to elements
    elements.append(table)

    # Build PDF
    doc.build(elements)

# Example usage
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
export_df_to_pdf(df, 'output.pdf')
© www.soinside.com 2019 - 2024. All rights reserved.