Python 和 ReportLab。如何更改 Table 对象中的字体和字体大小?

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

我需要更改表对象(ReportLab)中特定单元格的文本样式。 据我了解,可以通过 TableStayle 类来完成,但我找不到示例。

my_table = Table(data, colWidths=column_widths, rowHeights = row_heghts)

my_colour_black = [0, 0, 0]
my_colour_ligt_gray = [0.8, 0.8, 0.8]
my_colour_gray = [0.5, 0.5, 0.5]
my_colour_dark_gray = [0.2, 0.2, 0.2]
my_colour_white = [1, 1, 1]

my_table.setStyle(TableStyle([
    ('ALIGN',(0,0),(-1,0),'CENTER'),
    ('VALIGN',(0,0),(-1,0),'MIDDLE'),
    ('TEXTCOLOR',(0,0),(-1,0), my_colour_black),
    ('BACKGROUND',(0,0),(-1,0),my_colour_ligt_gray),
    ('ALIGN',(0,1),(-1,-1),'RIGHT'),
    ('VALIGN',(0,1),(-1,-1),'MIDDLE'), 
    ('TEXTCOLOR',(0,1),(-1,-1),my_colour_gray),
    ('INNERGRID', (0,0), (-1,-1), 0.5, my_colour_white),
    ]))

我试图在原始文档和其他公共资源(Google)中找到答案,但没有找到。 原始文档中提到了“FONT、FONTNAME(或 FACE)、FONTSIZE(或 SIZE)”,但没有如何使用它的示例。

python reportlab
2个回答
4
投票

终于,我找到了答案。格式为: ('字体名称', (0,0), (-1,-1), 'Arial'), ('字体大小', (0,0), (-1,0), 10),

TableStyle 的完整列表:

    current_tab_style = TableStyle([
('FONTNAME', (0,0), (-1,-1), 'Arial'), # font
('FONTSIZE', (0,0), (-1,0), 12),
('FONTSIZE', (0,1), (-1,-1), 10),
('ALIGN',(0,0),(-1,0),'CENTER'),
('VALIGN',(0,0),(-1,0),'MIDDLE'),
('TEXTCOLOR',(0,0),(-1,0), my_colour_black),
('BACKGROUND',(0,0),(-1,0),my_colour_ligt_gray),
('ALIGN',(0,1),(-1,-1),'RIGHT'),
('VALIGN',(0,1),(-1,-1),'MIDDLE'), 
('TEXTCOLOR',(0,1),(-1,-1),my_colour_gray),
('INNERGRID', (0,0), (-1,-1), 0.5, my_colour_white),
])

0
投票

我想更改内容的字体大小,但它没有改变,只有标题的字体大小......有什么想法吗?

我有这个例子:

import time
from reportlab.lib.pagesizes import landscape, letter
from reportlab.lib import colors
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, PageTemplate, Frame
from reportlab.lib.styles import getSampleStyleSheet

# Function to add header and footer
def add_header_footer(canvas, doc, header_text):
    canvas.saveState()
    # Header
    # header_text = "Report Header"
    canvas.setFont('Helvetica-Bold', 14)
    text_width = canvas.stringWidth(header_text, 'Helvetica-Bold', 14)
    canvas.drawCentredString(doc.pagesize[0] / 2, doc.pagesize[1] - 80, header_text)  # Adjusted position
    
    # Footer
    footer_text = f"Page {doc.page}"
    canvas.setFont('Helvetica', 10)
    text_width = canvas.stringWidth(footer_text, 'Helvetica', 10)
    canvas.drawString((doc.pagesize[0] - text_width) / 2, 40, footer_text)
    canvas.restoreState()

