Ejemplo n.º 1
0
 def draw(self):
     self.canv.saveState()
     self.canv.setLineWidth(self.borderwidth)
     self.canv.translate(0,self.margin)
     self.canv.rect(0,0,self.width, self.height+self.padding*2)
     self.canv.translate(0, self.style.spaceAfter)
     Preformatted.draw(self)
     self.canv.restoreState()
Ejemplo n.º 2
0
    def _showWidgetProperties(self, widget):
        """Dump all properties of a widget."""

        props = widget.getProperties()
        keys = props.keys()
        keys.sort()
        lines = []
        for key in keys:
            value = props[key]

            f = getStringIO()
            pprint.pprint(value, f)
            value = f.getvalue()[:-1]
            valueLines = string.split(value, '\n')
            for i in range(1, len(valueLines)):
                valueLines[i] = ' ' * (len(key) + 3) + valueLines[i]
            value = string.join(valueLines, '\n')

            lines.append('%s = %s' % (key, value))

        text = join(lines, '\n')
        self.story.append(
            Paragraph("<i>Properties of Example Widget</i>", self.bt))
        self.story.append(Paragraph("", self.bt))
        self.story.append(Preformatted(text, self.code))
Ejemplo n.º 3
0
    def _showWidgetDemoCode(self, widget):
        """Show a demo code of the widget."""
        # Heading
        #className = widget.__class__.__name__
        self.story.append(Paragraph("<i>Example</i>", self.bt))

        # Sample code
        codeSample = inspect.getsource(widget.__class__.demo)
        self.story.append(Preformatted(codeSample, self.code))
Ejemplo n.º 4
0
    def _showDrawingCode(self, drawing):
        """Show code of the drawing class."""
        # Heading
        #className = drawing.__class__.__name__
        self.story.append(Paragraph("<i>Example</i>", self.bt))

        # Sample code
        codeSample = inspect.getsource(drawing.__class__.__init__)
        self.story.append(Preformatted(codeSample, self.code))
Ejemplo n.º 5
0
    def _showFunctionDemoCode(self, function):
        """Show a demo code of the function generating the drawing."""
        # Heading
        self.story.append(Paragraph("<i>Example</i>", self.bt))
        self.story.append(Paragraph("", self.bt))

        # Sample code
        codeSample = inspect.getsource(function)
        self.story.append(Preformatted(codeSample, self.code))
Ejemplo n.º 6
0
    def doErrors(self):
        style = self.getStyle()
        title = "Error Summary"
        text = """Below is a summary of the top errors to and from %s
        for the week beginning %s.""" % (self.site, self.getDate())
        errors = """*** ERRORS from T2_Estonia_Buffer:***
    942   transfer expired in the download agent queue
    777   Canceled (null)
    140   transfer timed out after 3630 seconds with signal 15
     77   transfer timed out after 3645 seconds with signal 9
     53   Failed on SRM put: SRM getRequestStatus timed out on put
     50   no detail - validate failed: [unknown reason - inspect log]
      7   the gridFTP transfer timed out"""

        return KeepTogether([
            Paragraph(title, style=style['SectionTitle']),
            Paragraph(text, style=style["Normal_just"]),
            Spacer(inch * .125, inch * .125),
            Preformatted(errors, style=style["Preformatted"])
        ])
Ejemplo n.º 7
0
 def wrap(self, availWidth, availHeight):
     w,h = Preformatted.wrap(self,availWidth, availHeight)
     return ( w+self.margin+self.borderwidth+self.padding*2, h+self.margin+self.borderwidth+self.padding*2)
Ejemplo n.º 8
0
 def __init__(self, text, style, margin=4, padding=4, borderwidth=0.1, **kwargs):
     Preformatted.__init__(self, text, style, **kwargs)
     self.margin = margin
     self.padding = padding
     self.borderwidth = borderwidth
