1

我正在创建一个 PDF,其中包含一个表格,但表格行在 PDF 和 PDF 之间会有所不同

    table = Table(data, colWidths=[3.05 * cm, 4.5 * cm, 4 * cm,3* cm, 3 * cm])
    table.setStyle(TableStyle([
                   ('INNERGRID', (0,0), (-1,-1), 0.25, black),
                   ('BOX', (0,0), (-1,-1), 0.25, black),
                   ]))
    table.wrapOn(self.pdf, self.width_table, self.height_table)
    table.drawOn(self.pdf, *self.coord(1.0, 18.6,cm))

这就是我现在用来创建表格的东西。

谢谢,

4

1 回答 1

2

对于任何刚开始的人来说,这都是一个核心问题。

以下是开始构建的完整可行代码。答案是,正如您在评论中自己写的那样,是循环。但是,以后任何人都会发现的问题是您如何处理多页表和这些表的设计。有各种值得研究的解决方案。

from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.platypus import Frame, PageTemplate, KeepInFrame
from reportlab.lib.units import cm
from reportlab.platypus import (Table, TableStyle, BaseDocTemplate)

########################################################################

def create_pdf():
    """
    Create a pdf
    """

    # Create a frame
    text_frame = Frame(
        x1=3.00 * cm,  # From left
        y1=1.5 * cm,  # From bottom
        height=19.60 * cm,
        width=15.90 * cm,
        leftPadding=0 * cm,
        bottomPadding=0 * cm,
        rightPadding=0 * cm,
        topPadding=0 * cm,
        showBoundary=1,
        id='text_frame')

    # Create a table
    test_table = []
    data = []
    for i in range(11, 1, -1):
        column1data = f'Column_1 on row {i}'
        column2data = f'Column_2 on row {i}'
        data.append([column1data, column2data])

    data_table = Table(data, 15.90 * cm / 2)
    data_table.setStyle(TableStyle([
        # Title
        ('LEFTPADDING', (0, 0), (1, 0), 0),
        ('RIGHTPADDING', (0, 0), (1, 0), 0),
        ('VALIGN', (0, 0), (1, 0), 'TOP'),
        ('ALIGN', (0, 0), (1, 0), 'CENTRE'),
        # DataTable
        ('ALIGN', (0, 1), (1, -1), 'CENTRE'),
        ('SIZE', (0, 1), (-1, -1), 7),
        ('LEADING', (0, 1), (-1, -1), 8.4),
        ('VALIGN', (0, 1), (-1, -1), 'MIDDLE'),
        ('TOPPADDING', (0, 1), (-1, -1), 2.6),
        ('BOTTOMPADDING', (0, 1), (-1, -1), 2.6),
        ('LINEBELOW', (0, 1), (-1, -1), 0.3, colors.gray),
    ]))

    test_table.append(data_table)
    test_table = KeepInFrame(0, 0, test_table, mode='overflow')

    # Building the story
    story = [test_table] # adding test_table table (alternative, story.add(test_table))

    # Establish a document
    doc = BaseDocTemplate("Example_output.pdf", pagesize=letter)

    # Creating a page template
    frontpage = PageTemplate(id='FrontPage',
                             frames=[text_frame]
                             )
    # Adding the story to the template and template to the document
    doc.addPageTemplates(frontpage)

    # Building doc
    doc.build(story)


# ----------------------------------------------------------------------
if __name__ == "__main__":
    create_pdf() # Printing the pdf
于 2020-04-17T14:07:29.573 回答