Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReportLab: LayoutError when content of cell too long for a page

I'm trying to create a table with 7 cols. The last column contains a long text which seems to create the error. It seems that when the cells exceeds the size of the page, it throws an exception.

from reportlab.lib.pagesizes import landscape, A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, LongTable, TableStyle, Paragraph
from reportlab.lib import colors
from reportlab.lib.units import mm
from datetime import date

doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
doc.pagesize = landscape(A4)
elements = []

styles = getSampleStyleSheet()
cell_style = styles['BodyText']
cell_style.wordWrap = 1
cell_style.fontName = 'Courier'
cell_style.spaceBefore = 30
cell_style.spaceAfter = 30

title_style = styles['Title']
title_style.fontName = 'Courier'
title = Paragraph('Export Issue Tracker (%s)' % (date.today().isoformat()), title_style)
elements.append(title)

data2 = [[Paragraph(cell, cell_style) for cell in row] for row in data]
table = LongTable(data2, colWidths=(None, None, None, None, None, None, 50*mm))
table_style = TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black),
                            ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                            ('FONTNAME',(0,0),(-1,-1),'Courier'),
                            ('VALIGN',(0,0),(-1,-1),'TOP'),
                            ('ALIGN',(0,0),(-1,0),'CENTER'),
                            ('TEXTCOLOR',(0,0),(-1,0), colors.yellow),
                            ('BACKGROUND', (0,0), (-1,0), colors.gray),
                            ('FONTSIZE',(0,0),(-1,-1),50)] + color_style)
table.setStyle(table_style)
elements.append(table)

doc.build(elements)

However I get the following error:

LayoutError at /issues/export_comments/
Flowable <LongTable@0x7F5AFBBB6560 35 rows x 7 cols(tallest row 2694)> with cell(0,0) containing
u'<Paragraph at 0x7f5afbcb7ef0>9'(769.88976378 x 4782), tallest cell 2694.0 points,  too large on page 2 in frame 'normal'(769.88976378 x 535.275590551*) of template 'Later'

I have seen many posts about how to do it by using KeepTogether, Spacer, LongTable but non of them works for me.

like image 612
Ruben Avatar asked Jan 06 '16 15:01

Ruben


People also ask

Why is my row height too high in my paginated report?

When you set a row height, you are specifying the maximum height for the row in the rendered paginated report. However, by default, text boxes in the row are set to grow vertically to accommodate their data at run-time, and this can cause a row to expand beyond the height that you specify.

Why does the reporter fail when trying to insert a space?

This is happening when trying to insert the SPACER near the bottom of the page. the reporter might fail if the space is close to the bottom of the page. The expected behavious is that it should not fail. It should somehow handle that. Sign up for free to join this conversation on GitHub .

What happens when string length is too long for a cell?

When I paste in and the string length is too long for a cell to handle, Excel automatically puts the next batch of text on the next line in col. A. With a macro or formula...

What is the length of cell contents (text) in Excel?

Length of cell contents (text): 32,767 characters. Only 1,024 display in a cell; all 32,767 display in the formula bar. so that if the cell contains more than 32767 characters it will say TOO BIG TEXT otherwise OK. Have you tried to select the cells with text and some blank cells in the columns to the right, and then select Edit>Fill>Justify.


1 Answers

This problem is usually solved by format the content as a flowable Paragraphs (with a defined paragraph style), otherwise the text is not aware if it should wrap or not. Many times it is a conflict of what the formatting within a table will do with a text. Above problem is RL throwing an error as it has not been told how to deal with overflow text. The workaround with shrink, KeepTogether as mentioned in the comments will not work on unformatted text, you first need to convert it into a paragraph.

In my experience, it's easiest to to work with the rule that table styles takes care of all things but paragraphs.

Below is a generalised solution to build upon. I saw @sagar-gupta was looking for an answer just end of last year on this old question.

from reportlab.lib.pagesizes import letter, A4, landscape
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT
from reportlab.lib.styles import ParagraphStyle, StyleSheet1
from reportlab.lib import colors
from reportlab.platypus import Frame, PageTemplate, KeepInFrame, Paragraph
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')

    styles = StyleSheet1()
    styles.add(ParagraphStyle(name='Breadpointlist_style',
                              alignment=TA_LEFT,
                              bulletFontSize=7,
                              bulletIndent=0,
                              endDots=None,
                              firstLineIndent=0,
                              fontSize=8,
                              justifyBreaks=0,
                              justifyLastLine=0,
                              leading=9.2,
                              leftIndent=11,
                              rightIndent=0,
                              spaceAfter=0,
                              spaceBefore=0,
                              textColor=colors.black,
                              wordWrap='LTR',
                              splitLongWords=True,
                              spaceShrinkage=0.05,
                              ))

    bps = ParagraphStyle('bps', parent=styles['Breadpointlist_style'])

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

    data_table = Table(data, 15.90 * cm / 7)
    data_table.setStyle(TableStyle([

        ('ALIGN', (0, 0), (1, -1), 'RIGHT'),
        ('SIZE', (0, 0), (-1, -1), 7),
        ('LEADING', (0, 0), (-1, -1), 8.4),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('TOPPADDING', (0, 0), (-1, -1), 2.6),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 2.6),
        ('LINEBELOW', (0, 0), (-1, -1), 0.3, colors.gray),
    ]))

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

    # 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
like image 73
Jaco Avatar answered Nov 16 '22 00:11

Jaco