# Function to generate PDF with ordered data in a table format
def generate_pdf(data, pdf_filename, header_text):
    # Create the document
    doc = SimpleDocTemplate(pdf_filename, pagesize=landscape(letter), topMargin=1.5*inch)  # Adjust topMargin here
    
    # Define the table data
    table_data = [['Parameter Name', 'Expected Value', 'Your INI Value']]
    
    # Get the sample style sheet
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    
    # Add "Results for the Ini file:" text as a paragraph before the table
    results_text = "Results for the Ini file:"
    results_paragraph = Paragraph(results_text, styles['Heading2'])
    
    # Calculate the height of the results paragraph
    results_paragraph_height = results_paragraph.wrap(doc.width, doc.topMargin)[1]
    
    # Populate the table with data
    for i in range(len(data['Parameter_Name'])):
        # Ensure each cell in the row is a Paragraph object
        row = [
            Paragraph(data['Parameter_Name'][i], styleN),
            Paragraph(data['Expected_Value'][i], styleN),
            Paragraph(data['Your_INI_Value'][i], styleN)
        ]
        
        table_data.append(row)
    
    # Create the table
    table = Table(table_data, colWidths=[2.5 * inch, 3.0 * inch, 3.0 * inch], repeatRows=1)  # use repeatRows=1 if you want the header of the table to be repetad in teh table in the next pages
    
    # Add style to the table
    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'),
        ('FONTSIZE', (0, 0), (-1, 0), 14), # For header in table
        ('BOTTOMPADDING', (0, 0), (-1, 0), 8),
        ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
        ('FONTSIZE', (0, 1), (-1, -1), 24),  # Font size for content
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),  # Ensure text starts from the top of the cell
    ])
    table.setStyle(style)

    # Apply conditional styling for rows where values differ
    for i in range(1, len(table_data)):  # Start from 1 to skip header row
        expected_value = data['Expected_Value'][i-1]
        your_ini_value = data['Your_INI_Value'][i-1]
        if expected_value != your_ini_value:
            # Apply red background and white text for differing rows
            table.setStyle(TableStyle([
                ('BACKGROUND', (0, i), (-1, i), colors.red),
                ('TEXTCOLOR', (0, i), (-1, i), colors.white)
            ]))

    # Define the frame for the page template
    frame = Frame(doc.leftMargin, doc.bottomMargin + 5 + results_paragraph_height, doc.width, doc.height - 5 - results_paragraph_height, id='normal')
    # frame = Frame(doc.leftMargin, doc.bottomMargin + 100 + results_paragraph_height, doc.width, doc.height - 100 - results_paragraph_height, id='normal')
    
    # Add the PageTemplate with header and footer
    template = PageTemplate(id='test', frames=frame, onPage=lambda canvas, doc: add_header_footer(canvas, doc, header_text))
    doc.addPageTemplates([template])
    
    # # Calculate row heights for each row in the table
    # row_heights = []
    # for row in table_data:
    #     # Ensure all elements in row are Paragraph objects
    #     if all(isinstance(cell, Paragraph) for cell in row):
    #         row_heights.append(max([p.wrap(doc.width, doc.height)[1] for p in row]))
    
    # # Remove the header row height
    # if row_heights:
    #     header_row_height = row_heights.pop(0)
    # else:
    #     header_row_height = 0
    
    # Build the PDF
    elements = [results_paragraph, table]
    doc.build(elements, onFirstPage=lambda canvas, doc: add_header_footer(canvas, doc, header_text), onLaterPages=lambda canvas, doc: add_header_footer(canvas, doc, header_text))


if __name__ == '__main__':
    # Example data (20 parameters with fictitious names and values)
    data = {
        'Parameter_Name': [
            'Parameter 1', 'Parameter 2', 'Parameter 3', 'Parameter 4', 'Parameter 5',
            'Parameter 6', 'Parameter 7', 'Parameter 8', 'Parameter 9', 'Parameter 10',
        ],
        'Expected_Value': [
            'Value 1', 'Expected Value 2', 'Expected Value 3', 'Expected Value 4', 'Expected Value 5',
            'Expected Value 6', 'Value 7', 'Expected Value 8', 'Expected Value 9', 'Expected Value 10',
        ],
        'Your_INI_Value': [
            'Value 1', 'Your INI Value 2', 'Your INI Value 3', 'Your INI Value 4', 'Your INI Value 5',
            'Your INI Value 6', 'Value 7', 'Your INI Value 8', 'Example of large data for a cell, and autoadjust for Your INI Value 9', 'Your INI Value 10',
        ]
    }
    # PDF filename with timestamp
    # pdf_filename = f"ordered_data_{time.strftime('%Y%m%d%H%M%S')}.pdf"
    pdf_filename = f"ordered_data.pdf"
    header_text = "Custom Header Text INI"
    # Generate the PDF with ordered data
    generate_pdf(data, pdf_filename, header_text)
    print(pdf_filename)
© www.soinside.com 2019 - 2024. All rights reserved.