Ejemplo n.º 9
0
def old_tables_test():
    from reportlab.lib.units import inch, cm
    from reportlab.platypus.flowables import Image, PageBreak, Spacer, XBox
    from reportlab.platypus.paragraph import Paragraph
    from reportlab.platypus.xpreformatted import XPreformatted
    from reportlab.platypus.flowables import Preformatted
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.platypus.tables import GRID_STYLE, BOX_STYLE, LABELED_GRID_STYLE, COLORED_GRID_STYLE, LIST_STYLE, LongTable
    rowheights = (24, 16, 16, 16, 16)
    rowheights2 = (24, 16, 16, 16, 30)
    colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32)
    data = (
        ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
        ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89),
        ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119),
        ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13),
        ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843')
        )
    data2 = (
        ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
        ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89),
        ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119),
        ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13),
        ('Hats\nLarge', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843')
        )
    lst = []
    lst.append(Paragraph("Tables", styleSheet['Heading1']))
    lst.append(Paragraph(__doc__, styleSheet['BodyText']))
    lst.append(Paragraph("The Tables (shown in different styles below) were created using the following code:", styleSheet['BodyText']))
    lst.append(Preformatted("""
    colwidths = (50, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32)
    rowheights = (24, 16, 16, 16, 16)
    data = (
        ('', 'Jan', 'Feb', 'Mar','Apr','May', 'Jun',
           'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
        ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89),
        ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119),
        ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13),
        ('Hats', 893, 912, '1,212', 643, 789, 159,
             888, '1,298', 832, 453, '1,344','2,843')
        )
    t = Table(data, colwidths, rowheights)
    """, styleSheet['Code'], dedent=4))
    lst.append(Paragraph("""
    You can then give the Table a TableStyle object to control its format. The first TableStyle used was
    created as follows:
    """, styleSheet['BodyText']))
    lst.append(Preformatted("""
GRID_STYLE = TableStyle(
    [('GRID', (0,0), (-1,-1), 0.25, colors.black),
     ('ALIGN', (1,1), (-1,-1), 'RIGHT')]
    )
    """, styleSheet['Code']))
    lst.append(Paragraph("""
    TableStyles are created by passing in a list of commands. There are two types of commands - line commands
    and cell formatting commands. In all cases, the first three elements of a command are the command name,
    the starting cell and the ending cell.
    """, styleSheet['BodyText']))
    lst.append(Paragraph("""
    Line commands always follow this with the weight and color of the desired lines. Colors can be names,
    or they can be specified as a (R,G,B) tuple, where R, G and B are floats and (0,0,0) is black. The line
    command names are: GRID, BOX, OUTLINE, INNERGRID, LINEBELOW, LINEABOVE, LINEBEFORE
    and LINEAFTER. BOX and OUTLINE are equivalent, and GRID is the equivalent of applying both BOX and
    INNERGRID.
    """, styleSheet['BodyText']))
    lst.append(Paragraph("""
    Cell formatting commands are:
    """, styleSheet['BodyText']))
    lst.append(Paragraph("""
    FONT - takes fontname, fontsize and (optional) leading.
    """, styleSheet['Definition']))
    lst.append(Paragraph("""
    TEXTCOLOR - takes a color name or (R,G,B) tuple.
    """, styleSheet['Definition']))
    lst.append(Paragraph("""
    ALIGNMENT (or ALIGN) - takes one of LEFT, RIGHT, CENTRE (or CENTER) or DECIMAL.
    """, styleSheet['Definition']))
    lst.append(Paragraph("""
    LEFTPADDING - defaults to 6.
    """, styleSheet['Definition']))
    lst.append(Paragraph("""
    RIGHTPADDING - defaults to 6.
    """, styleSheet['Definition']))
    lst.append(Paragraph("""
    BOTTOMPADDING - defaults to 3.
    """, styleSheet['Definition']))
    lst.append(Paragraph("""
    A tablestyle is applied to a table by calling Table.setStyle(tablestyle).
    """, styleSheet['BodyText']))
    t = Table(data, colwidths, rowheights)
    t.setStyle(GRID_STYLE)
    lst.append(PageBreak())
    lst.append(Paragraph("This is GRID_STYLE\n", styleSheet['BodyText']))
    lst.append(t)

    t = Table(data, colwidths, rowheights)
    t.setStyle(BOX_STYLE)
    lst.append(Paragraph("This is BOX_STYLE\n", styleSheet['BodyText']))
    lst.append(t)
    lst.append(Paragraph("""
    It was created as follows:
    """, styleSheet['BodyText']))
    lst.append(Preformatted("""
BOX_STYLE = TableStyle(
    [('BOX', (0,0), (-1,-1), 0.50, colors.black),
     ('ALIGN', (1,1), (-1,-1), 'RIGHT')]
    )
    """, styleSheet['Code']))

    t = Table(data, colwidths, rowheights)
    t.setStyle(LABELED_GRID_STYLE)
    lst.append(Paragraph("This is LABELED_GRID_STYLE\n", styleSheet['BodyText']))
    lst.append(t)
    t = Table(data2, colwidths, rowheights2)
    t.setStyle(LABELED_GRID_STYLE)
    lst.append(Paragraph("This is LABELED_GRID_STYLE ILLUSTRATES EXPLICIT LINE SPLITTING WITH NEWLINE (different heights and data)\n", styleSheet['BodyText']))
    lst.append(t)
    lst.append(Paragraph("""
    It was created as follows:
    """, styleSheet['BodyText']))
    lst.append(Preformatted("""
LABELED_GRID_STYLE = TableStyle(
    [('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
     ('BOX', (0,0), (-1,-1), 2, colors.black),
     ('LINEBELOW', (0,0), (-1,0), 2, colors.black),
     ('LINEAFTER', (0,0), (0,-1), 2, colors.black),
     ('ALIGN', (1,1), (-1,-1), 'RIGHT')]
    )
    """, styleSheet['Code']))
    lst.append(PageBreak())

    t = Table(data, colwidths, rowheights)
    t.setStyle(COLORED_GRID_STYLE)
    lst.append(Paragraph("This is COLORED_GRID_STYLE\n", styleSheet['BodyText']))
    lst.append(t)
    lst.append(Paragraph("""
    It was created as follows:
    """, styleSheet['BodyText']))
    lst.append(Preformatted("""
COLORED_GRID_STYLE = TableStyle(
    [('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
     ('BOX', (0,0), (-1,-1), 2, colors.red),
     ('LINEBELOW', (0,0), (-1,0), 2, colors.black),
     ('LINEAFTER', (0,0), (0,-1), 2, colors.black),
     ('ALIGN', (1,1), (-1,-1), 'RIGHT')]
    )
    """, styleSheet['Code']))

    t = Table(data, colwidths, rowheights)
    t.setStyle(LIST_STYLE)
    lst.append(Paragraph("This is LIST_STYLE\n", styleSheet['BodyText']))
    lst.append(t)
    lst.append(Paragraph("""
    It was created as follows:
    """, styleSheet['BodyText']))
    lst.append(Preformatted("""
LIST_STYLE = TableStyle(
    [('LINEABOVE', (0,0), (-1,0), 2, colors.green),
     ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
     ('LINEBELOW', (0,-1), (-1,-1), 2, colors.green),
     ('ALIGN', (1,1), (-1,-1), 'RIGHT')]
    )
    """, styleSheet['Code']))

    t = Table(data, colwidths, rowheights)
    ts = TableStyle(
    [('LINEABOVE', (0,0), (-1,0), 2, colors.green),
     ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
     ('LINEBELOW', (0,-1), (-1,-1), 3, colors.green,'butt'),
     ('LINEBELOW', (0,-1), (-1,-1), 1, colors.white,'butt'),
     ('ALIGN', (1,1), (-1,-1), 'RIGHT'),
     ('TEXTCOLOR', (0,1), (0,-1), colors.red),
     ('BACKGROUND', (0,0), (-1,0), colors.Color(0,0.7,0.7))]
    )
    t.setStyle(ts)
    lst.append(Paragraph("This is a custom style\n", styleSheet['BodyText']))
    lst.append(t)
    lst.append(Paragraph("""
    It was created as follows:
    """, styleSheet['BodyText']))
    lst.append(Preformatted("""
   ts = TableStyle(
    [('LINEABOVE', (0,0), (-1,0), 2, colors.green),
     ('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
     ('LINEBELOW', (0,-1), (-1,-1), 3, colors.green,'butt'),
     ('LINEBELOW', (0,-1), (-1,-1), 1, colors.white,'butt'),
     ('ALIGN', (1,1), (-1,-1), 'RIGHT'),
     ('TEXTCOLOR', (0,1), (0,-1), colors.red),
     ('BACKGROUND', (0,0), (-1,0), colors.Color(0,0.7,0.7))]
    )
    """, styleSheet['Code']))
    data = (
        ('', 'Jan\nCold', 'Feb\n', 'Mar\n','Apr\n','May\n', 'Jun\nHot', 'Jul\n', 'Aug\nThunder', 'Sep\n', 'Oct\n', 'Nov\n', 'Dec\n'),
        ('Mugs', 0, 4, 17, 3, 21, 47, 12, 33, 2, -2, 44, 89),
        ('T-Shirts', 0, 42, 9, -3, 16, 4, 72, 89, 3, 19, 32, 119),
        ('Key Ring', 0,0,0,0,0,0,1,0,0,0,2,13),
        ('Hats', 893, 912, '1,212', 643, 789, 159, 888, '1,298', 832, 453, '1,344','2,843')
        )
    c = list(colwidths)
    c[0] = None
    c[8] = None
    t = Table(data, c, [None]+list(rowheights[1:]))
    t.setStyle(LIST_STYLE)
    lst.append(Paragraph("""
        This is a LIST_STYLE table with the first rowheight set to None ie automatic.
        The top row cells are split at a newline '\\n' character. The first and August
        column widths were also set to None.
    """, styleSheet['BodyText']))
    lst.append(t)

    lst.append(Paragraph("""
        This demonstrates a number of features useful in financial statements. The first is decimal alignment;
        with ALIGN=DECIMAL the numbers align on the points; and the points are aligned based on
        the RIGHTPADDING, which is usually 3 points so you should set it higher.  The second is multiple lines;
        one can specify double or triple lines and control the separation if desired. Finally, the coloured
        negative numbers were (we regret to say) done in the style; we don't have a way to conditionally
        format numbers based on value yet.
    """, styleSheet['BodyText']))


    t = Table([['Corporate Assets','Amount'],
               ['Fixed Assets','1,234,567.89'],
               ['Company Vehicle','1,234.8901'],
               ['Petty Cash','42'],
               [u'Intellectual Property\u00ae','(42,078,231.56)'],
               ['Overdraft','(12,345)'],
               ['Boardroom Flat Screen','60 inches'],
               ['Net Position','Deep Sh*t.Really']
               ],
              [144,72])

    ts = TableStyle(
        [#first the top row
         ('ALIGN', (1,1), (-1,-1), 'CENTER'),
         ('LINEABOVE', (0,0), (-1,0), 1, colors.purple),
         ('LINEBELOW', (0,0), (-1,0), 1, colors.purple),
         ('FONT', (0,0), (-1,0), 'Times-Bold'),

        #bottom row has a line above, and two lines below
         ('LINEABOVE', (0,-1), (-1,-1), 1, colors.purple),  #last 2 are count, sep
         ('LINEBELOW', (0,-1), (-1,-1), 0.5, colors.purple, 1, None, None, 4,1),
         ('LINEBELOW', (0,-1), (-1,-1), 1, colors.red),
         ('FONT', (0,-1), (-1,-1), 'Times-Bold'),

        #numbers column
         ('ALIGN', (1,1), (-1,-1), 'DECIMAL'),
         ('RIGHTPADDING', (1,1), (-1,-1), 36),
         ('TEXTCOLOR', (1,4), (1,4), colors.red),

        #red cell
        ]
        )

    t.setStyle(ts)
    lst.append(t)
    lst.append(Spacer(36,36))
    lst.append(Paragraph("""
        The red numbers should be aligned LEFT &amp; BOTTOM, the blue RIGHT &amp; TOP
        and the green CENTER &amp; MIDDLE.
    """, styleSheet['BodyText']))
    XY  =   [['X00y', 'X01y', 'X02y', 'X03y', 'X04y'],
            ['X10y', 'X11y', 'X12y', 'X13y', 'X14y'],
            ['X20y', 'X21y', 'X22y', 'X23y', 'X24y'],
            ['X30y', 'X31y', 'X32y', 'X33y', 'X34y']]
    t=Table(XY, 5*[0.6*inch], 4*[0.6*inch])
    t.setStyle([('ALIGN',(1,1),(-2,-2),'LEFT'),
                ('TEXTCOLOR',(1,1),(-2,-2),colors.red),

                ('VALIGN',(0,0),(1,-1),'TOP'),
                ('ALIGN',(0,0),(1,-1),'RIGHT'),
                ('TEXTCOLOR',(0,0),(1,-1),colors.blue),

                ('ALIGN',(0,-1),(-1,-1),'CENTER'),
                ('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
                ('TEXTCOLOR',(0,-1),(-1,-1),colors.green),
                ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                ])
    lst.append(t)
    data = [('alignment', 'align\012alignment'),
            ('bulletColor', 'bulletcolor\012bcolor'),
            ('bulletFontName', 'bfont\012bulletfontname'),
            ('bulletFontSize', 'bfontsize\012bulletfontsize'),
            ('bulletIndent', 'bindent\012bulletindent'),
            ('firstLineIndent', 'findent\012firstlineindent'),
            ('fontName', 'face\012fontname\012font'),
            ('fontSize', 'size\012fontsize'),
            ('leading', 'leading'),
            ('leftIndent', 'leftindent\012lindent'),
            ('rightIndent', 'rightindent\012rindent'),
            ('spaceAfter', 'spaceafter\012spacea'),
            ('spaceBefore', 'spacebefore\012spaceb'),
            ('textColor', 'fg\012textcolor\012color')]
    t = Table(data)
    t.setStyle([
            ('VALIGN',(0,0),(-1,-1),'TOP'),
            ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
            ('BOX', (0,0), (-1,-1), 0.25, colors.black),
            ])
    lst.append(t)
    t = Table([ ('Attribute', 'Synonyms'),
                ('alignment', 'align, alignment'),
                ('bulletColor', 'bulletcolor, bcolor'),
                ('bulletFontName', 'bfont, bulletfontname'),
                ('bulletFontSize', 'bfontsize, bulletfontsize'),
                ('bulletIndent', 'bindent, bulletindent'),
                ('firstLineIndent', 'findent, firstlineindent'),
                ('fontName', 'face, fontname, font'),
                ('fontSize', 'size, fontsize'),
                ('leading', 'leading'),
                ('leftIndent', 'leftindent, lindent'),
                ('rightIndent', 'rightindent, rindent'),
                ('spaceAfter', 'spaceafter, spacea'),
                ('spaceBefore', 'spacebefore, spaceb'),
                ('textColor', 'fg, textcolor, color')])
    t.repeatRows = 1
    t.setStyle([
                ('FONT',(0,0),(-1,1),'Times-Bold',10,12),
                ('FONT',(0,1),(-1,-1),'Courier',8,8),
                ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.green),
                ('BACKGROUND', (0, 1), (-1, -1), colors.pink),
                ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                ('ALIGN', (0, 1), (0, -1), 'LEFT'),
                ('ALIGN', (-1, 1), (-1, -1), 'RIGHT'),
                ('FONT', (0, 0), (-1, 0), 'Times-Bold', 12),
                ('ALIGN', (1, 1), (1, -1), 'CENTER'),
                ])
    lst.append(t)
    lst.append(Table(XY,
            style=[ ('FONT',(0,0),(-1,-1),'Times-Roman', 5,6),
                    ('GRID', (0,0), (-1,-1), 0.25, colors.blue),]))
    lst.append(Table(XY,
            style=[ ('FONT',(0,0),(-1,-1),'Times-Roman', 10,12),
                    ('GRID', (0,0), (-1,-1), 0.25, colors.black),]))
    lst.append(Table(XY,
            style=[ ('FONT',(0,0),(-1,-1),'Times-Roman', 20,24),
                    ('GRID', (0,0), (-1,-1), 0.25, colors.red),]))
    lst.append(PageBreak())
    data=  [['00', '01', '02', '03', '04'],
            ['10', '11', '12', '13', '14'],
            ['20', '21', '22', '23', '24'],
            ['30', '31', '32', '33', '34']]
    t=Table(data,style=[
                    ('GRID',(0,0),(-1,-1),0.5,colors.grey),
                    ('GRID',(1,1),(-2,-2),1,colors.green),
                    ('BOX',(0,0),(1,-1),2,colors.red),
                    ('BOX',(0,0),(-1,-1),2,colors.black),
                    ('LINEABOVE',(1,2),(-2,2),1,colors.blue),
                    ('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    ('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    ('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    ('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    ('TEXTCOLOR',(0,-1),(-2,-1),colors.green),
                    ])
    lst.append(Paragraph("Illustrating splits: nosplit", styleSheet['BodyText']))
    lst.append(t)
    lst.append(Spacer(0,6))
    lst.append(Paragraph("Illustrating splits: split(4in,30)", styleSheet['BodyText']))
    for s in t.split(4*inch,30):
        lst.append(s)
        lst.append(Spacer(0,6))
    lst.append(Spacer(0,6))
    lst.append(Paragraph("Illustrating splits: split(4in,36)", styleSheet['BodyText']))
    for s in t.split(4*inch,36):
        lst.append(s)
        lst.append(Spacer(0,6))
    lst.append(Paragraph("Illustrating splits: split(4in,56)", styleSheet['BodyText']))
    lst.append(Spacer(0,6))
    for s in t.split(4*inch,56):
        lst.append(s)
        lst.append(Spacer(0,6))

    lst.append(Paragraph("Illustrating splits: repeated split(4in,30)", styleSheet['BodyText']))
    lst.append(Spacer(0,6))
    S = t.split(4*inch,30)
    s = S.pop(-1)
    S.extend(s.split(4*inch,30))
    s = S.pop(-1)
    S.extend(s.split(4*inch,30))

    for s in S:
        lst.append(s)
        lst.append(Spacer(0,6))

    lst.append(PageBreak())
    data=  [['00', '01', '02', '03', '04'],
            ['', '11', '12', '13', '14'],
            ['20', '21', '22', '23', '24'],
            ['30', '31', '', '33', '34']]
    sty=[
                    ('GRID',(0,0),(-1,-1),0.5,colors.grey),
                    ('GRID',(1,1),(-2,-2),1,colors.green),
                    ('BOX',(0,0),(1,-1),2,colors.red),
                    ('BOX',(0,0),(-1,-1),2,colors.black),
                    ('LINEABOVE',(1,2),(-2,2),1,colors.blue),
                    ('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    ('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    ('SPAN',(0,0),(0,1)),
                    ('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    ('SPAN',(2,2),(2,3)),
                    ]
    t=Table(data,style=sty)
    lst.append(Paragraph("Illustrating splits with spans: nosplit", styleSheet['BodyText']))
    lst.append(t)
    lst.append(Spacer(0,6))
    lst.append(Paragraph("Illustrating splits with spans: split(4in,30)", styleSheet['BodyText']))
    for s in t.split(4*inch,30):
        lst.append(s)
        lst.append(Spacer(0,6))
    lst.append(Spacer(0,6))
    lst.append(Paragraph("Illustrating splits with spans: split(4in,36)", styleSheet['BodyText']))
    for s in t.split(4*inch,36):
        lst.append(s)
        lst.append(Spacer(0,6))
    lst.append(Paragraph("Illustrating splits with spans: split(4in,56)", styleSheet['BodyText']))
    lst.append(Spacer(0,6))
    for s in t.split(4*inch,56):
        lst.append(s)
        lst.append(Spacer(0,6))

    data=  [['00', '01', '02', '03', '04'],
            ['', '11', '12', '13', ''],
            ['20', '21', '22', '23', '24'],
            ['30', '31', '', '33', ''],
            ['40', '41', '', '43', '44']]
    sty=[
        ('GRID',(0,0),(-1,-1),0.5,colors.grey),
        ('GRID',(1,1),(-2,-2),1,colors.green),
        ('BOX',(0,0),(1,-1),2,colors.red),
        ('BOX',(0,0),(-1,-1),2,colors.black),
        ('LINEABOVE',(1,2),(-2,2),1,colors.blue),
        ('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
        ('BACKGROUND', (0, 0), (0, 1), colors.pink),
        ('SPAN',(0,0),(0,1)),
        ('BACKGROUND',(-2,1),(-1,1),colors.palegreen),
        ('SPAN',(-2,1),(-1,1)),
        ('BACKGROUND',(-2,3),(-1,3),colors.yellow),
        ('SPAN',(-2,3),(-1,3)),
        ('BACKGROUND', (2, 3), (2, 4), colors.orange),
        ('SPAN',(2,3),(2,4)),
        ]

    t=Table(data,style=sty,repeatRows=2)
    lst.append(Paragraph("Illustrating splits with spans and repeatRows: nosplit", styleSheet['BodyText']))
    lst.append(t)
    lst.append(Spacer(0,6))
    if  1:
        lst.append(Paragraph("Illustrating splits with spans and repeatRows: split(4in,30)", styleSheet['BodyText']))
        for s in t.split(4*inch,30):
            lst.append(s)
            lst.append(Spacer(0,6))
        lst.append(Spacer(0,6))
        lst.append(Paragraph("Illustrating splits with spans and repeatRows: split(4in,36)", styleSheet['BodyText']))
        for s in t.split(4*inch,36):
            lst.append(s)
            lst.append(Spacer(0,6))
    lst.append(Paragraph("Illustrating splits with spans and repeatRows: split(4in,56)", styleSheet['BodyText']))
    lst.append(Spacer(0,6))
    for s in t.split(4*inch,56):
        lst.append(s)
        lst.append(Spacer(0,6))

    lst.append(PageBreak())
    from reportlab.lib.testutils import testsFolder
    I = Image(os.path.join(os.path.dirname(testsFolder),'tools','pythonpoint','demos','leftlogo.gif'))
    I.drawHeight = 1.25*inch*I.drawHeight / I.drawWidth
    I.drawWidth = 1.25*inch
    #I.drawWidth = 9.25*inch #uncomment to see better messaging
    P = Paragraph("<para align=center spaceb=3>The <b>ReportLab Left <font color=red>Logo</font></b> Image</para>", styleSheet["BodyText"])
    B = TableBarChart()
    BP = Paragraph("<para align=center spaceb=3>A bar chart in a cell.</para>", styleSheet["BodyText"])

    data=  [['A', 'B', 'C', Paragraph("<b>A pa<font color=red>r</font>a<i>graph</i></b><super><font color=yellow>1</font></super>",styleSheet["BodyText"]), 'D'],
            ['00', '01', '02', [I,P], '04'],
            ['10', '11', '12', [I,P], '14'],
            ['20', '21', '22', '23', '24'],
            ['30', '31', '32', '33', '34'],
            ['40', '41', '42', [B,BP], '44']]

    t=Table(data,style=[('GRID',(1,1),(-2,-2),1,colors.green),
                    ('BOX',(0,0),(1,-1),2,colors.red),
                    ('LINEABOVE',(1,2),(-2,2),1,colors.blue),
                    ('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
                    ('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    ('BACKGROUND', (1, 1), (1, 2), colors.lavender),
                    ('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    ('BOX',(0,0),(-1,-1),2,colors.black),
                    ('GRID',(0,0),(-1,-1),0.5,colors.black),
                    ('VALIGN',(3,0),(3,0),'BOTTOM'),
                    ('BACKGROUND',(3,0),(3,0),colors.limegreen),
                    ('BACKGROUND',(3,1),(3,1),colors.khaki),
                    ('ALIGN',(3,1),(3,1),'CENTER'),
                    ('BACKGROUND',(3,2),(3,2),colors.beige),
                    ('ALIGN',(3,2),(3,2),'LEFT'),
                    ])

    t._argW[3]=1.5*inch
    lst.append(t)

    # now for an attempt at column spanning.
    lst.append(PageBreak())
    data=  [['A', 'BBBBB', 'C', 'D', 'E'],
            ['00', '01', '02', '03', '04'],
            ['10', '11', '12', '13', '14'],
            ['20', '21', '22', '23', '24'],
            ['30', '31', '32', '33', '34']]
    sty = [
            ('ALIGN',(0,0),(-1,-1),'CENTER'),
            ('VALIGN',(0,0),(-1,-1),'TOP'),
            ('GRID',(0,0),(-1,-1),1,colors.green),
            ('BOX',(0,0),(-1,-1),2,colors.red),

            #span 'BBBB' across middle 3 cells in top row
            ('SPAN',(1,0),(3,0)),
            #now color the first cell in this range only,
            #i.e. the one we want to have spanned.  Hopefuly
            #the range of 3 will come out khaki.
            ('BACKGROUND',(1,0),(1,0),colors.khaki),

            ('SPAN',(0,2),(-1,2)),


            #span 'AAA'down entire left column
            ('SPAN',(0,0), (0, 1)),
            ('BACKGROUND',(0,0),(0,0),colors.cyan),
            ('TEXTCOLOR', (0,'splitfirst'), (-1,'splitfirst'), colors.cyan),
            ('TEXTCOLOR', (0,'splitlast'), (-1,'splitlast'), colors.red),
            ('BACKGROUND', (0,'splitlast'), (-1,'splitlast'), colors.pink),
            ('LINEBELOW', (0,'splitlast'), (-1,'splitlast'), 1, colors.grey,'butt'),
           ]
    t=Table(data,style=sty, colWidths = [20] * 5, rowHeights = [20]*5)
    lst.append(t)
    lst.append(Spacer(18,18))

    t=Table(data,style=sty, colWidths = [20] * 5, rowHeights = [20]*5)
    for s in t.split(4*inch,72):
        lst.append(s)
        lst.append(Spacer(0,6))

    # now for an attempt at percentage widths
    lst.append(Spacer(18,18))
    lst.append(Paragraph("This table has colWidths=5*['14%']!", styleSheet['BodyText']))
    t=Table(data,style=sty, colWidths = ['14%'] * 5, rowHeights = [20]*5)
    lst.append(t)

    lst.append(Spacer(18,18))
    lst.append(Paragraph("This table has colWidths=['14%','10%','19%','22%','*']!", styleSheet['BodyText']))
    t=Table(data,style=sty, colWidths = ['14%','10%','19%','22%','*'], rowHeights = [20]*5)
    lst.append(t)

    # Mike's test example
    lst.append(Spacer(18,18))
    lst.append(Paragraph('Mike\'s Spanning Example', styleSheet['Heading1']))
    data=  [[Paragraph('World Domination: The First Five Years', styleSheet['BodyText']), ''],
            [Paragraph('World <font color="green">Domination</font>: The First Five Years', styleSheet['BodyText']),''],
            [Paragraph('World Domination: The First Five Years', styleSheet['BodyText']), ''],
            ]
    t=Table(data, style=[('SPAN',(0,0),(1,0)),('SPAN',(0,1),(1,1)),('SPAN',(0,2),(1,2)),], colWidths = [3*cm,8*cm], rowHeights = [None]*3)
    lst.append(t)

    lst.append(Spacer(18,18))
    lst.append(Paragraph('Mike\'s Non-spanning Example', styleSheet['Heading1']))
    data=  [[Paragraph('World Domination: The First Five Years', styleSheet['BodyText'])],
            [Paragraph('World <font color="magenta">Domination</font>: The First Five Years', styleSheet['BodyText'])],
            [Paragraph('World Domination: The First Five Years', styleSheet['BodyText'])],
            ]
    t=Table(data, style=[], colWidths = [11*cm], rowHeights = [None]*3)
    lst.append(t)

    lst.append(Spacer(18,18))
    lst.append(Paragraph('xpre example', styleSheet['Heading1']))
    data=  [    [
                XPreformatted('Account Details', styleSheet['Heading3']),
                '', XPreformatted('Client Details', styleSheet['Heading3']),
                ],  #end of row 0
            ]
    t=Table(data, style=[], colWidths = [80,230.0,80], rowHeights = [None]*1)
    lst.append(t)

    lst.append(PageBreak())

    lst.append(Paragraph('Trying colour cycling in background', styleSheet['Heading1']))
    lst.append(Paragraph("This should alternate pale blue and uncolored by row", styleSheet['BodyText']))
    data=  [['001', '01', '02', '03', '04', '05'],
            ['002', '01', '02', '03', '04', '05'],
            ['003', '01', '02', '03', '04', '05'],
            ['004', '01', '02', '03', '04', '05'],
            ['005', '01', '02', '03', '04', '05'],
            ['006', '01', '02', '03', '04', '05'],
            ['007', '01', '02', '03', '04', '05'],
            ['008', '01', '02', '03', '04', '05'],
            ['009', '01', '02', '03', '04', '05'],
            ['010', '01', '02', '03', '04', '05'],

            ]
    t=Table(data,style=[
                    ('GRID',(0,0),(-1,-1),0.5,colors.grey),
                    ('ROWBACKGROUNDS', (0, 0), (-1, -1), (0xD0D0FF, None)),
                    ])
    lst.append(t)
    lst.append(Spacer(0,6))
    lst.append(Paragraph("And this should pale blue, pale pink and None by column", styleSheet['BodyText']))
    data=  [['001', '01', '02', '03', '04', '05'],
            ['002', '01', '02', '03', '04', '05'],
            ['003', '01', '02', '03', '04', '05'],
            ['004', '01', '02', '03', '04', '05'],
            ['005', '01', '02', '03', '04', '05'],
            ['006', '01', '02', '03', '04', '05'],
            ['007', '01', '02', '03', '04', '05'],
            ['008', '01', '02', '03', '04', '05'],
            ['009', '01', '02', '03', '04', '05'],
            ['010', '01', '02', '03', '04', '05'],

            ]
    t=Table(data,style=[
                    ('GRID',(0,0),(-1,-1),0.5,colors.grey),
                    ('COLBACKGROUNDS', (0, 0), (-1, -1), (0xD0D0FF, 0xFFD0D0, None)),
                    ])
    lst.append(t)

    lst.append(PageBreak())
    lst.append(Paragraph("This spanning example illustrates automatic removal of grids and lines in spanned cells!", styleSheet['BodyText']))
    lst.append(Spacer(0,6))
    data=  [['Top\nLeft', '', '02', '03', '04', '05', '06', '07'],
            ['', '', '12', 'Span (3,1) (6,2)', '','','','17'],
            ['20', '21', '22', '', '','','','27'],
            ['30', '31', '32', '33', '34','35','36','37'],
            ['40', 'In The\nMiddle', '', '', '44','45','46','47'],
            ['50', '', '', '', '54','55','56','57'],
            ['60', '', '', '','64', '65', 'Bottom\nRight', ''],
            ['70', '71', '72', '73','74', '75', '', '']]
    t=Table(data,style=[
            ('GRID',(0,0),(-1,-1),0.5,colors.grey),
            ('BACKGROUND',(0,0),(1,1),colors.palegreen),
            ('SPAN',(0,0),(1,1)),
            ('BACKGROUND',(-2,-2),(-1,-1), colors.pink),
            ('SPAN',(-2,-2),(-1,-1)),
            ('SPAN',(1,4),(3,6)),
            ('BACKGROUND',(1,4),(3,6), colors.lightblue),
            ('SPAN',(3,1),(6,2)),
            ('BACKGROUND',(3,1),(6,2), colors.peachpuff),
            ('VALIGN',(3,1),(6,2),'TOP'),
            ('LINEABOVE', (0,2),(-1,2), 1, colors.black, 0, None, None, 2, 2),
            ('LINEBEFORE', (3,0),(3,-1), 1, colors.black, 0, None, None, 2, 2),
            ])
    lst.append(t)

    lst.append(PageBreak())

    lst.append(Paragraph("und jetzt noch eine Tabelle mit 5000 Zeilen:", styleSheet['BodyText']))
    sty = [ ('GRID',(0,0),(-1,-1),1,colors.green),
            ('BOX',(0,0),(-1,-1),2,colors.red),
           ]
    data = [[str(i), Paragraph("xx "* (i%10), styleSheet["BodyText"]), Paragraph("blah "*(i%40), styleSheet["BodyText"])] for i in range(500)]
    t=LongTable(data, style=sty, colWidths = [50,100,200])
    lst.append(t)

    #Yuan Hong's bug tester
    lst.append(PageBreak())
    lst.append(Paragraph('Yian Hong\'s Bug Case (should not blow up)', styleSheet['Heading2']))
    data = ([['Col1', 'Col2', 'Col3', 'Col4', 'Col5']]+
                [['01', Paragraph('This is cell one that contains a paragraph.', styleSheet['Normal']), '02', '03', '04']
                    for i in range(50)])

    t = Table(data, ['20%']*5, repeatRows=1)
    t.setStyle(TableStyle([
        ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
        ('BOX', (0,0), (-1,-1), 0.25, colors.black),
        ('SPAN', (0,50), (-2,50)),
        ]))

    lst.append(t)
    lst.append(PageBreak())

    #Volker Haas' example extended
    #the optimal row heights are the solution of an LP similar to
    #
    #Objective function
    #   min: 3*h0+3*h1+3*h2+2*h3;
    #
    #constraints
    #   h0>=12;
    #   h1>=12;
    #   h2>=12;
    #   h3>=12;
    #   h0+h1+h2>=48;
    #   h0+h1>=12;
    #   h2+h3>=60;
    #
    #the solution H=[12,12,24,36]
    def makeTable(x,y):
        return Table([
                ['00', '01', '02', '03', '04', '05\nline2\nline3\nline4'],
                ['', '11', '12', x, '',''],
                ['20', '21', y, '23', '24',''],
                ['30', '31', '', '33', '34','35'],
                ],
                style=[
                    ('TOPPADDING',(0,0),(-1,-1),0),
                    ('BOTTOMPADDING',(0,0),(-1,-1),0),
                    ('RIGHTPADDING',(0,0),(-1,-1),0),
                    ('LEFTPADDING',(0,0),(-1,-1),0),
                    ('GRID',(0,0),(-1,-1),0.5,colors.grey),
                    ('BACKGROUND', (0, 0), (0, 1), colors.pink),
                    ('SPAN',(0,0),(0,1)),
                    ('BACKGROUND', (2, 2), (2, 3), colors.orange),
                    ('SPAN',(2,2),(2,3)),
                    ('SPAN',(3,1),(4,1)),
                    ('SPAN',(5,0),(5,2)),
                ])
    p_style= ParagraphStyle('Normal')
    lst.append(makeTable(
            Paragraph('This is a string',p_style),
            Paragraph('22<br/>blub<br/>asfd<br/>afd<br/>asdfs', p_style)
            ))

    lst.append(Spacer(10,10))
    lst.append(makeTable(
            XPreformatted('This is a string',p_style),
            Paragraph('22<br/>blub<br/>asfd<br/>afd<br/>asdfs', p_style)
            ))
    lst.append(Spacer(10,10))
    lst.append(makeTable(
            'This is a string',
            '22\nblub\nasfd\nafd\nasdfs',
            ))
    lst.append(Spacer(10,10))
    lst.append(makeTable(
            'This is a string',
            Paragraph('22<br/>blub<br/>asfd<br/>afd<br/>asdfs', p_style)
            ))
    SimpleDocTemplate(outputfile('test_platypus_tables_2.pdf'), showBoundary=1).build(lst)
Ejemplo n.º 10
0
    def test0(self):
        "This makes one long multi-page paragraph."

        # Build story.
        story = []

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet['Heading1']
        h1.spaceBefore = 18
        bt = styleSheet['BodyText']
        bt.spaceBefore = 6
        normalStyle = styleSheet['Code']

        story.append(Paragraph('Test of preformatted text wrapping', h1))

        story.append(Spacer(18, 18))

        txt = """Our Preformatted class can be used for printing simple blocks
of code. It respects whitespace and newlines, and will not normally attempt 
to wrap your code. However, if your individual lines are too long, this can 
overflow the width of the column and even run off the page. Three optional 
attributes - maximumLineLength, splitCharacters and newLineCharacter - 
can be used to do simple wrapping. maximumLineLength will force the text to
wrap. Note that this simply counts characters - it takes no account of
actual width on the page. The examples below wrap lines above a certain length
and add a '>' to the start of the following line.
"""

        story.append(Paragraph(txt, bt))

        story.append(Paragraph("", bt))

        code = """
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/platypus/xpreformatted.py
__version__='3.3.0'
__doc__='''A 'rich preformatted text' widget allowing internal markup'''

from reportlab.lib import PyFontify
from paragraph import Paragraph, cleanBlockQuotedText, _handleBulletWidth, ParaLines, _getFragWords, stringWidth, _sameFrag, getAscentDescent, imgVRange, imgNormV
from flowables import _dedenter

class XPreformatted(Paragraph):
    def __init__(self, text, style, bulletText = None, frags=None, caseSensitive=1, dedent=0):
        self.caseSensitive = caseSensitive
        cleaner = lambda text, dedent=dedent: ,'\\n'.join(_dedenter(text or '',dedent))
        self._setup(text, style, bulletText, frags, cleaner)

    def breakLines(self, width):
        if isinstance(width,list): maxWidths = [width]
        else: maxWidths = width
        lines = []
        lineno = 0
        maxWidth = maxWidths[lineno]
        style = self.style
        fFontSize = float(style.fontSize)
        requiredWidth = 0

        #for bullets, work out width and ensure we wrap the right amount onto line one
        _handleBulletWidth(self.bulletText,style,maxWidths)

        self.height = 0
        autoLeading = getattr(self,'autoLeading',getattr(style,'autoLeading',''))
        calcBounds = autoLeading not in ('','off')
        frags = self.frags
        nFrags= len(frags)
        if nFrags==1:
            f = frags[0]
            if hasattr(f,'text'):
                fontSize = f.fontSize
                fontName = f.fontName
                ascent, descent = getAscentDescent(fontName,fontSize)
                kind = 0
                L=f.text.split('\\n')
                for l in L:
                    currentWidth = stringWidth(l,fontName,fontSize)
                    requiredWidth = max(currentWidth,requiredWidth)
                    extraSpace = maxWidth-currentWidth
                    lines.append((extraSpace,l.split(' '),currentWidth))
                    lineno = lineno+1
                    maxWidth = lineno&lt;len(maxWidths) and maxWidths[lineno] or maxWidths[-1]
                blPara = f.clone(kind=kind, lines=lines,ascent=ascent,descent=descent,fontSize=fontSize)
            else:
                kind = f.kind
                lines = f.lines
                for L in lines:
                    if kind==0:
                        currentWidth = L[2]
                    else:
                        currentWidth = L.currentWidth
                    requiredWidth = max(currentWidth,requiredWidth)
                blPara = f.clone(kind=kind, lines=lines)

            self.width = max(self.width,requiredWidth)
            return blPara
        elif nFrags&lt;=0:
            return ParaLines(kind=0, fontSize=style.fontSize, fontName=style.fontName,
                            textColor=style.textColor, ascent=style.fontSize,descent=-0.2*style.fontSize,
                            lines=[])
        else:
            for L in _getFragLines(frags):
                currentWidth, n, w = _getFragWord(L,maxWidth)
                f = w[0][0]
                maxSize = f.fontSize
                maxAscent, minDescent = getAscentDescent(f.fontName,maxSize)
                words = [f.clone()]
                words[-1].text = w[0][1]
                for i in w[1:]:
                    f = i[0].clone()
                    f.text=i[1]
                    words.append(f)
                    fontSize = f.fontSize
                    fontName = f.fontName
                    if calcBounds:
                        cbDefn = getattr(f,'cbDefn',None)
                        if getattr(cbDefn,'width',0):
                            descent,ascent = imgVRange(imgNormV(cbDefn.height,fontSize),cbDefn.valign,fontSize)
                        else:
                            ascent, descent = getAscentDescent(fontName,fontSize)
                    else:
                        ascent, descent = getAscentDescent(fontName,fontSize)
                    maxSize = max(maxSize,fontSize)
                    maxAscent = max(maxAscent,ascent)
                    minDescent = min(minDescent,descent)

                lineno += 1
                maxWidth = lineno&lt;len(maxWidths) and maxWidths[lineno] or maxWidths[-1]
                requiredWidth = max(currentWidth,requiredWidth)
                extraSpace = maxWidth - currentWidth
                lines.append(ParaLines(extraSpace=extraSpace,wordCount=n, words=words, fontSize=maxSize, ascent=maxAscent,descent=minDescent,currentWidth=currentWidth))

            self.width = max(self.width,requiredWidth)
            return ParaLines(kind=1, lines=lines)

        return lines
"""

        story.append(
            Preformatted(code,
                         normalStyle,
                         dedent=0,
                         maxLineLength=60,
                         newLineChars='> '))

        doc = MyDocTemplate(outputfile('test_platypus_preformatted.pdf'))
        doc.multiBuild(story)
Ejemplo n.º 11
0
def createStandardCoverPage(page_size=PAGE_SIZE_LETTER,
                            total_pages=1,
                            recipient_name='',
                            recipient_phone='',
                            recipient_fax='',
                            sender_name='',
                            sender_phone='',
                            sender_fax='',
                            sender_email='',
                            regarding='',
                            message='',
                            preserve_formatting=False,
                            output=None):

    s = getSampleStyleSheet()

    story = []

    #print prop.locale
    #TTFSearchPath.append('/usr/share/fonts/truetype/arphic')
    #pdfmetrics.registerFont(TTFont('UMing', 'uming.ttf'))

    ps = ParagraphStyle(
        name="title",
        parent=None,
        fontName='helvetica-bold',
        #fontName='STSong-Light',
        #fontName = 'UMing',
        fontSize=72,
    )

    story.append(Paragraph("FAX", ps))

    story.append(Spacer(1, inch))

    ps = ParagraphStyle(
        name='normal',
        fontName='Times-Roman',
        #fontName='STSong-Light',
        #fontName='UMing',
        fontSize=12)

    recipient_name_label = Paragraph("To:", ps)
    recipient_name_text = Paragraph(escape(recipient_name[:64]), ps)

    recipient_fax_label = Paragraph("Fax:", ps)
    recipient_fax_text = Paragraph(escape(recipient_fax[:64]), ps)

    recipient_phone_label = Paragraph("Phone:", ps)
    recipient_phone_text = Paragraph(escape(recipient_phone[:64]), ps)

    sender_name_label = Paragraph("From:", ps)
    sender_name_text = Paragraph(escape(sender_name[:64]), ps)

    sender_phone_label = Paragraph("Phone:", ps)
    sender_phone_text = Paragraph(escape(sender_phone[:64]), ps)

    sender_email_label = Paragraph("Email:", ps)
    sender_email_text = Paragraph(escape(sender_email[:64]), ps)

    regarding_label = Paragraph("Regarding:", ps)
    regarding_text = Paragraph(escape(regarding[:128]), ps)

    date_time_label = Paragraph("Date:", ps)
    date_time_text = Paragraph(
        strftime("%a, %d %b %Y %H:%M:%S (%Z)", localtime()), ps)

    total_pages_label = Paragraph("Total Pages:", ps)
    total_pages_text = Paragraph("%d" % total_pages, ps)

    data = [[
        recipient_name_label, recipient_name_text, sender_name_label,
        sender_name_text
    ],
            [
                recipient_fax_label, recipient_fax_text, sender_phone_label,
                sender_phone_text
            ],
            [
                date_time_label, date_time_text, sender_email_label,
                sender_email_text
            ],
            [
                regarding_label, regarding_text, total_pages_label,
                total_pages_text
            ]]

    LIST_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
        #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
        #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
    ])

    story.append(HRFlowable(width='100%', color='black'))

    story.append(Table(data, style=LIST_STYLE))

    if message:
        MSG_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
            #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
            #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
            ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (-2, 1), (-1, -1)),
        ])

        story.append(HRFlowable(width='100%', color='black'))
        story.append(Spacer(1, 0.5 * inch))

        if preserve_formatting:
            message = '\n'.join(message[:2048].splitlines()[:32])

            data = [
                [Paragraph("Comments/Notes:", ps), ''],
                [Preformatted(escape(message), ps), ''],
            ]
        else:
            data = [
                [Paragraph("Comments/Notes:", ps), ''],
                [Paragraph(escape(message[:2048]), ps), ''],
            ]

        story.append(HRFlowable(width='100%', color='black'))
        story.append(Table(data, style=MSG_STYLE))
        story.append(HRFlowable(width='100%', color='black'))

    if page_size == PAGE_SIZE_LETTER:
        pgsz = letter
    elif page_size == PAGE_SIZE_LEGAL:
        pgsz = legal
    else:
        pgsz = A4

    if output is None:
        f_fd, f = utils.make_temp_file()
    else:
        f = output

    doc = SimpleDocTemplate(f, pagesize=pgsz)
    doc.build(story)

    return f
Ejemplo n.º 12
0
def createUrgentCoverPage(page_size=PAGE_SIZE_LETTER,
                          total_pages=1,
                          recipient_name='',
                          recipient_phone='',
                          recipient_fax='',
                          sender_name='',
                          sender_phone='',
                          sender_fax='',
                          sender_email='',
                          regarding='',
                          message='',
                          preserve_formatting=False,
                          output=None):

    s = getSampleStyleSheet()

    story = []
    i = Image(os.path.join(prop.image_dir, 'other', 'urgent_title.png'),
              width=424,
              height=92)
    i.hAlign = 'LEFT'
    story.append(i)
    story.append(Spacer(1, inch))
    story.append(HRFlowable(width='100%', color='black'))

    ps = ParagraphStyle(
        name='normal',
        fontName='Times-Roman',
        #fontName='STSong-Light',
        #fontName='UMing',
        fontSize=12)

    recipient_name_label = Paragraph("To:", ps)
    recipient_name_text = Paragraph(escape(recipient_name[:64]), ps)

    recipient_fax_label = Paragraph("Fax:", ps)
    recipient_fax_text = Paragraph(escape(recipient_fax[:64]), ps)

    recipient_phone_label = Paragraph("Phone:", ps)
    recipient_phone_text = Paragraph(escape(recipient_phone[:64]), ps)

    sender_name_label = Paragraph("From:", ps)
    sender_name_text = Paragraph(escape(sender_name[:64]), ps)

    sender_phone_label = Paragraph("Phone:", ps)
    sender_phone_text = Paragraph(escape(sender_phone[:64]), ps)

    sender_email_label = Paragraph("Email:", ps)
    sender_email_text = Paragraph(escape(sender_email[:64]), ps)

    regarding_label = Paragraph("Regarding:", ps)
    regarding_text = Paragraph(escape(regarding[:128]), ps)

    date_time_label = Paragraph("Date:", ps)
    date_time_text = Paragraph(
        strftime("%a, %d %b %Y %H:%M:%S (%Z)", localtime()), ps)

    total_pages_label = Paragraph("Total Pages:", ps)
    total_pages_text = Paragraph("%d" % total_pages, ps)

    data = [
        [recipient_name_label, recipient_name_text],
        [recipient_fax_label, recipient_fax_text],
        ['', ''],
        [sender_name_label, sender_name_text],
        [sender_phone_label, sender_phone_text],
        [sender_email_label, sender_email_text],
        ['', ''],
        [date_time_label, date_time_text],
        [total_pages_label, total_pages_text],
        [regarding_label, regarding_text],
    ]

    LIST_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
        #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
        #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
    ])

    story.append(Table(data, style=LIST_STYLE))
    story.append(HRFlowable(width='100%', color='black'))

    if message:
        MSG_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
            #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
            #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
            ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            #('SPAN', (-2, 1), (-1, -1)),
        ])

        #story.append(HRFlowable(width='100%', color='black'))
        story.append(Spacer(1, 0.5 * inch))

        #        if preserve_formatting:
        #            message = '\n'.join(message[:2048].splitlines()[:32])
        #
        #            data = [#[Paragraph("Comments/Notes:", ps), ''],
        #                    [Preformatted(escape(message), ps)],]
        #        else:
        #            data = [#[Paragraph("Comments/Notes:", ps), ''],
        #                    [Paragraph(escape(message[:2048]), ps), ''],]
        #
        #        #story.append(HRFlowable(width='100%', color='black'))
        #        #story.append(Table(data, style=MSG_STYLE))

        if preserve_formatting:
            message = '\n'.join(message[:2048].splitlines()[:32])
            story.append(Preformatted(escape(message), ps))
        else:
            story.append(Paragraph(escape(message), ps))

    if page_size == PAGE_SIZE_LETTER:
        pgsz = letter
    elif page_size == PAGE_SIZE_LEGAL:
        pgsz = legal
    else:
        pgsz = A4

    if output is None:
        f_fd, f = utils.make_temp_file()
    else:
        f = output

    doc = SimpleDocTemplate(f, pagesize=pgsz)
    doc.build(story)

    return f
Ejemplo n.º 13
0
def writeCompareReportAsPdf(resultpath, outputpath, err, label):
    doc = SimpleDocTemplate(outputpath,
                            pagesize=A4,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=40,
                            bottomMargin=18)

    # Get the different files and parse the text out of them
    Report = []
    Title = "Virus Report"
    SubTitle = "(Comparisons)"
    Date = getTimestamp()
    CompareTxtPath = dF.findFileByName(resultpath, "compare_results.txt")[0]
    CompareTxt = dF.readInFile(CompareTxtPath)
    SequencePart = dF.findNext4LinesByKeyword(CompareTxtPath, "Sequences")
    StructurePart = dF.findNext4LinesByKeyword(CompareTxtPath,
                                               "Secondary structure:")
    GCPart = dF.findNext2LinesByKeyword(CompareTxtPath, "GC content")
    EnergyPart = dF.findNext2LinesByKeyword(
        CompareTxtPath, "Energies of secondary structure:")
    NumberOfProteinsPart = dF.findNext2LinesByKeyword(CompareTxtPath,
                                                      "Number of Proteins")
    ErrorTxt1 = dF.findLineByKeyword(
        CompareTxtPath,
        "PDF1 was not generated by the VirusToolBox, stopped execution")
    ErrorTxt2 = dF.findLineByKeyword(
        CompareTxtPath,
        "PDF2 was not generated by the VirusToolBox, stopped execution")

    # Define some styles
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    styles.add(ParagraphStyle(name='MyTitle', alignment=TA_CENTER))

    # Set text onto the Pdf
    ptext = '<font name=Helvetica-Bold size=18>%s</font>' % Title
    Report.append(Paragraph(ptext, styles['MyTitle']))
    Report.append(Spacer(1, 12))

    ptext = '<font name=Helvetica size=14>%s</font>' % SubTitle
    Report.append(Paragraph(ptext, styles['MyTitle']))
    Report.append(Spacer(1, 12))

    ptext = '<font name=Helvetica size=12>%s</font>' % Date
    Report.append(Paragraph(ptext, styles["MyTitle"]))
    Report.append(Spacer(1, 12))

    if (CompareTxt[0] == "The file doesn't exist"):
        err.write("________________")
        err.write("Write the comparison Pdf:")
        err.write("comparison.txt file doesn't exist")
        addTextToLabel(label, "Create Pdf file without statistics")
        ptext = '<font name=Helvetica-Bold size=16>%s</font>' % "The comparison file doesn't exist !"
        Report.append(Paragraph(ptext, styles["MyTitle"]))
    else:
        if ErrorTxt1:
            ptext = '<font name=Helvetica size=10>%s</font>' % "PDF1 was not generated by the VirusToolBox, stopped execution"
            Report.append(Paragraph(ptext, styles['MyTitle']))

        elif ErrorTxt2:
            ptext = '<font name=Helvetica size=10>%s</font>' % "PDF2 was not generated by the VirusToolBox, stopped execution"
            Report.append(Paragraph(ptext, styles['MyTitle']))

        else:
            ptext = '<font name=Helvetica size=10>%s</font>' % "Sequences:"
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % SequencePart[0]
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % SequencePart[1]
            Report.append(Paragraph(ptext, styles['Justify']))
            Report.append(Spacer(1, 12))

            ptext = '<font name=Helvetica size=7>%s</font>' % SequencePart[2]
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % SequencePart[3]
            Report.append(Paragraph(ptext, styles['Justify']))
            Report.append(Spacer(1, 12))

            ptext = '<font name=Helvetica size=10>%s</font>' % "Secondary Structure:"
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % StructurePart[0]
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % StructurePart[1]
            Report.append(Paragraph(ptext, styles['Justify']))
            Report.append(Spacer(1, 12))

            ptext = '<font name=Helvetica size=7>%s</font>' % StructurePart[2]
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % StructurePart[3]
            Report.append(Paragraph(ptext, styles['Justify']))
            Report.append(Spacer(1, 12))

            ptext = '<font name=Helvetica size=10>%s</font>' % "Energies of secondary structure:"
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % EnergyPart[0]
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % EnergyPart[1]
            Report.append(Paragraph(ptext, styles['Justify']))
            Report.append(Spacer(1, 12))

            ptext = '<font name=Helvetica size=10>%s</font>' % "GC content:"
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % GCPart[0]
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % GCPart[1]
            Report.append(Paragraph(ptext, styles['Justify']))
            Report.append(Spacer(1, 12))

            ptext = '<font name=Helvetica size=10>%s</font>' % "Number of Proteins:"
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % NumberOfProteinsPart[
                0]
            Report.append(Paragraph(ptext, styles['Justify']))

            ptext = '<font name=Helvetica size=7>%s</font>' % NumberOfProteinsPart[
                1]
            Report.append(Paragraph(ptext, styles['Justify']))
            Report.append(Spacer(1, 12))

            for i in range(22, len(CompareTxt)):
                ptext = CompareTxt[i]
                Report.append(Preformatted(ptext, styles['Code']))

    doc.build(Report)
Ejemplo n.º 14
0
    def __init__(self, data, colWidths=None, rowHeights=None, style=None,
                repeatRows=0, repeatCols=0, splitByRow=1, emptyTableAction=None):
        self.hAlign = 'CENTER'
        self.vAlign = 'MIDDLE'
        if type(data) not in _SeqTypes:
            raise ValueError, "%s invalid data type" % self.identity()
        self._nrows = nrows = len(data)
        self._cellvalues = []
        _seqCW = type(colWidths) in _SeqTypes
        _seqRH = type(rowHeights) in _SeqTypes
        if nrows: self._ncols = ncols = max(map(_rowLen,data))
        elif colWidths and _seqCW: ncols = len(colWidths)
        else: ncols = 0
        if not emptyTableAction: emptyTableAction = rl_config.emptyTableAction
        if not (nrows and ncols):
            if emptyTableAction=='error':
                raise ValueError, "%s must have at least a row and column" % self.identity()
            elif emptyTableAction=='indicate':
                self.__class__ = Preformatted
                global _emptyTableStyle
                if '_emptyTableStyle' not in globals().keys():
                    _emptyTableStyle = ParagraphStyle('_emptyTableStyle')
                    _emptyTableStyle.textColor = colors.red
                    _emptyTableStyle.backColor = colors.yellow
                Preformatted.__init__(self,'%s(%d,%d)' % (self.__class__.__name__,nrows,ncols), _emptyTableStyle)
            elif emptyTableAction=='ignore':
                self.__class__ = Spacer
                Spacer.__init__(self,0,0)
            else:
                raise ValueError, '%s bad emptyTableAction: "%s"' % (self.identity(),emptyTableAction)
            return

        self._cellvalues = data
        if not _seqCW: colWidths = ncols*[colWidths]
        elif len(colWidths) != ncols:
            raise ValueError, "%s data error - %d columns in data but %d in grid" % (self.identity(),ncols, len(colWidths))
        if not _seqRH: rowHeights = nrows*[rowHeights]
        elif len(rowHeights) != nrows:
            raise ValueError, "%s data error - %d rows in data but %d in grid" % (self.identity(),nrows, len(rowHeights))
        for i in range(nrows):
            if len(data[i]) != ncols:
                raise ValueError, "%s not enough data points in row %d!" % (self.identity(),i)
        self._rowHeights = self._argH = rowHeights
        self._colWidths = self._argW = colWidths
        cellrows = []
        for i in range(nrows):
            cellcols = []
            for j in range(ncols):
                cellcols.append(CellStyle(`(i,j)`))
            cellrows.append(cellcols)
        self._cellStyles = cellrows

        self._bkgrndcmds = []
        self._linecmds = []
        self._spanCmds = []
        self.repeatRows = repeatRows
        self.repeatCols = repeatCols
        self.splitByRow = splitByRow

        if style:
            self.setStyle(style)
Ejemplo n.º 15
0
    def wrap(self, availWidth, availHeight):

        start, end = sections[self._section_id]

        self.lines = [ "Page {}/{}".format(self.canv.getPageNumber() - start.page_number + 1, end.page_number - start.page_number + 1) ]
        return Preformatted.wrap(self, availWidth, availHeight)
Ejemplo n.º 16
0
 def __init__(self, section_id, style):
     self._section_id = section_id
     Preformatted.__init__(self, "", style)