コード例 #1
0
 def doSome():
     for i in range(10):
         story.append(Paragraph("Heading 1 always starts a new page (%d)" % len(story), h1))
         for j in range(3):
             story.append(
                 Paragraph(
                     "Heading1 paragraphs should always"
                     "have a page break before.  Heading 2 on the other hand"
                     "should always have a FRAME break before (%d)" % len(story),
                     bt,
                 )
             )
             story.append(Paragraph("Heading 2 always starts a new frame (%d)" % len(story), h2))
             story.append(
                 Paragraph(
                     "Heading1 paragraphs should always"
                     "have a page break before.  Heading 2 on the other hand"
                     "should always have a FRAME break before (%d)" % len(story),
                     bt,
                 )
             )
             for j in range(3):
                 story.append(Paragraph(randomText(theme=PYTHON, sentences=2) + " (%d)" % len(story), bt))
                 story.append(Paragraph("I should never be at the bottom of a frame (%d)" % len(story), h3))
                 story.append(Paragraph(randomText(theme=PYTHON, sentences=1) + " (%d)" % len(story), bt))
コード例 #2
0
def _test0(self):
    "This makes one long multi-page paragraph."
    from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile

    # Build story.
    story = []

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet["Heading1"]
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1
    h1.outlineLevel = 0

    h2 = styleSheet["Heading2"]
    h2.backColor = colors.cyan
    h2.keepWithNext = 1
    h2.outlineLevel = 1

    bt = styleSheet["BodyText"]

    story.append(Paragraph("""Cross-Referencing Test""", styleSheet["Title"]))
    story.append(
        Paragraph(
            """
        Subsequent pages test cross-references: indexes, tables and individual
        cross references.  The number in brackets at the end of each paragraph
        is its position in the story. (%d)"""
            % len(story),
            bt,
        )
    )

    story.append(Paragraph("""Table of Contents:""", styleSheet["Title"]))
    toc = TableOfContents()
    story.append(toc)

    chapterNum = 1
    for i in range(10):
        story.append(Paragraph("Chapter %d: Chapters always starts a new page" % chapterNum, h1))
        chapterNum = chapterNum + 1
        for j in range(3):
            story.append(
                Paragraph(
                    "Heading1 paragraphs should always"
                    "have a page break before.  Heading 2 on the other hand"
                    "should always have a FRAME break before (%d)" % len(story),
                    bt,
                )
            )
            story.append(Paragraph("Heading 2 should always be kept with the next thing (%d)" % len(story), h2))
            for j in range(3):
                story.append(Paragraph(randomText(theme=PYTHON, sentences=2) + " (%d)" % len(story), bt))
                story.append(Paragraph("I should never be at the bottom of a frame (%d)" % len(story), h2))
                story.append(Paragraph(randomText(theme=PYTHON, sentences=1) + " (%d)" % len(story), bt))
    story.append(Paragraph("The Index which goes at the back", h1))
    story.append(SimpleIndex())

    doc = MyDocTemplate(outputfile("test_platypus_xref.pdf"))
    doc.multiBuild(story)
コード例 #3
0
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet["Heading1"]
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet["Heading2"]
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet["Heading3"]
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet["BodyText"]

    story.append(
        Paragraph(
            """
        Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)"""
            % (time.ctime(time.time()), len(story)),
            bt,
        )
    )

    for i in range(10):
        story.append(Paragraph("Heading 1 always starts a new page (%d)" % len(story), h1))
        for j in range(3):
            story.append(
                Paragraph(
                    "Heading1 paragraphs should always"
                    "have a page break before.  Heading 2 on the other hand"
                    "should always have a FRAME break before (%d)" % len(story),
                    bt,
                )
            )
            story.append(Paragraph("Heading 2 always starts a new frame (%d)" % len(story), h2))
            story.append(
                Paragraph(
                    "Heading1 paragraphs should always"
                    "have a page break before.  Heading 2 on the other hand"
                    "should always have a FRAME break before (%d)" % len(story),
                    bt,
                )
            )
            for j in range(3):
                story.append(Paragraph(randomText(theme=PYTHON, sentences=2) + " (%d)" % len(story), bt))
                story.append(Paragraph("I should never be at the bottom of a frame (%d)" % len(story), h3))
                story.append(Paragraph(randomText(theme=PYTHON, sentences=1) + " (%d)" % len(story), bt))

    doc = MyDocTemplate(outputfile("test_platypus_breaking.pdf"))
    doc.multiBuild(story)
コード例 #4
0
 def doSome():
     for i in range(10):
         story.append(Paragraph('Heading 1 always starts a new page (%d)' % len(story), h1))
         for j in range(3):
             story.append(Paragraph('Heading1 paragraphs should always'
                             'have a page break before.  Heading 2 on the other hand'
                             'should always have a FRAME break before (%d)' % len(story), bt))
             story.append(Paragraph('Heading 2 always starts a new frame (%d)' % len(story), h2))
             story.append(Paragraph('Heading1 paragraphs should always'
                             'have a page break before.  Heading 2 on the other hand'
                             'should always have a FRAME break before (%d)' % len(story), bt))
             for j in range(3):
                 story.append(Paragraph(randomText(theme=PYTHON, sentences=2)+' (%d)' % len(story), bt))
                 story.append(Paragraph('I should never be at the bottom of a frame (%d)' % len(story), h3))
                 story.append(Paragraph(randomText(theme=PYTHON, sentences=1)+' (%d)' % len(story), bt))
コード例 #5
0
ファイル: doclet.py プロジェクト: Xhiffer/Lama-projet-l2
def testRml():
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    from reportlab.platypus.flowables import Spacer
    from reportlab.lib.randomtext import randomText

    templ = SimpleDocTemplate('doclet_output.pdf')

    #need a style
    story = []
    normal = ParagraphStyle('normal')
    normal.firstLineIndent = 18
    normal.spaceBefore = 6

    para = Paragraph(
        "Test of doclets.  You should see a little table with a reversed word.",
        normal)
    story.append(para)

    story.append(Spacer(36, 36))

    theDoclet = TestReverseDoclet()
    story.append(theDoclet.asFlowable())

    for i in range(5):
        para = Paragraph(randomText(), normal)
        story.append(para)

    templ.build(story)

    print('saved doclet_output.pdf')
コード例 #6
0
ファイル: doclet.py プロジェクト: AndyKovv/hostel
def testRml():
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    from reportlab.platypus.flowables import Spacer
    from reportlab.lib.randomtext import randomText

    templ = SimpleDocTemplate('doclet_output.pdf')

    #need a style
    story = []
    normal = ParagraphStyle('normal')
    normal.firstLineIndent = 18
    normal.spaceBefore = 6

    para = Paragraph("Test of doclets.  You should see a little table with a reversed word.", normal)
    story.append(para)

    story.append(Spacer(36,36))
                 
    theDoclet = TestReverseDoclet()
    story.append(theDoclet.asFlowable())
    
    for i in range(5):
        para = Paragraph(randomText(), normal)
        story.append(para)



    templ.build(story)    

    print('saved doclet_output.pdf')
コード例 #7
0
    def test0(self):
        """Test story with TOC and a cascaded header hierarchy.

        The story should contain exactly one table of contents that is
        immediatly followed by a list of of cascaded levels of header
        lines, each nested one level deeper than the previous one.

        Features to be visually confirmed by a human being are:

            1. TOC lines are indented in multiples of 1 cm.
            2. Wrapped TOC lines continue with additional 0.5 cm indentation.
            3. Only entries of every second level has links
            ...
        """

        maxLevels = 12

        # Create styles to be used for document headers
        # on differnet levels.
        headerLevelStyles = []
        for i in range(maxLevels):
            headerLevelStyles.append(makeHeaderStyle(i))

        # Create styles to be used for TOC entry lines
        # for headers on differnet levels.
        tocLevelStyles = []
        d, e = tableofcontents.delta, tableofcontents.epsilon
        for i in range(maxLevels):
            tocLevelStyles.append(makeTocHeaderStyle(i, d, e))

        # Build story.
        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']

        description = '<font color=red>%s</font>' % self.test0.__doc__
        story.append(XPreformatted(description, bt))

        toc = tableofcontents.TableOfContents()
        toc.levelStyles = tocLevelStyles
        story.append(toc)

        for i in range(maxLevels):
            story.append(
                Paragraph('HEADER, LEVEL %d' % i, headerLevelStyles[i]))
            #now put some body stuff in.
            txt = xmlEscape(randomtext.randomText(randomtext.PYTHON, 5))
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

        path = outputfile('test_platypus_toc.pdf')
        doc = MyDocTemplate(path)
        doc.multiBuild(story)
コード例 #8
0
ファイル: test_platypus_toc.py プロジェクト: Jbaumotte/web2py
    def test0(self):
        """Test story with TOC and a cascaded header hierarchy.

        The story should contain exactly one table of contents that is
        immediatly followed by a list of of cascaded levels of header
        lines, each nested one level deeper than the previous one.

        Features to be visually confirmed by a human being are:

            1. TOC lines are indented in multiples of 1 cm.
            2. Wrapped TOC lines continue with additional 0.5 cm indentation.
            3. Only entries of every second level has links
            ...
        """

        maxLevels = 12

        # Create styles to be used for document headers
        # on differnet levels.
        headerLevelStyles = []
        for i in range(maxLevels):
            headerLevelStyles.append(makeHeaderStyle(i))

        # Create styles to be used for TOC entry lines
        # for headers on differnet levels.
        tocLevelStyles = []
        d, e = tableofcontents.delta, tableofcontents.epsilon
        for i in range(maxLevels):
            tocLevelStyles.append(makeTocHeaderStyle(i, d, e))

        # Build story.
        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']

        description = '<font color=red>%s</font>' % self.test0.__doc__
        story.append(XPreformatted(description, bt))

        toc = tableofcontents.TableOfContents()
        toc.levelStyles = tocLevelStyles
        story.append(toc)

        for i in range(maxLevels):
            story.append(Paragraph('HEADER, LEVEL %d' % i,
                                   headerLevelStyles[i]))
            #now put some body stuff in.
            txt = randomtext.randomText(randomtext.PYTHON, 5)
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

        path = outputfile('test_platypus_toc.pdf')
        doc = MyDocTemplate(path)
        doc.multiBuild(story)
コード例 #9
0
    def test0(self):
        '''
        Test case for Indexes. This will draw an index %sat the end of the
        document with dots seperating the indexing terms from the page numbers.
        Index terms are grouped by their first 2, and first 3 characters.
        The page numbers should be clickable and link to the indexed word.
        '''
        # Build story.
        
        for headers in False, True:
            path = outputfile('test_platypus_index%s.pdf' % (headers and '_headers' or ''))
            doc = MyDocTemplate(path)
            story = []
            styleSheet = getSampleStyleSheet()
            bt = styleSheet['BodyText']
    
            description = '<font color=red>%s</font>' % (self.test0.__doc__  % (headers and 'with alphabetic headers ' or ''))
            story.append(Paragraph(description, bt))
            index = SimpleIndex(dot=' . ', headers=headers)

            def addParas(words):
                words = [asUnicode(w) for w in words]
                txt = u' '.join([(len(w) > 5 and u'<index item=%s/>%s' % (quoteattr(commajoin([w[:2], w[:3], w])), w) or w) for w in words])
                para = Paragraph(txt, makeBodyStyle())
                story.append(para)
    
            for i in xrange(20):
                addParas(randomtext.randomText(randomtext.PYTHON, 5).split(' '))
            addParas([u+w for u in u'E\xc8\xc9\xca\xcb' for w in (u'erily',u'asily')])
            addParas([u+w for u in u'A\xc0\xc4\xc1\xc3\xc2' for w in (u'dvance',u'ttend')])
            addParas([u+w for u in u'O\xd2\xd6\xd3\xd2' for w in (u'rdinary',u'verflow')])
            addParas([u+w for u in u'U\xd9\xdc\xdb' for w in (u'ndertow',u'nbeliever')])
            addParas([u+w for u in u'e\xe8\xea\xeb\xe9' for w in (u'ventide',u'lision')])
            addParas([u+w for u in u'o\xf2\xf5\xf3\xf4' for w in (u'verture',u'ntology')])

            #test ampersand in index term
            txt = '\nMarks &amp; Spencer - purveyors of fine groceries, underwear and ampersands - should have their initials displayed however they were input.\n<index item="M&amp;S,groceries"/><index item="M&amp;S,underwear"/><index item="M&amp;S,ampersands"/>'
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)
        

            story.append(index)
    
            doc.build(story, canvasmaker=index.getCanvasMaker())
コード例 #10
0
    def test0(self):
        """
        Test case for Indexes. This will draw an index %sat the end of the
        document with dots seperating the indexing terms from the page numbers.
        Index terms are grouped by their first 2, and first 3 characters.
        The page numbers should be clickable and link to the indexed word.
        """
        # Build story.

        for headers in False, True:
            path = outputfile("test_platypus_index%s.pdf" % (headers and "_headers" or ""))
            doc = MyDocTemplate(path)
            story = []
            styleSheet = getSampleStyleSheet()
            bt = styleSheet["BodyText"]

            description = "<font color=red>%s</font>" % (
                self.test0.__doc__ % (headers and "with alphabetic headers " or "")
            )
            story.append(Paragraph(description, bt))
            index = SimpleIndex(dot=" . ", headers=headers)

            for i in range(20):
                words = randomtext.randomText(randomtext.PYTHON, 5).split(" ")
                txt = " ".join(
                    [
                        (len(w) > 5 and "<index item=%s/>%s" % (quoteattr(commajoin([w[:2], w[:3], w])), w) or w)
                        for w in words
                    ]
                )
                para = Paragraph(txt, makeBodyStyle())
                story.append(para)

            # test ampersand in index term
            txt = '\nMarks &amp; Spencer - purveyors of fine groceries, underwear and ampersands - should have their initials displayed however they were input.\n<index item="M&amp;S,groceries"/><index item="M&amp;S,underwear"/><index item="M&amp;S,ampersands"/>'
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

            story.append(index)

            doc.build(story, canvasmaker=index.getCanvasMaker())
コード例 #11
0
ファイル: doctemplate.py プロジェクト: eaudeweb/naaya
    def run():
        objects_to_draw = []
        from reportlab.lib.styles import ParagraphStyle
        #from paragraph import Paragraph
        from doctemplate import SimpleDocTemplate

        #need a style
        normal = ParagraphStyle('normal')
        normal.firstLineIndent = 18
        normal.spaceBefore = 6
        from reportlab.lib.randomtext import randomText
        import random
        for i in range(15):
            height = 0.5 + (2*random.random())
            box = XBox(6 * inch, height * inch, 'Box Number %d' % i)
            objects_to_draw.append(box)
            para = Paragraph(randomText(), normal)
            objects_to_draw.append(para)

        SimpleDocTemplate('doctemplate.pdf').build(objects_to_draw,
            onFirstPage=myFirstPage,onLaterPages=myLaterPages)
コード例 #12
0
    def run():
        objects_to_draw = []
        from reportlab.lib.styles import ParagraphStyle
        #from paragraph import Paragraph
        from reportlab.platypus.doctemplate import SimpleDocTemplate

        #need a style
        normal = ParagraphStyle('normal')
        normal.firstLineIndent = 18
        normal.spaceBefore = 6
        from reportlab.lib.randomtext import randomText
        import random
        for i in range(15):
            height = 0.5 + (2*random.random())
            box = XBox(6 * inch, height * inch, 'Box Number %d' % i)
            objects_to_draw.append(box)
            para = Paragraph(randomText(), normal)
            objects_to_draw.append(para)

        SimpleDocTemplate('doctemplate.pdf').build(objects_to_draw,
            onFirstPage=myFirstPage,onLaterPages=myLaterPages)
コード例 #13
0
    def test0(self):
        '''
        Test case for Indexes. This will draw an index %sat the end of the
        document with dots seperating the indexing terms from the page numbers.
        Index terms are grouped by their first 2, and first 3 characters.
        The page numbers should be clickable and link to the indexed word.
        '''
        # Build story.

        for headers in False, True:
            path = outputfile('test_platypus_index%s.pdf' %
                              (headers and '_headers' or ''))
            doc = MyDocTemplate(path)
            story = []
            styleSheet = getSampleStyleSheet()
            bt = styleSheet['BodyText']

            description = '<font color=red>%s</font>' % (
                self.test0.__doc__ %
                (headers and 'with alphabetic headers ' or ''))
            story.append(Paragraph(description, bt))
            index = SimpleIndex(dot=' . ', headers=headers)

            for i in range(20):
                words = randomtext.randomText(randomtext.PYTHON, 5).split(' ')
                txt = ' '.join([(len(w) > 5 and '<index item=%s/>%s' %
                                 (quoteattr(commajoin([w[:2], w[:3], w])), w)
                                 or w) for w in words])
                para = Paragraph(txt, makeBodyStyle())
                story.append(para)

            #test ampersand in index term
            txt = '\nMarks &amp; Spencer - purveyors of fine groceries, underwear and ampersands - should have their initials displayed however they were input.\n<index item="M&S,groceries"/><index item="M&S,underwear"/><index item="M&amp;S,ampersands"/>'
            para = Paragraph(txt, makeBodyStyle())
            story.append(para)

            story.append(index)

            doc.build(story, canvasmaker=index.getCanvasMaker())
コード例 #14
0
    def test2(self):
        "This makes one long multi-page paragraph in multi-pass for testing docWhile etc etc"
        from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile
        from test_platypus_xref import MyDocTemplate
        from reportlab.platypus.tableofcontents import TableOfContents, SimpleIndex
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.platypus import Paragraph
        from reportlab.lib import colors
        from reportlab.lib.randomtext import randomText, PYTHON

        # Build story.
        story = []

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet['Heading1']
        h1.pageBreakBefore = 1
        h1.keepWithNext = 1
        h1.outlineLevel = 0

        h2 = styleSheet['Heading2']
        h2.backColor = colors.cyan
        h2.keepWithNext = 1
        h2.outlineLevel = 1

        bt = styleSheet['BodyText']

        story.append(Paragraph("""Cross-Referencing Test""", styleSheet["Title"]))
        story.append(Paragraph("""
            Subsequent pages test cross-references: indexes, tables and individual
            cross references.  The number in brackets at the end of each paragraph
            is its position in the story. (%d)""" % len(story), bt))

        story.append(Paragraph("""Table of Contents:""", styleSheet["Title"]))
        toc = TableOfContents()
        story.append(toc)

        chapterNum = 1
        for i in range(10):
            story.append(Paragraph('Chapter %d: Chapters always starts a new page' % chapterNum, h1))
            chapterNum += chapterNum
            story.append(DocAssign('chapterNum',chapterNum))
            for j in range(3):
                story.append(Paragraph('Heading1 paragraphs should always'
                                'have a page break before.  Heading 2 on the other hand'
                                'should always have a FRAME break before (%d)' % len(story), bt))
                story.append(Paragraph('Heading 2 should always be kept with the next thing (%d)' % len(story), h2))
                for j in range(3):
                    story.append(Paragraph(randomText(theme=PYTHON, sentences=2)+' (%d)' % len(story), bt))
                    story.append(Paragraph('I should never be at the bottom of a frame (%d)' % len(story), h2))
                    story.append(Paragraph(randomText(theme=PYTHON, sentences=1)+' (%d)' % len(story), bt))

            story.extend([
                    DocAssign('currentFrame','doc.frame.id'),
                    DocAssign('currentPageTemplate','doc.pageTemplate.id'),
                    DocAssign('aW','availableWidth'),
                    DocAssign('aH','availableHeight'),
                    DocAssign('aWH','availableWidth,availableHeight'),
                    DocAssign('i',3,life='forever'),
                    DocIf('i>3',Paragraph('The value of i is larger than 3',bt),Paragraph('The value of i is not larger than 3',bt)),
                    DocIf('i==3',Paragraph('The value of i is equal to 3',bt),Paragraph('The value of i is not equal to 3',bt)),
                    DocIf('i<3',Paragraph('The value of i is less than 3',bt),Paragraph('The value of i is not less than 3',bt)),
                    DocWhile('i',[DocPara('i',format='The value of i is %(__expr__)d',style=bt),DocExec('i-=1')]),
                    DocPara('repr(doc._nameSpace)',escape=True),
                    ])
        story.append(Paragraph('The Index which goes at the back', h1))
        story.append(SimpleIndex())

        doc = MyDocTemplate(outputfile('test_platypus_programming_multipass.pdf'))
        doc.multiBuild(story)
コード例 #15
0
ファイル: test_paragraphs.py プロジェクト: fbrcosta/reportlab
    def test0(self):
        """Test...

        The story should contain...

        Features to be visually confirmed by a human being are:

            1. ...
            2. ...
            3. ...
        """

        story = []
        SA = story.append

        #need a style
        styNormal = ParagraphStyle('normal')
        styGreen = ParagraphStyle('green',parent=styNormal,textColor=green)
        styDots = ParagraphStyle('styDots',parent=styNormal,endDots='.')
        styDots1 = ParagraphStyle('styDots1',parent=styNormal,endDots=ABag(text=' -',dy=2,textColor='red'))
        styDotsR = ParagraphStyle('styDotsR',parent=styNormal,alignment=TA_RIGHT,endDots=' +')
        styDotsC = ParagraphStyle('styDotsC',parent=styNormal,alignment=TA_CENTER,endDots=' *')
        styDotsJ = ParagraphStyle('styDotsJ',parent=styNormal,alignment=TA_JUSTIFY,endDots=' =')

        istyDots = ParagraphStyle('istyDots',parent=styNormal,firstLineIndent=12,leftIndent=6,endDots='.')
        istyDots1 = ParagraphStyle('istyDots1',parent=styNormal,firstLineIndent=12,leftIndent=6,endDots=ABag(text=' -',dy=2,textColor='red'))
        istyDotsR = ParagraphStyle('istyDotsR',parent=styNormal,firstLineIndent=12,leftIndent=6,alignment=TA_RIGHT,endDots=' +')
        istyDotsC = ParagraphStyle('istyDotsC',parent=styNormal,firstLineIndent=12,leftIndent=6,alignment=TA_CENTER,endDots=' *')
        istyDotsJ = ParagraphStyle('istyDotsJ',parent=styNormal,firstLineIndent=12,leftIndent=6,alignment=TA_JUSTIFY,endDots=' =')

        # some to test
        stySpaced = ParagraphStyle('spaced',
                                   parent=styNormal,
                                   spaceBefore=12,
                                   spaceAfter=12)

        SA(Paragraph("This is a normal paragraph. "+ randomText(), styNormal))
        SA(Paragraph("There follows a paragraph with only \"&lt;br/&gt;\"", styNormal))
        SA(Paragraph("<br/>", styNormal))
        SA(Paragraph("This has 12 points space before and after, set in the style. " + randomText(), stySpaced))
        SA(Paragraph("This is normal. " + randomText(), styNormal))
        SA(Paragraph("""<para spacebefore="12" spaceafter="12">
              This has 12 points space before and after, set inline with
              XML tag.  It works too.""" + randomText() + "</para",
                        styNormal))

        SA(Paragraph("This is normal. " + randomText(), styNormal))
  
        styBackground = ParagraphStyle('MyTitle',
                                       fontName='Helvetica-Bold',
                                       fontSize=24,
                                       leading=28,
                                       textColor=white,
                                       backColor=navy)
        SA(Paragraph("This is a title with a background. ", styBackground))
        SA(Paragraph("""<para backcolor="pink">This got a background from the para tag</para>""", styNormal))
        SA(Paragraph("""<para>\n\tThis has newlines and tabs on the front but inside the para tag</para>""", styNormal))
        SA(Paragraph("""<para>  This has spaces on the front but inside the para tag</para>""", styNormal))
        SA(Paragraph("""\n\tThis has newlines and tabs on the front but no para tag""", styNormal))
        SA(Paragraph("""  This has spaces on the front but no para tag""", styNormal))
        SA(Paragraph("""This has <font color=blue>blue text</font> here.""", styNormal))
        SA(Paragraph("""This has <i>italic text</i> here.""", styNormal))
        SA(Paragraph("""This has <b>bold text</b> here.""", styNormal))
        SA(Paragraph("""This has <u>underlined text</u> here.""", styNormal))
        SA(Paragraph("""This has <font color=blue><u>blue and <font color=red>red</font> underlined text</u></font> here.""", styNormal))
        SA(Paragraph("""<u>green underlining</u>""", styGreen))
        SA(Paragraph("""<u>green <font size=+4><i>underlining</font></i></u>""", styGreen))
        SA(Paragraph("""This has m<super>2</super> a superscript.""", styNormal))
        SA(Paragraph("""This has m<sub>2</sub> a subscript. Like H<sub>2</sub>O!""", styNormal))
        SA(Paragraph("""This has a font change to <font name=Helvetica>Helvetica</font>.""", styNormal))
        #This one fails:
        #SA(Paragraph("""This has a font change to <font name=Helvetica-Oblique>Helvetica-Oblique</font>.""", styNormal))
        SA(Paragraph("""This has a font change to <font name=Helvetica><i>Helvetica in italics</i></font>.""", styNormal))

        SA(Paragraph('''This one uses upper case tags and has set caseSensitive=0: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''', styNormal, caseSensitive=0))
        SA(Paragraph('''The same as before, but has set not set caseSensitive, thus the tags are ignored: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''', styNormal))
        SA(Paragraph('''This one uses fonts with size "14pt" and also uses the em and strong tags: Here comes <font face="Helvetica" size="14pt">Helvetica 14</font> with <Strong>strong</Strong> <em>emphasis</em>.''', styNormal, caseSensitive=0))
        SA(Paragraph('''This uses a font size of 3cm: Here comes <font face="Courier" size="3cm">Courier 3cm</font> and normal again.''', styNormal, caseSensitive=0))
        SA(Paragraph('''This is just a very long silly text to see if the <FONT face="Courier">caseSensitive</FONT> flag also works if the paragraph is <EM>very</EM> long. '''*20, styNormal, caseSensitive=0))

        SA(Paragraph('''Simple paragraph with dots''', styDots))
        SA(Paragraph('''Simple indented paragraph with dots''', istyDots))
        SA(Paragraph('''Simple centred paragraph with stars''', styDotsC))
        SA(Paragraph('''Simple centred indented paragraph with stars''', istyDotsC))
        SA(Paragraph('''Simple right justified paragraph with pluses, but no pluses''', styDotsR))
        SA(Paragraph('''Simple right justified indented paragraph with pluses, but no pluses''', istyDotsR))
        SA(Paragraph('''Simple justified paragraph with equals''', styDotsJ))
        SA(Paragraph('''Simple justified indented paragraph with equals''', istyDotsJ))
        SA(Paragraph('''A longer simple paragraph with dots''', styDots))
        SA(Paragraph('''A longer simple indented paragraph with dots''', istyDots))
        SA(Paragraph('A very much' +50*' longer'+' simple paragraph with dots', styDots))
        SA(Paragraph('A very much' +50*' longer'+' simple indented paragraph with dots', istyDots))
        SA(Paragraph('A very much' +50*' longer'+' centred simple paragraph with stars', styDotsC))
        SA(Paragraph('A very much' +50*' longer'+' centred simple indented paragraph with stars', istyDotsC))
        SA(Paragraph('A very much' +50*' longer'+' right justified simple paragraph with pluses, but no pluses', styDotsR))
        SA(Paragraph('A very much' +50*' longer'+' right justified simple indented paragraph with pluses, but no pluses', istyDotsR))
        SA(Paragraph('A very much' +50*' longer'+' justified simple paragraph with equals', styDotsJ))
        SA(Paragraph('A very much' +50*' longer'+' justified simple indented paragraph with equals', istyDotsJ))
        SA(Paragraph('''Simple paragraph with dashes that have a dy and a textColor.''', styDots1))
        SA(Paragraph('''Simple indented paragraph with dashes that have a dy and a textColor.''', istyDots1))
        SA(Paragraph('''Complex <font color="green">paragraph</font> with dots''', styDots))
        SA(Paragraph('''Complex <font color="green">indented paragraph</font> with dots''', istyDots))
        SA(Paragraph('''Complex centred <font color="green">paragraph</font> with stars''', styDotsC))
        SA(Paragraph('''Complex centred <font color="green">indented paragraph</font> with stars''', istyDotsC))
        SA(Paragraph('''Complex right justfied <font color="green">paragraph</font> with pluses, but no pluses''', styDotsR))
        SA(Paragraph('''Complex right justfied <font color="green">indented paragraph</font> with pluses, but no pluses''', istyDotsR))
        SA(Paragraph('''Complex justfied <font color="green">paragraph</font> with equals''', styDotsJ))
        SA(Paragraph('''Complex justfied <font color="green">indented paragraph</font> with equals''', istyDotsJ))
        SA(Paragraph('''A longer complex <font color="green">paragraph</font> with dots''', styDots))
        SA(Paragraph('''A longer complex <font color="green">indented paragraph</font> with dots''', istyDots))
        SA(Paragraph('A very much' +50*' longer'+' complex <font color="green">paragraph</font> with dots', styDots))
        SA(Paragraph('A very much' +50*' longer'+' complex <font color="green">indented paragraph</font> with dots', istyDots))
        SA(Paragraph('''Complex <font color="green">paragraph</font> with dashes that have a dy and a textColor.''', styDots1))
        SA(Paragraph('''Complex <font color="green">indented paragraph</font> with dashes that have a dy and a textColor.''', istyDots1))
        SA(Paragraph('A very much' +50*' longer'+' centred complex <font color="green">paragraph</font> with stars', styDotsC))
        SA(Paragraph('A very much' +50*' longer'+' centred complex <font color="green">indented paragraph</font> with stars', istyDotsC))
        SA(Paragraph('A very much' +50*' longer'+' right justified <font color="green">complex</font> paragraph with pluses, but no pluses', styDotsR))
        SA(Paragraph('A very much' +50*' longer'+' right justified <font color="green">complex</font> indented paragraph with pluses, but no pluses', istyDotsR))
        SA(Paragraph('A very much' +50*' longer'+' justified complex <font color="green">paragraph</font> with equals', styDotsJ))
        SA(Paragraph('A very much' +50*' longer'+' justified complex <font color="green">indented paragraph</font> with equals', istyDotsJ))

        SA(Indenter("1cm"))
        SA(Paragraph("<para><bullet bulletIndent='-1cm' bulletOffsetY='2'><seq id='s0'/>)</bullet>Indented list bulletOffsetY=2. %s</para>" % randomText(), styNormal))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(XPreformatted("<para leftIndent='0.5cm' backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(XPreformatted("<para leftIndent='0.5cm' backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(Indenter("-1cm"))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Indenter("-1cm"))
        SA(Paragraph("<para>Indented list using seqChain/Format<seqChain order='s0 s1 s2 s3 s4'/><seqReset id='s0'/><seqFormat id='s0' value='1'/><seqFormat id='s1' value='a'/><seqFormat id='s2' value='i'/><seqFormat id='s3' value='A'/><seqFormat id='s4' value='I'/></para>", stySpaced))
        SA(Indenter("1cm"))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(XPreformatted("<para backcolor=pink boffsety='-3'><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list bulletOffsetY=-3.</para>", styNormal))
        SA(XPreformatted("<para backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(Indenter("-1cm"))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(XPreformatted("<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(Indenter("1cm"))
        SA(XPreformatted("<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line1</para>", styNormal))
        SA(XPreformatted("<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line2</para>", styNormal))
        SA(Indenter("-1cm"))
        SA(XPreformatted("<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(Indenter("-1cm"))
        SA(Indenter("-1cm"))

        template = SimpleDocTemplate(outputfile('test_paragraphs.pdf'),
                                     showBoundary=1)
        template.build(story,
            onFirstPage=myFirstPage, onLaterPages=myLaterPages)
コード例 #16
0
ファイル: test_platypus_toc.py プロジェクト: Jbaumotte/web2py
    def test2(self):
        chapters = 20   #so we know we use only one page
        from reportlab.lib.colors import pink

        #TOC and this HParagraph class just handle the collection
        TOC = []
        fontSize = 14
        leading = fontSize*1.2
        descent = 0.2*fontSize
        x = 2.5*cm          #these come from the frame size
        y = (25+2.5)*cm - leading
        x1 = (15+2.5)*cm

        class HParagraph(Paragraph):
            def __init__(self,key,text,*args,**kwds):
                self._label = text
                self._key = key
                Paragraph.__init__(self,text,*args,**kwds)

            def draw(self):
                Paragraph.draw(self)
                TOC.append((self._label,self.canv.getPageNumber(),self._key))
                self.canv.bookmarkHorizontal('TOC_%s' % self._key,0,+20)

        class UseForm(Flowable):
            _ZEROSIZE = 1
            def __init__(self,formName):
                self._formName = formName
                self.width = self.height = 0

            def draw(self):
                self.canv.doForm(self._formName)
                for i in xrange(chapters):
                    yb = y - i*leading      #baseline
                    self.canv.linkRect('','TOC_%s' % i,(x,yb-descent,x1,yb+fontSize),thickness=0.5,color=pink,relative=0)

            def drawOn(self,canvas,x,y,_sW=0):
                Flowable.drawOn(self,canvas,0,0,canvas._pagesize[0])

        class MakeForm(UseForm):
            def draw(self):
                canv = self.canv
                canv.saveState()
                canv.beginForm(self._formName)
                canv.setFont("Helvetica",fontSize)
                for i,(text,pageNumber,key) in enumerate(TOC):
                    yb = y - i*leading      #baseline
                    canv.drawString(x,yb,text)
                    canv.drawRightString(x1,y-i*leading,str(pageNumber))
                canv.endForm()
                canv.restoreState()

        headerStyle = makeHeaderStyle(0)
        S = [Spacer(0,180),UseForm('TOC')]
        RT = 'STARTUP COMPUTERS BLAH BUZZWORD STARTREK PRINTING PYTHON CHOMSKY'.split()
        for i in range(chapters):
            S.append(PageBreak())
            S.append(HParagraph(i,'This is chapter %d' % (i+1), headerStyle))
            txt = randomtext.randomText(RT[i*13 % len(RT)], 15)
            para = Paragraph(txt, makeBodyStyle())
            S.append(para)

        S.append(MakeForm('TOC'))

        doc = MyDocTemplate(outputfile('test_platypus_toc_simple.pdf'))
        doc.build(S)
コード例 #17
0
ファイル: test_platypus_toc.py プロジェクト: Jbaumotte/web2py
    def test1(self):
        """This shows a table which would take more than one page,
        and need multiple passes to render.  But we preload it
        with the right headings to make it go faster.  We used
        a simple 100-chapter document with one level.
        """

        chapters = 30   #goes over one page
        
        headerStyle = makeHeaderStyle(0)
        d, e = tableofcontents.delta, tableofcontents.epsilon
        tocLevelStyle = makeTocHeaderStyle(0, d, e)

        # Build most of the story; we'll re-use it to 
        # make documents with different numbers of passes.

        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']

        description = '<font color=red>%s</font>' % self.test1.__doc__
        story.append(XPreformatted(description, bt))

        for i in range(chapters):
            story.append(PageBreak())
            story.append(Paragraph('This is chapter %d' % (i+1),
                                   headerStyle))
            #now put some lengthy body stuff in.  
            for paras in range(random.randint(1,3)):
                txt = randomtext.randomText(randomtext.PYTHON, 5)
                para = Paragraph(txt, makeBodyStyle())
                story.append(para)


        #try 1: empty TOC, 3 passes

        toc = tableofcontents.TableOfContents()
        toc.levelStyles = [tocLevelStyle]   #only need one
        story1 = [toc] + story


        path = outputfile('test_platypus_toc_preload.pdf')
        doc = MyDocTemplate(path)
        passes = doc.multiBuild(story1)
        self.assertEquals(passes, 3)

        #try 2: now preload the TOC with the entries

        toc = tableofcontents.TableOfContents()
        toc.levelStyles = [tocLevelStyle]   #only need one
        tocEntries = []
        for i in range(chapters):
            #add tuple of (level, text, pageNum, key)
            #with an initial guess of pageNum=0
            tocEntries.append((0, 'This is chapter %d' % (i+1), 0, None))
        toc.addEntries(tocEntries)

        story2 = [toc] + story


        path = outputfile('test_platypus_toc_preload.pdf')
        doc = MyDocTemplate(path)
        passes = doc.multiBuild(story2)
        self.assertEquals(passes, 2)



        #try 3: preload again but try to be really smart and work out
        #in advance what page everything starts on.  We cannot
        #use a random story for this.


        toc3 = tableofcontents.TableOfContents()
        toc3.levelStyles = [tocLevelStyle]   #only need one
        tocEntries = []
        for i in range(chapters):
            #add tuple of (level, text, pageNum, key)
            #with an initial guess of pageNum= 3
            tocEntries.append((0, 'This is chapter %d' % i, 2+i, None))
        toc3.addEntries(tocEntries)

        story3 = [toc3] 
        for i in range(chapters):
            story3.append(PageBreak())
            story3.append(Paragraph('This is chapter %d' % (i+1),
                                   headerStyle))
            txt = """
                The paragraphs in this are not at all random, because
                we need to be absolutely, totally certain they will fit 
                on one page.  Each chapter will be one page long.
            """
            para = Paragraph(txt, makeBodyStyle())
            story3.append(para)


        path = outputfile('test_platypus_toc_preload.pdf')
        doc = MyDocTemplate(path)
        passes = doc.multiBuild(story3)
コード例 #18
0
    def test1(self):
        if rl_invariant: random.seed(888147853)
        styleSheet = getSampleStyleSheet()
        doc = SimpleDocTemplate(outputfile('test_platypus_lists1.pdf'),
                                showBoundary=True)
        story = []
        sty = [
            ('GRID', (0, 0), (-1, -1), 1, colors.green),
            ('BOX', (0, 0), (-1, -1), 2, colors.red),
        ]
        normal = styleSheet['BodyText']
        bold = normal.clone('bold', fontName='Helvetica-Bold')
        lpSty = normal.clone('lpSty', spaceAfter=18)
        data = [[
            str(i + 1),
            Paragraph("xx " * (i % 10), styleSheet["BodyText"]),
            Paragraph(("blah " * (i % 40)), normal)
        ] for i in range(5)]
        data1 = [[
            str(i + 1),
            Paragraph(["zz ", "yy "][i] * (i + 3), styleSheet["BodyText"]),
            Paragraph(("duh  " * (i + 3)), normal)
        ] for i in range(2)]
        OL = ListFlowable([
            Paragraph("A table with 5 rows", lpSty),
            Table(data, style=sty, colWidths=[50, 100, 200]),
            ListItem(
                Paragraph("A sublist", normal),
                value=7,
            ),
            ListFlowable(
                [
                    Paragraph("Another table with 3 rows", normal),
                    Table(data[:3], style=sty, colWidths=[60, 90, 180]),
                    Paragraph(TEXTS[0], normal),
                ],
                bulletType='i',
            ),
            Paragraph("An unordered sublist", normal),
            ListFlowable(
                [
                    Paragraph("A table with 2 rows", normal),
                    ListItem(Table(data1, style=sty, colWidths=[60, 90, 180]),
                             bulletColor='green'),
                    ListItem(Paragraph(TEXTS[2], normal),
                             bulletColor='red',
                             value='square')
                ],
                bulletType='bullet',
                start='circle',
            ),
            Paragraph(TEXTS[1], normal),
        ])

        story.append(OL)

        story.append(PageBreak())
        story.append(
            Paragraph(
                "Now try a list with a very long URL in it.  Without splitting the long word it used to be that this can push out the right page margin",
                normal))
        OL = ListFlowable([
            Paragraph(TEXTS[1], normal),
            Paragraph(
                '''For details about pairing the smart card reader with the Android device, refer to the baiMobile specification: 
<a href="http://www.biometricassociates.com/downloads/user-guides/baiMobile-3000MP-User-Guide-for-Android-v2.0.pdf" color="blue">http://www.biometricassociates.com/downloads/user-guides/make-the-url-even-longer/baiMobile-3000MP-User-Guide-for-Android-v2.0.pdf</a>.''',
                normal),
            Paragraph(TEXTS[1], normal),
        ])

        story.append(OL)

        story.append(
            Paragraph(
                "Same as above with a simple paragraph for the long word",
                normal))
        OL = ListFlowable([
            Paragraph(TEXTS[1], normal),
            Paragraph(
                '''For details about pairing the smart card reader with the Android device, refer to the baiMobile specification: 
http://www.biometricassociates.com/downloads/user-guides/make-the-url-even-longer/baiMobile-3000MP-User-Guide-for-Android-v2.0.pdf.''',
                normal),
            Paragraph(TEXTS[1], normal),
        ])
        story.append(OL)

        story.append(
            Paragraph(
                "Same as above with a simple unicode paragraph for the long word",
                normal))
        OL = ListFlowable([
            Paragraph(TEXTS[1], normal),
            Paragraph(
                u'''For details about pairing the smart card reader with the Android device, refer to the baiMobile specification: 
http://www.biometricassociates.com/downloads/user-guides/make-the-url-even-longer/baiMobile-3000MP-User-Guide-for-Android-v2.0.pdf.''',
                normal),
            Paragraph(TEXTS[1], normal),
        ])
        story.append(OL)

        story.append(
            ListFlowable(
                [
                    Paragraph("Level 0.1", normal),
                    Paragraph("Level 0.2", normal),
                    ListFlowable([
                        Paragraph("Level 1.1", normal),
                        Paragraph("Level 1.1", normal),
                        ListFlowable([
                            Paragraph("Level 2.1", normal),
                            Paragraph("Level 2.1", normal),
                            Paragraph("Level 2.3", normal),
                        ], ),
                        Paragraph("Level 1.4", normal),
                    ], ),
                    Paragraph("Level 0.4", normal),
                ],
                bulletType='1',
                start='10',
            ), )

        story.append(PageBreak())
        story.append(Paragraph("DDIndenter", style=normal))
        story.append(Paragraph("Coffee", style=bold))
        story.append(
            DDIndenter(Paragraph("Black hot drink", style=normal),
                       leftIndent=36))
        story.append(Paragraph("Milk", style=bold))
        story.append(
            DDIndenter(Paragraph("White cold drink", style=normal),
                       leftIndent=36))
        story.append(Paragraph("Whiskey", style=bold))
        story.append(
            DDIndenter(Paragraph("A nice alcoholic drink", style=normal),
                       leftIndent=36))
        story.append(PageBreak())
        story.append(Paragraph("MultiCol", style=normal))
        RT = 'STARTUP COMPUTERS BLAH BUZZWORD STARTREK PRINTING PYTHON CHOMSKY CHOMSKY'.split(
        )
        for i in range(5):
            topic = RT[randint(0, len(RT) - 1)]
            np = randint(2, 6)
            story.append(
                MultiCol(
                    [[Paragraph('Column %d' % (i + 1, ), style=bold)], [],
                     [
                         Paragraph(xmlEscape(
                             randomtext.randomText(topic, randint(1, 7))),
                                   style=normal) for j in range(np)
                     ]],
                    widths=['20%', 3, '80%'],
                ))

        story.append(PageBreak())
        story.append(Paragraph("MultiCol 2", style=normal))
        for i in range(5):
            topic = RT[randint(0, len(RT) - 1)]
            np = randint(2, 6)
            story.append(
                MultiCol(
                    [([Paragraph('Column %d' % (i + 1, ), style=bold)] + [
                        Paragraph(xmlEscape(
                            randomtext.randomText(topic, randint(1, 7))),
                                  style=normal) for j in range(np)
                    ]), [],
                     [
                         Paragraph(xmlEscape(
                             randomtext.randomText(topic, randint(1, 7))),
                                   style=normal) for j in range(np)
                     ]],
                    widths=['50%', 5, '50%'],
                ))

        doc.build(story)
コード例 #19
0
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []
    a = story.append

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet['Heading2']
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet['Heading3']
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet['BodyText']
    btj = ParagraphStyle('bodyText1j',parent=bt,alignment=TA_JUSTIFY)
    btr = ParagraphStyle('bodyText1r',parent=bt,alignment=TA_RIGHT)
    btc = ParagraphStyle('bodyText1c',parent=bt,alignment=TA_CENTER)
    a(Paragraph("""
        <a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)""" % (
            time.ctime(time.time()), len(story)), bt))

    for i in range(10):
        a(Paragraph('Heading 1 always starts a new page (%d)' % len(story), h1))
        for j in range(3):
            a(Paragraph('Heading1 paragraphs should always'
                            'have a page break before.  Heading 2 on the other hand'
                            'should always have a FRAME break before (%d)' % len(story), bt))
            a(Paragraph('Heading 2 always starts a new frame (%d)' % len(story), h2))
            a(Paragraph('Heading1 paragraphs should always'
                            'have a page break before.  Heading 2 on the other hand'
                            'should always have a FRAME break before (%d)' % len(story), bt))
            for j in range(3):
                a(Paragraph(randomText(theme=PYTHON, sentences=2)+' (%d)' % len(story), bt))
                a(Paragraph('I should never be at the bottom of a frame (%d)' % len(story), h3))
                a(Paragraph(randomText(theme=PYTHON, sentences=1)+' (%d)' % len(story), bt))

    for align,bts in [('left',bt),('JUSTIFIED',btj),('RIGHT',btr),('CENTER',btc)]:
        a(Paragraph('Now we do &lt;br/&gt; tests(align=%s)' % align, h1))
        a(Paragraph('First off no br tags',h3))
        a(Paragraph(_text1,bts))
        a(Paragraph("&lt;br/&gt; after 'the' in line 4",h3))
        a(Paragraph(_text1.replace('forms of the','forms of the<br/>',1),bts))
        a(Paragraph("2*&lt;br/&gt; after 'the' in line 4",h3))
        a(Paragraph(_text1.replace('forms of the','forms of the<br/><br/>',1),bts))
        a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5",h3))
        a(Paragraph(_text1.replace('I suggested ','I suggested<br/>',1),bts))
        a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5",h3))
        a(Paragraph(_text1.replace('I suggested ','I suggested<br/><br/>',1),bts))
        a(Paragraph("&lt;br/&gt; at the end of the paragraph!",h3))
        a(Paragraph("""text one<br/>text two<br/>""",bts))
        a(Paragraph("Border with &lt;br/&gt; at the end of the paragraph!",h3))
        bt1 = ParagraphStyle('bodyText1',bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""",bt1))
        a(Paragraph("Border no &lt;br/&gt; at the end of the paragraph!",h3))
        bt1 = ParagraphStyle('bodyText1',bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two""",bt1))
        a(Paragraph("Different border style!",h3))
        bt2 = ParagraphStyle('bodyText1',bt1)
        bt2.borderWidth = 1.5
        bt2.borderColor = colors.toColor('blue')
        bt2.backColor = colors.gray
        bt2.borderRadius = 3
        bt2.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""",bt2))
    for i in 0, 1, 2:
        P = Paragraph("""This is a paragraph with <font color='blue'><a href='#top'>with an incredibly
long and boring link in side of it that
contains lots and lots of stupidly boring and worthless information.
So that we can split the link and see if we get problems like Dinu's.
I hope we don't, but you never do Know.</a></font>""",bt)
        a(P)

    doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf'))
    doc.multiBuild(story)
コード例 #20
0
def _test0(self):
    "This makes one long multi-page paragraph."
    from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile

    # Build story.
    story = []

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1
    h1.outlineLevel = 0

    h2 = styleSheet['Heading2']
    h2.backColor = colors.cyan
    h2.keepWithNext = 1
    h2.outlineLevel = 1

    bt = styleSheet['BodyText']

    story.append(Paragraph("""Cross-Referencing Test""", styleSheet["Title"]))
    story.append(
        Paragraph(
            """
        Subsequent pages test cross-references: indexes, tables and individual
        cross references.  The number in brackets at the end of each paragraph
        is its position in the story. (%d)""" % len(story), bt))

    story.append(Paragraph("""Table of Contents:""", styleSheet["Title"]))
    toc = TableOfContents()
    story.append(toc)

    chapterNum = 1
    for i in range(10):
        story.append(
            Paragraph(
                'Chapter %d: Chapters always starts a new page' % chapterNum,
                h1))
        chapterNum = chapterNum + 1
        for j in range(3):
            story.append(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            story.append(
                Paragraph(
                    'Heading 2 should always be kept with the next thing (%d)'
                    % len(story), h2))
            for j in range(3):
                story.append(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=2) +
                        ' (%d)' % len(story), bt))
                story.append(
                    Paragraph(
                        'I should never be at the bottom of a frame (%d)' %
                        len(story), h2))
                story.append(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=1) +
                        ' (%d)' % len(story), bt))
    story.append(Paragraph('The Index which goes at the back', h1))
    story.append(SimpleIndex())

    doc = MyDocTemplate(outputfile('test_platypus_xref.pdf'))
    doc.multiBuild(story)
コード例 #21
0
    def test2(self):
        "This makes one long multi-page paragraph in multi-pass for testing docWhile etc etc"
        from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile
        from test_platypus_xref import MyDocTemplate
        from reportlab.platypus.tableofcontents import TableOfContents, SimpleIndex
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.platypus import Paragraph
        from reportlab.lib import colors
        from reportlab.lib.randomtext import randomText, PYTHON

        # Build story.
        story = []

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet['Heading1']
        h1.pageBreakBefore = 1
        h1.keepWithNext = 1
        h1.outlineLevel = 0

        h2 = styleSheet['Heading2']
        h2.backColor = colors.cyan
        h2.keepWithNext = 1
        h2.outlineLevel = 1

        bt = styleSheet['BodyText']

        story.append(
            Paragraph("""Cross-Referencing Test""", styleSheet["Title"]))
        story.append(
            Paragraph(
                """
            Subsequent pages test cross-references: indexes, tables and individual
            cross references.  The number in brackets at the end of each paragraph
            is its position in the story. (%d)""" % len(story), bt))

        story.append(Paragraph("""Table of Contents:""", styleSheet["Title"]))
        toc = TableOfContents()
        story.append(toc)

        chapterNum = 1
        for i in range(10):
            story.append(
                Paragraph(
                    'Chapter %d: Chapters always starts a new page' %
                    chapterNum, h1))
            chapterNum += chapterNum
            story.append(DocAssign('chapterNum', chapterNum))
            for j in range(3):
                story.append(
                    Paragraph(
                        'Heading1 paragraphs should always'
                        'have a page break before.  Heading 2 on the other hand'
                        'should always have a FRAME break before (%d)' %
                        len(story), bt))
                story.append(
                    Paragraph(
                        'Heading 2 should always be kept with the next thing (%d)'
                        % len(story), h2))
                for j in range(3):
                    story.append(
                        Paragraph(
                            randomText(theme=PYTHON, sentences=2) +
                            ' (%d)' % len(story), bt))
                    story.append(
                        Paragraph(
                            'I should never be at the bottom of a frame (%d)' %
                            len(story), h2))
                    story.append(
                        Paragraph(
                            randomText(theme=PYTHON, sentences=1) +
                            ' (%d)' % len(story), bt))

            story.extend([
                DocAssign('currentFrame', 'doc.frame.id'),
                DocAssign('currentPageTemplate', 'doc.pageTemplate.id'),
                DocAssign('aW', 'availableWidth'),
                DocAssign('aH', 'availableHeight'),
                DocAssign('aWH', 'availableWidth,availableHeight'),
                DocAssign('i', 3, life='forever'),
                DocIf('i>3', Paragraph('The value of i is larger than 3', bt),
                      Paragraph('The value of i is not larger than 3', bt)),
                DocIf('i==3', Paragraph('The value of i is equal to 3', bt),
                      Paragraph('The value of i is not equal to 3', bt)),
                DocIf('i<3', Paragraph('The value of i is less than 3', bt),
                      Paragraph('The value of i is not less than 3', bt)),
                DocWhile('i', [
                    DocPara('i',
                            format='The value of i is %(__expr__)d',
                            style=bt),
                    DocExec('i-=1')
                ]),
                DocPara('repr(doc._nameSpace)', escape=True),
            ])
        story.append(Paragraph('The Index which goes at the back', h1))
        story.append(SimpleIndex())

        doc = MyDocTemplate(
            outputfile('test_platypus_programming_multipass.pdf'))
        doc.multiBuild(story)
コード例 #22
0
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []
    a = story.append

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet["Heading1"]
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet["Heading2"]
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet["Heading3"]
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet["BodyText"]
    a(
        Paragraph(
            """
        Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)"""
            % (time.ctime(time.time()), len(story)),
            bt,
        )
    )

    for i in xrange(10):
        a(Paragraph("Heading 1 always starts a new page (%d)" % len(story), h1))
        for j in xrange(3):
            a(
                Paragraph(
                    "Heading1 paragraphs should always"
                    "have a page break before.  Heading 2 on the other hand"
                    "should always have a FRAME break before (%d)" % len(story),
                    bt,
                )
            )
            a(Paragraph("Heading 2 always starts a new frame (%d)" % len(story), h2))
            a(
                Paragraph(
                    "Heading1 paragraphs should always"
                    "have a page break before.  Heading 2 on the other hand"
                    "should always have a FRAME break before (%d)" % len(story),
                    bt,
                )
            )
            for j in xrange(3):
                a(Paragraph(randomText(theme=PYTHON, sentences=2) + " (%d)" % len(story), bt))
                a(Paragraph("I should never be at the bottom of a frame (%d)" % len(story), h3))
                a(Paragraph(randomText(theme=PYTHON, sentences=1) + " (%d)" % len(story), bt))

    a(Paragraph("Now we do &lt;br/&gt; tests", h1))
    a(Paragraph("First off no br tags", h3))
    a(Paragraph(_text1, bt))
    a(Paragraph("&lt;br/&gt; after 'the' in line 4", h3))
    a(Paragraph(_text1.replace("forms of the", "forms of the<br/>", 1), bt))
    a(Paragraph("2*&lt;br/&gt; after 'the' in line 4", h3))
    a(Paragraph(_text1.replace("forms of the", "forms of the<br/><br/>", 1), bt))
    a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5", h3))
    a(Paragraph(_text1.replace("I suggested ", "I suggested<br/>", 1), bt))
    a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5", h3))
    a(Paragraph(_text1.replace("I suggested ", "I suggested<br/><br/>", 1), bt))
    a(Paragraph("&lt;br/&gt; at the end of the paragraph!", h3))
    a(Paragraph("""text one<br/>text two<br/>""", bt))
    a(Paragraph("Border with &lt;nr/&gt; at the end of the paragraph!", h3))
    bt1 = ParagraphStyle("bodyText1", bt)
    bt1.borderWidth = 0.5
    bt1.borderColor = colors.toColor("red")
    bt1.backColor = colors.pink
    bt1.borderRadius = 2
    bt1.borderPadding = 3
    a(Paragraph("""text one<br/>text two<br/>""", bt1))
    a(Paragraph("Border no &lt;nr/&gt; at the end of the paragraph!", h3))
    bt1 = ParagraphStyle("bodyText1", bt)
    bt1.borderWidth = 0.5
    bt1.borderColor = colors.toColor("red")
    bt1.backColor = colors.pink
    bt1.borderRadius = 2
    bt1.borderPadding = 3
    a(Paragraph("""text one<br/>text two""", bt1))
    a(Paragraph("Different border style!", h3))
    bt2 = ParagraphStyle("bodyText1", bt1)
    bt2.borderWidth = 1.5
    bt2.borderColor = colors.toColor("blue")
    bt2.backColor = colors.gray
    bt2.borderRadius = 3
    bt2.borderPadding = 3
    a(Paragraph("""text one<br/>text two<br/>""", bt2))

    doc = MyDocTemplate(outputfile("test_platypus_breaking.pdf"))
    doc.multiBuild(story)
コード例 #23
0
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []
    a = story.append

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet['Heading2']
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet['Heading3']
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet['BodyText']
    btj = ParagraphStyle('bodyText1j', parent=bt, alignment=TA_JUSTIFY)
    btr = ParagraphStyle('bodyText1r', parent=bt, alignment=TA_RIGHT)
    btc = ParagraphStyle('bodyText1c', parent=bt, alignment=TA_CENTER)
    a(
        Paragraph(
            """
        <a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)""" %
            (time.ctime(time.time()), len(story)), bt))

    for i in xrange(10):
        a(Paragraph('Heading 1 always starts a new page (%d)' % len(story),
                    h1))
        for j in xrange(3):
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            a(
                Paragraph(
                    'Heading 2 always starts a new frame (%d)' % len(story),
                    h2))
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            for j in xrange(3):
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=2) +
                        ' (%d)' % len(story), bt))
                a(
                    Paragraph(
                        'I should never be at the bottom of a frame (%d)' %
                        len(story), h3))
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=1) +
                        ' (%d)' % len(story), bt))

    for align, bts in [('left', bt), ('JUSTIFIED', btj), ('RIGHT', btr),
                       ('CENTER', btc)]:
        a(Paragraph('Now we do &lt;br/&gt; tests(align=%s)' % align, h1))
        a(Paragraph('First off no br tags', h3))
        a(Paragraph(_text1, bts))
        a(Paragraph("&lt;br/&gt; after 'the' in line 4", h3))
        a(
            Paragraph(_text1.replace('forms of the', 'forms of the<br/>', 1),
                      bts))
        a(Paragraph("2*&lt;br/&gt; after 'the' in line 4", h3))
        a(
            Paragraph(
                _text1.replace('forms of the', 'forms of the<br/><br/>', 1),
                bts))
        a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5", h3))
        a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/>', 1),
                    bts))
        a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5", h3))
        a(
            Paragraph(
                _text1.replace('I suggested ', 'I suggested<br/><br/>', 1),
                bts))
        a(Paragraph("&lt;br/&gt; at the end of the paragraph!", h3))
        a(Paragraph("""text one<br/>text two<br/>""", bts))
        a(Paragraph("Border with &lt;br/&gt; at the end of the paragraph!",
                    h3))
        bt1 = ParagraphStyle('bodyText1', bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""", bt1))
        a(Paragraph("Border no &lt;br/&gt; at the end of the paragraph!", h3))
        bt1 = ParagraphStyle('bodyText1', bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two""", bt1))
        a(Paragraph("Different border style!", h3))
        bt2 = ParagraphStyle('bodyText1', bt1)
        bt2.borderWidth = 1.5
        bt2.borderColor = colors.toColor('blue')
        bt2.backColor = colors.gray
        bt2.borderRadius = 3
        bt2.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""", bt2))
    for i in 0, 1, 2:
        P = Paragraph(
            """This is a paragraph with <font color='blue'><a href='#top'>with an incredibly
long and boring link in side of it that
contains lots and lots of stupidly boring and worthless information.
So that we can split the link and see if we get problems like Dinu's.
I hope we don't, but you never do Know.</a></font>""", bt)
        a(P)

    doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf'))
    doc.multiBuild(story)
コード例 #24
0
    def test2(self):
        chapters = 20  #so we know we use only one page
        from reportlab.lib.colors import pink

        #TOC and this HParagraph class just handle the collection
        TOC = []
        fontSize = 14
        leading = fontSize * 1.2
        descent = 0.2 * fontSize
        x = 2.5 * cm  #these come from the frame size
        y = (25 + 2.5) * cm - leading
        x1 = (15 + 2.5) * cm

        class HParagraph(Paragraph):
            def __init__(self, key, text, *args, **kwds):
                self._label = text
                self._key = key
                Paragraph.__init__(self, text, *args, **kwds)

            def draw(self):
                Paragraph.draw(self)
                TOC.append((self._label, self.canv.getPageNumber(), self._key))
                self.canv.bookmarkHorizontal('TOC_%s' % self._key, 0, +20)

        class UseForm(Flowable):
            _ZEROSIZE = 1

            def __init__(self, formName):
                self._formName = formName
                self.width = self.height = 0

            def draw(self):
                self.canv.doForm(self._formName)
                for i in range(chapters):
                    yb = y - i * leading  #baseline
                    self.canv.linkRect('',
                                       'TOC_%s' % i,
                                       (x, yb - descent, x1, yb + fontSize),
                                       thickness=0.5,
                                       color=pink,
                                       relative=0)

            def drawOn(self, canvas, x, y, _sW=0):
                Flowable.drawOn(self, canvas, 0, 0, canvas._pagesize[0])

        class MakeForm(UseForm):
            def draw(self):
                canv = self.canv
                canv.saveState()
                canv.beginForm(self._formName)
                canv.setFont("Helvetica", fontSize)
                for i, (text, pageNumber, key) in enumerate(TOC):
                    yb = y - i * leading  #baseline
                    canv.drawString(x, yb, text)
                    canv.drawRightString(x1, y - i * leading, str(pageNumber))
                canv.endForm()
                canv.restoreState()

        headerStyle = makeHeaderStyle(0)
        S = [Spacer(0, 180), UseForm('TOC')]
        RT = 'STARTUP COMPUTERS BLAH BUZZWORD STARTREK PRINTING PYTHON CHOMSKY'.split(
        )
        for i in range(chapters):
            S.append(PageBreak())
            S.append(HParagraph(i, 'This is chapter %d' % (i + 1),
                                headerStyle))
            txt = xmlEscape(randomtext.randomText(RT[i * 13 % len(RT)], 15))
            para = Paragraph(txt, makeBodyStyle())
            S.append(para)

        S.append(MakeForm('TOC'))

        doc = MyDocTemplate(outputfile('test_platypus_toc_simple.pdf'))
        doc.build(S)
コード例 #25
0
    def test1(self):
        """This shows a table which would take more than one page,
        and need multiple passes to render.  But we preload it
        with the right headings to make it go faster.  We used
        a simple 100-chapter document with one level.
        """

        chapters = 30  #goes over one page

        headerStyle = makeHeaderStyle(0)
        d, e = tableofcontents.delta, tableofcontents.epsilon
        tocLevelStyle = makeTocHeaderStyle(0, d, e)
        bodyStyle = makeBodyStyle()

        # Build most of the story; we'll re-use it to
        # make documents with different numbers of passes.

        story = []
        styleSheet = getSampleStyleSheet()
        bt = styleSheet['BodyText']

        description = '<font color=red>%s</font>' % self.test1.__doc__
        story.append(XPreformatted(description, bt))

        for i in range(chapters):
            story.append(PageBreak())
            story.append(Paragraph('This is chapter %d' % (i + 1),
                                   headerStyle))
            #now put some lengthy body stuff in.
            for paras in range(random.randint(1, 3)):
                txt = xmlEscape(randomtext.randomText(randomtext.PYTHON, 5))
                para = Paragraph(txt, bodyStyle)
                story.append(para)

        #try 1: empty TOC, 3 passes

        toc = tableofcontents.TableOfContents()
        toc.levelStyles = [tocLevelStyle]  #only need one
        story1 = [toc] + story

        path = outputfile('test_platypus_toc_preload_1.pdf')
        doc = MyDocTemplate(path)
        passes = doc.multiBuild(story1)
        self.assertEquals(passes, 3)

        #try 2: now preload the TOC with the entries

        toc = tableofcontents.TableOfContents()
        toc.levelStyles = [tocLevelStyle]  #only need one
        tocEntries = []
        for i in range(chapters):
            #add tuple of (level, text, pageNum, key)
            #with an initial guess of pageNum=0
            tocEntries.append((0, 'This is chapter %d' % (i + 1), 0, None))
        toc.addEntries(tocEntries)

        story2 = [toc] + story

        path = outputfile('test_platypus_toc_preload_2.pdf')
        doc = MyDocTemplate(path)
        passes = doc.multiBuild(story2)
        self.assertEquals(passes, 2)

        #try 3: preload again but try to be really smart and work out
        #in advance what page everything starts on.  We cannot
        #use a random story for this.

        toc3 = tableofcontents.TableOfContents()
        toc3.levelStyles = [tocLevelStyle]  #only need one
        tocEntries = []
        for i in range(chapters):
            #add tuple of (level, text, pageNum, key)
            #with an initial guess of pageNum= 3
            title = (
                'This is chapter %d' % (i + 1)
            ) if i != 9 else '<a href="http://www.reportlab.com">onelink</a>'
            tocEntries.append((0, title, 2 + i, None))
        toc3.addEntries(tocEntries)

        story3 = [toc3]
        for i in range(chapters):
            story3.append(PageBreak())
            title = (
                'This is chapter %d' % (i + 1)
            ) if i != 9 else '<a href="http://www.reportlab.com">onelink</a>'
            story3.append(Paragraph(title, headerStyle))
            txt = """
                The paragraphs in this are not at all random, because
                we need to be absolutely, totally certain they will fit 
                on one page.  Each chapter will be one page long.
            """
            para = Paragraph(txt, bodyStyle)
            story3.append(para)

        path = outputfile('test_platypus_toc_preload_3.pdf')
        doc = MyDocTemplate(path)
        passes = doc.multiBuild(story3)
コード例 #26
0
    def test0(self):
        """Test...

        The story should contain...

        Features to be visually confirmed by a human being are:

            1. ...
            2. ...
            3. ...
        """

        story = []
        SA = story.append

        #need a style
        styNormal = ParagraphStyle('normal')
        styGreen = ParagraphStyle('green',parent=styNormal,textColor=green)

        styDots = ParagraphStyle('styDots',parent=styNormal,endDots='.')
        styDots1 = ParagraphStyle('styDots1',parent=styNormal,endDots=ABag(text=' -',dy=2,textColor='red'))
        styDotsR = ParagraphStyle('styDotsR',parent=styNormal,alignment=TA_RIGHT,endDots=' +')
        styDotsC = ParagraphStyle('styDotsC',parent=styNormal,alignment=TA_CENTER,endDots=' *')
        styDotsJ = ParagraphStyle('styDotsJ',parent=styNormal,alignment=TA_JUSTIFY,endDots=' =')

        istyDots = ParagraphStyle('istyDots',parent=styNormal,firstLineIndent=12,leftIndent=6,endDots='.')
        istyDots1 = ParagraphStyle('istyDots1',parent=styNormal,firstLineIndent=12,leftIndent=6,endDots=ABag(text=' -',dy=2,textColor='red'))
        istyDotsR = ParagraphStyle('istyDotsR',parent=styNormal,firstLineIndent=12,leftIndent=6,alignment=TA_RIGHT,endDots=' +')
        istyDotsC = ParagraphStyle('istyDotsC',parent=styNormal,firstLineIndent=12,leftIndent=6,alignment=TA_CENTER,endDots=' *')
        istyDotsJ = ParagraphStyle('istyDotsJ',parent=styNormal,firstLineIndent=12,leftIndent=6,alignment=TA_JUSTIFY,endDots=' =')

        styNormalCJK = ParagraphStyle('normal',wordWrap='CJK')
        styDotsCJK = ParagraphStyle('styDots',parent=styNormalCJK,endDots='.')
        styDots1CJK = ParagraphStyle('styDots1',parent=styNormalCJK,endDots=ABag(text=' -',dy=2,textColor='red'))
        styDotsRCJK = ParagraphStyle('styDotsR',parent=styNormalCJK,alignment=TA_RIGHT,endDots=' +')
        styDotsCCJK = ParagraphStyle('styDotsC',parent=styNormalCJK,alignment=TA_CENTER,endDots=' *')
        styDotsJCJK = ParagraphStyle('styDotsJ',parent=styNormalCJK,alignment=TA_JUSTIFY,endDots=' =')

        istyDotsCJK = ParagraphStyle('istyDots',parent=styNormalCJK,firstLineIndent=12,leftIndent=6,endDots='.')
        istyDots1CJK = ParagraphStyle('istyDots1',parent=styNormalCJK,firstLineIndent=12,leftIndent=6,endDots=ABag(text=' -',dy=2,textColor='red'))
        istyDotsRCJK = ParagraphStyle('istyDotsR',parent=styNormalCJK,firstLineIndent=12,leftIndent=6,alignment=TA_RIGHT,endDots=' +')
        istyDotsCCJK = ParagraphStyle('istyDotsC',parent=styNormalCJK,firstLineIndent=12,leftIndent=6,alignment=TA_CENTER,endDots=' *')
        istyDotsJCJK = ParagraphStyle('istyDotsJ',parent=styNormalCJK,firstLineIndent=12,leftIndent=6,alignment=TA_JUSTIFY,endDots=' =')
        

        # some to test
        stySpaced = ParagraphStyle('spaced',
                                   parent=styNormal,
                                   spaceBefore=12,
                                   spaceAfter=12)


        SA(Paragraph("This is a normal paragraph. "+ randomText(), styNormal))
        SA(Paragraph("There follows a paragraph with only \"&lt;br/&gt;\"", styNormal))
        SA(Paragraph("<br/>", styNormal))
        SA(Paragraph("This has 12 points space before and after, set in the style. " + randomText(), stySpaced))
        SA(Paragraph("This is normal. " + randomText(), styNormal))
        SA(Paragraph("""<para spacebefore="12" spaceafter="12">
            This has 12 points space before and after, set inline with
            XML tag.  It works too.""" + randomText() + "</para>",
                      styNormal))

        SA(Paragraph("This is normal. " + randomText(), styNormal))

        styBackground = ParagraphStyle('MyTitle',
                                       fontName='Helvetica-Bold',
                                       fontSize=24,
                                       leading=28,
                                       textColor=white,
                                       backColor=navy)
        SA(Paragraph("This is a title with a background. ", styBackground))
        SA(Paragraph("""<para backcolor="pink">This got a background from the para tag</para>""", styNormal))
        SA(Paragraph("""<para>\n\tThis has newlines and tabs on the front but inside the para tag</para>""", styNormal))
        SA(Paragraph("""<para>  This has spaces on the front but inside the para tag</para>""", styNormal))
        SA(Paragraph("""\n\tThis has newlines and tabs on the front but no para tag""", styNormal))
        SA(Paragraph("""  This has spaces on the front but no para tag""", styNormal))
        SA(Paragraph("""This has <font color=blue>blue text</font> here.""", styNormal))
        SA(Paragraph("""This has <i>italic text</i> here.""", styNormal))
        SA(Paragraph("""This has <b>bold text</b> here.""", styNormal))
        SA(Paragraph("""This has <u>underlined text</u> here.""", styNormal))
        SA(Paragraph("""This has <font color=blue><u>blue and <font color=red>red</font> underlined text</u></font> here.""", styNormal))
        SA(Paragraph("""<u>green underlining</u>""", styGreen))
        SA(Paragraph("""<u>green <font size="+4"><i>underlining</i></font></u>""", styGreen))
        SA(Paragraph("""This has m<super>2</super> a superscript.""", styNormal))
        SA(Paragraph("""This has m<sub>2</sub> a subscript. Like H<sub>2</sub>O!""", styNormal))
        SA(Paragraph("""This has a font change to <font name=Helvetica>Helvetica</font>.""", styNormal))
        #This one fails:
        #SA(Paragraph("""This has a font change to <font name=Helvetica-Oblique>Helvetica-Oblique</font>.""", styNormal))
        SA(Paragraph("""This has a font change to <font name=Helvetica><i>Helvetica in italics</i></font>.""", styNormal))

        SA(Paragraph('''This one uses upper case tags and has set caseSensitive=0: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''', styNormal, caseSensitive=0))
        SA(Paragraph('''The same as before, but has set not set caseSensitive, thus the tags are ignored: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''', styNormal))
        SA(Paragraph('''This one uses fonts with size "14pt" and also uses the em and strong tags: Here comes <font face="Helvetica" size="14pt">Helvetica 14</font> with <Strong>strong</Strong> <em>emphasis</em>.''', styNormal, caseSensitive=0))
        SA(Paragraph('''This uses a font size of 3cm: Here comes <font face="Courier" size="3cm">Courier 3cm</font> and normal again.''', styNormal, caseSensitive=0))
        SA(Paragraph('''This is just a very long silly text to see if the <FONT face="Courier">caseSensitive</FONT> flag also works if the paragraph is <EM>very</EM> long. '''*20, styNormal, caseSensitive=0))

        SA(Indenter("1cm"))
        SA(Paragraph("<para><bullet bulletIndent='-1cm' bulletOffsetY='2'><seq id='s0'/>)</bullet>Indented list bulletOffsetY=2. %s</para>" % randomText(), styNormal))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(XPreformatted("<para leftIndent='0.5cm' backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(XPreformatted("<para leftIndent='0.5cm' backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(Indenter("-1cm"))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Indenter("-1cm"))
        SA(Paragraph("<para>Indented list using seqChain/Format<seqChain order='s0 s1 s2 s3 s4'/><seqReset id='s0'/><seqFormat id='s0' value='1'/><seqFormat id='s1' value='a'/><seqFormat id='s2' value='i'/><seqFormat id='s3' value='A'/><seqFormat id='s4' value='I'/></para>", stySpaced))
        SA(Indenter("1cm"))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(XPreformatted("<para backcolor=pink boffsety='-3'><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list bulletOffsetY=-3.</para>", styNormal))
        SA(XPreformatted("<para backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(Indenter("-1cm"))
        SA(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(XPreformatted("<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(Indenter("1cm"))
        SA(XPreformatted("<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line1</para>", styNormal))
        SA(XPreformatted("<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line2</para>", styNormal))
        SA(Indenter("-1cm"))
        SA(XPreformatted("<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        SA(Indenter("-1cm"))
        SA(Indenter("-1cm"))
        
        for i in range(2):
            SA(PageBreak())
            SA(Paragraph('''%s dotted paragraphs''' % (i and 'CJK' or 'Normal'), styNormal))
            SA(Paragraph('''Simple paragraph with dots''', i and styDotsCJK or styDots))
            SA(Paragraph('''Simple indented paragraph with dots''', i and istyDotsCJK or istyDots))
            SA(Paragraph('''Simple centred paragraph with stars''', i and styDotsCCJK or styDotsC))
            SA(Paragraph('''Simple centred indented paragraph with stars''', i and istyDotsCCJK or istyDotsC))
            SA(Paragraph('''Simple right justified paragraph with pluses, but no pluses''', i and styDotsRCJK or styDotsR))
            SA(Paragraph('''Simple right justified indented paragraph with pluses, but no pluses''', i and istyDotsRCJK or istyDotsR))
            SA(Paragraph('''Simple justified paragraph with equals''', i and styDotsJCJK or styDotsJ))
            SA(Paragraph('''Simple justified indented paragraph with equals''', i and istyDotsJCJK or istyDotsJ))
            SA(Paragraph('''A longer simple paragraph with dots''', i and styDotsCJK or styDots))
            SA(Paragraph('''A longer simple indented paragraph with dots''', i and istyDotsCJK or istyDots))
            SA(Paragraph('A very much' +50*' longer'+' simple paragraph with dots', i and styDotsCJK or styDots))
            SA(Paragraph('A very much' +50*' longer'+' simple indented paragraph with dots', i and istyDotsCJK or istyDots))
            SA(Paragraph('A very much' +50*' longer'+' centred simple paragraph with stars', i and styDotsCCJK or styDotsC))
            SA(Paragraph('A very much' +50*' longer'+' centred simple indented paragraph with stars', i and istyDotsCCJK or istyDotsC))
            SA(Paragraph('A very much' +50*' longer'+' right justified simple paragraph with pluses, but no pluses', i and styDotsRCJK or styDotsR))
            SA(Paragraph('A very much' +50*' longer'+' right justified simple indented paragraph with pluses, but no pluses', i and istyDotsRCJK or istyDotsR))
            SA(Paragraph('A very much' +50*' longer'+' justified simple paragraph with equals', i and styDotsJCJK or styDotsJ))
            SA(Paragraph('A very much' +50*' longer'+' justified simple indented paragraph with equals', i and istyDotsJCJK or istyDotsJ))
            SA(Paragraph('''Simple paragraph with dashes that have a dy and a textColor.''', i and styDots1CJK or styDots1))
            SA(Paragraph('''Simple indented paragraph with dashes that have a dy and a textColor.''', i and istyDots1CJK or istyDots1))
            SA(Paragraph('''Complex <font color="green">paragraph</font> with dots''', i and styDotsCJK or styDots))
            SA(Paragraph('''Complex <font color="green">indented paragraph</font> with dots''', i and istyDotsCJK or istyDots))
            SA(Paragraph('''Complex centred <font color="green">paragraph</font> with stars''', i and styDotsCCJK or styDotsC))
            SA(Paragraph('''Complex centred <font color="green">indented paragraph</font> with stars''', i and istyDotsCCJK or istyDotsC))
            SA(Paragraph('''Complex right justfied <font color="green">paragraph</font> with pluses, but no pluses''', i and styDotsRCJK or styDotsR))
            SA(Paragraph('''Complex right justfied <font color="green">indented paragraph</font> with pluses, but no pluses''', i and istyDotsRCJK or istyDotsR))
            SA(Paragraph('''Complex justfied <font color="green">paragraph</font> with equals''', i and styDotsJCJK or styDotsJ))
            SA(Paragraph('''Complex justfied <font color="green">indented paragraph</font> with equals''', i and istyDotsJCJK or istyDotsJ))
            SA(Paragraph('''A longer complex <font color="green">paragraph</font> with dots''', i and styDotsCJK or styDots))
            SA(Paragraph('''A longer complex <font color="green">indented paragraph</font> with dots''', i and istyDotsCJK or istyDots))
            SA(Paragraph('A very much' +50*' longer'+' complex <font color="green">paragraph</font> with dots', i and styDotsCJK or styDots))
            SA(Paragraph('A very much' +50*' longer'+' complex <font color="green">indented paragraph</font> with dots', i and istyDotsCJK or istyDots))
            SA(Paragraph('''Complex <font color="green">paragraph</font> with dashes that have a dy and a textColor.''', i and styDots1CJK or styDots1))
            SA(Paragraph('''Complex <font color="green">indented paragraph</font> with dashes that have a dy and a textColor.''', i and istyDots1CJK or istyDots1))
            SA(Paragraph('A very much' +50*' longer'+' centred complex <font color="green">paragraph</font> with stars', i and styDotsCCJK or styDotsC))
            SA(Paragraph('A very much' +50*' longer'+' centred complex <font color="green">indented paragraph</font> with stars', i and istyDotsCCJK or istyDotsC))
            SA(Paragraph('A very much' +50*' longer'+' right justified <font color="green">complex</font> paragraph with pluses, but no pluses', i and styDotsRCJK or styDotsR))
            SA(Paragraph('A very much' +50*' longer'+' right justified <font color="green">complex</font> indented paragraph with pluses, but no pluses', i and istyDotsRCJK or istyDotsR))
            SA(Paragraph('A very much' +50*' longer'+' justified complex <font color="green">paragraph</font> with equals', i and styDotsJCJK or styDotsJ))
            SA(Paragraph('A very much' +50*' longer'+' justified complex <font color="green">indented paragraph</font> with equals', i and istyDotsJCJK or istyDotsJ))

        template = SimpleDocTemplate(outputfile('test_paragraphs.pdf'),
                                     showBoundary=1)
        template.build(story,
            onFirstPage=myFirstPage, onLaterPages=myLaterPages)
コード例 #27
0
 def RT(k, theme='PYTHON', sentences=1, cache={}):
     if k not in cache:
         cache[k] = randomText(theme=theme, sentences=sentences)
     return cache[k]
コード例 #28
0
ファイル: test_paragraphs.py プロジェクト: eaudeweb/naaya
    def test0(self):
        """Test...

        The story should contain...

        Features to be visually confirmed by a human being are:

            1. ...
            2. ...
            3. ...
        """

        story = []

        #need a style
        styNormal = ParagraphStyle('normal')

        # some to test
        stySpaced = ParagraphStyle('spaced',
                                   parent=styNormal,
                                   spaceBefore=12,
                                   spaceAfter=12)


        story.append(
            Paragraph("This is a normal paragraph. "
                      + randomText(), styNormal))
        story.append(
            Paragraph("This has 12 points space before and after, set in the style. "
                      + randomText(), stySpaced))
        story.append(
            Paragraph("This is normal. " +
                      randomText(), styNormal))

        story.append(
            Paragraph("""<para spacebefore="12" spaceafter="12">
            This has 12 points space before and after, set inline with
            XML tag.  It works too.""" + randomText() + "</para",
                      styNormal))

        story.append(
            Paragraph("This is normal. " +
                      randomText(), styNormal))

        styBackground = ParagraphStyle('MyTitle',
                                       fontName='Helvetica-Bold',
                                       fontSize=24,
                                       leading=28,
                                       textColor=white,
                                       backColor=navy)
        story.append(
            Paragraph("This is a title with a background. ", styBackground))

        story.append(
            Paragraph("""<para backcolor="pink">This got a background from the para tag</para>""", styNormal))


        story.append(
            Paragraph("""<para>\n\tThis has newlines and tabs on the front but inside the para tag</para>""", styNormal))
        story.append(
            Paragraph("""<para>  This has spaces on the front but inside the para tag</para>""", styNormal))

        story.append(
            Paragraph("""\n\tThis has newlines and tabs on the front but no para tag""", styNormal))
        story.append(
            Paragraph("""  This has spaces on the front but no para tag""", styNormal))

        story.append(Paragraph("""This has <font color=blue>blue text</font> here.""", styNormal))
        story.append(Paragraph("""This has <i>italic text</i> here.""", styNormal))
        story.append(Paragraph("""This has <b>bold text</b> here.""", styNormal))
        story.append(Paragraph("""This has <u>underlined text</u> here.""", styNormal))
        story.append(Paragraph("""This has m<super>2</super> a superscript.""", styNormal))
        story.append(Paragraph("""This has m<sub>2</sub> a subscript. Like H<sub>2</sub>O!""", styNormal))
        story.append(Paragraph("""This has a font change to <font name=Helvetica>Helvetica</font>.""", styNormal))
        #This one fails:
        #story.append(Paragraph("""This has a font change to <font name=Helvetica-Oblique>Helvetica-Oblique</font>.""", styNormal))
        story.append(Paragraph("""This has a font change to <font name=Helvetica><i>Helvetica in italics</i></font>.""", styNormal))

        story.append(Paragraph('''This one uses upper case tags and has set caseSensitive=0: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''', styNormal, caseSensitive=0))
        story.append(Paragraph('''The same as before, but has set not set caseSensitive, thus the tags are ignored: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''', styNormal))
        story.append(Paragraph('''This one uses fonts with size "14pt" and also uses the em and strong tags: Here comes <font face="Helvetica" size="14pt">Helvetica 14</font> with <Strong>strong</Strong> <em>emphasis</em>.''', styNormal, caseSensitive=0))
        story.append(Paragraph('''This uses a font size of 3cm: Here comes <font face="Courier" size="3cm">Courier 3cm</font> and normal again.''', styNormal, caseSensitive=0))
        story.append(Paragraph('''This is just a very long silly text to see if the <FONT face="Courier">caseSensitive</FONT> flag also works if the paragraph is <EM>very</EM> long. '''*20, styNormal, caseSensitive=0))
        story.append(Indenter("1cm"))
        story.append(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        story.append(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        story.append(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        story.append(Indenter("1cm"))
        story.append(XPreformatted("<para leftIndent='0.5cm' backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        story.append(XPreformatted("<para leftIndent='0.5cm' backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        story.append(Indenter("-1cm"))
        story.append(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        story.append(Indenter("-1cm"))
        story.append(Paragraph("<para>Indented list using seqChain/Format<seqChain order='s0 s1 s2 s3 s4'/><seqReset id='s0'/><seqFormat id='s0' value='1'/><seqFormat id='s1' value='a'/><seqFormat id='s2' value='i'/><seqFormat id='s3' value='A'/><seqFormat id='s4' value='I'/></para>", stySpaced))
        story.append(Indenter("1cm"))
        story.append(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        story.append(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        story.append(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        story.append(Indenter("1cm"))
        story.append(XPreformatted("<para backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        story.append(XPreformatted("<para backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        story.append(Indenter("-1cm"))
        story.append(Paragraph("<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal))
        story.append(Indenter("1cm"))
        story.append(XPreformatted("<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        story.append(Indenter("1cm"))
        story.append(XPreformatted("<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line1</para>", styNormal))
        story.append(XPreformatted("<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line2</para>", styNormal))
        story.append(Indenter("-1cm"))
        story.append(XPreformatted("<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal))
        story.append(Indenter("-1cm"))
        story.append(Indenter("-1cm"))

        template = SimpleDocTemplate(outputfile('test_paragraphs.pdf'),
                                     showBoundary=1)
        template.build(story,
            onFirstPage=myFirstPage, onLaterPages=myLaterPages)
コード例 #29
0
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []
    a = story.append

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet['Heading2']
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet['Heading3']
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet['BodyText']
    a(
        Paragraph(
            """
        Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)""" %
            (time.ctime(time.time()), len(story)), bt))

    for i in xrange(10):
        a(Paragraph('Heading 1 always starts a new page (%d)' % len(story),
                    h1))
        for j in xrange(3):
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            a(
                Paragraph(
                    'Heading 2 always starts a new frame (%d)' % len(story),
                    h2))
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            for j in xrange(3):
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=2) +
                        ' (%d)' % len(story), bt))
                a(
                    Paragraph(
                        'I should never be at the bottom of a frame (%d)' %
                        len(story), h3))
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=1) +
                        ' (%d)' % len(story), bt))

    a(Paragraph('Now we do &lt;br/&gt; tests', h1))
    a(Paragraph('First off no br tags', h3))
    a(Paragraph(_text1, bt))
    a(Paragraph("&lt;br/&gt; after 'the' in line 4", h3))
    a(Paragraph(_text1.replace('forms of the', 'forms of the<br/>', 1), bt))
    a(Paragraph("2*&lt;br/&gt; after 'the' in line 4", h3))
    a(
        Paragraph(_text1.replace('forms of the', 'forms of the<br/><br/>', 1),
                  bt))
    a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5", h3))
    a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/>', 1), bt))
    a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5", h3))
    a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/><br/>', 1),
                bt))
    a(Paragraph("&lt;br/&gt; at the end of the paragraph!", h3))
    a(Paragraph("""text one<br/>text two<br/>""", bt))
    a(Paragraph("Border with &lt;nr/&gt; at the end of the paragraph!", h3))
    bt1 = ParagraphStyle('bodyText1', bt)
    bt1.borderWidth = 0.5
    bt1.borderColor = colors.toColor('red')
    bt1.backColor = colors.pink
    bt1.borderRadius = 2
    bt1.borderPadding = 3
    a(Paragraph("""text one<br/>text two<br/>""", bt1))
    a(Paragraph("Border no &lt;nr/&gt; at the end of the paragraph!", h3))
    bt1 = ParagraphStyle('bodyText1', bt)
    bt1.borderWidth = 0.5
    bt1.borderColor = colors.toColor('red')
    bt1.backColor = colors.pink
    bt1.borderRadius = 2
    bt1.borderPadding = 3
    a(Paragraph("""text one<br/>text two""", bt1))
    a(Paragraph("Different border style!", h3))
    bt2 = ParagraphStyle('bodyText1', bt1)
    bt2.borderWidth = 1.5
    bt2.borderColor = colors.toColor('blue')
    bt2.backColor = colors.gray
    bt2.borderRadius = 3
    bt2.borderPadding = 3
    a(Paragraph("""text one<br/>text two<br/>""", bt2))

    doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf'))
    doc.multiBuild(story)
コード例 #30
0
 def RT(k,theme='PYTHON',sentences=1,cache={}):
     if k not in cache:
         cache[k] = randomText(theme=theme,sentences=sentences)
     return cache[k]
コード例 #31
0
    def test0(self):
        """Test...

        The story should contain...

        Features to be visually confirmed by a human being are:

            1. ...
            2. ...
            3. ...
        """

        story = []

        #need a style
        styNormal = ParagraphStyle('normal')
        styGreen = ParagraphStyle('green', parent=styNormal, textColor=green)

        # some to test
        stySpaced = ParagraphStyle('spaced',
                                   parent=styNormal,
                                   spaceBefore=12,
                                   spaceAfter=12)

        story.append(
            Paragraph("This is a normal paragraph. " + randomText(),
                      styNormal))
        story.append(
            Paragraph(
                "This has 12 points space before and after, set in the style. "
                + randomText(), stySpaced))
        story.append(Paragraph("This is normal. " + randomText(), styNormal))

        story.append(
            Paragraph(
                """<para spacebefore="12" spaceafter="12">
            This has 12 points space before and after, set inline with
            XML tag.  It works too.""" + randomText() + "</para", styNormal))

        story.append(Paragraph("This is normal. " + randomText(), styNormal))

        styBackground = ParagraphStyle('MyTitle',
                                       fontName='Helvetica-Bold',
                                       fontSize=24,
                                       leading=28,
                                       textColor=white,
                                       backColor=navy)
        story.append(
            Paragraph("This is a title with a background. ", styBackground))

        story.append(
            Paragraph(
                """<para backcolor="pink">This got a background from the para tag</para>""",
                styNormal))

        story.append(
            Paragraph(
                """<para>\n\tThis has newlines and tabs on the front but inside the para tag</para>""",
                styNormal))
        story.append(
            Paragraph(
                """<para>  This has spaces on the front but inside the para tag</para>""",
                styNormal))

        story.append(
            Paragraph(
                """\n\tThis has newlines and tabs on the front but no para tag""",
                styNormal))
        story.append(
            Paragraph("""  This has spaces on the front but no para tag""",
                      styNormal))

        story.append(
            Paragraph("""This has <font color=blue>blue text</font> here.""",
                      styNormal))
        story.append(
            Paragraph("""This has <i>italic text</i> here.""", styNormal))
        story.append(
            Paragraph("""This has <b>bold text</b> here.""", styNormal))
        story.append(
            Paragraph("""This has <u>underlined text</u> here.""", styNormal))
        story.append(
            Paragraph(
                """This has <font color=blue><u>blue and <font color=red>red</font> underlined text</u></font> here.""",
                styNormal))
        story.append(Paragraph("""<u>green underlining</u>""", styGreen))
        story.append(
            Paragraph(
                """<u>green <font size=+4><i>underlining</font></i></u>""",
                styGreen))
        story.append(
            Paragraph("""This has m<super>2</super> a superscript.""",
                      styNormal))
        story.append(
            Paragraph(
                """This has m<sub>2</sub> a subscript. Like H<sub>2</sub>O!""",
                styNormal))
        story.append(
            Paragraph(
                """This has a font change to <font name=Helvetica>Helvetica</font>.""",
                styNormal))
        #This one fails:
        #story.append(Paragraph("""This has a font change to <font name=Helvetica-Oblique>Helvetica-Oblique</font>.""", styNormal))
        story.append(
            Paragraph(
                """This has a font change to <font name=Helvetica><i>Helvetica in italics</i></font>.""",
                styNormal))

        story.append(
            Paragraph(
                '''This one uses upper case tags and has set caseSensitive=0: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''',
                styNormal,
                caseSensitive=0))
        story.append(
            Paragraph(
                '''The same as before, but has set not set caseSensitive, thus the tags are ignored: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''',
                styNormal))
        story.append(
            Paragraph(
                '''This one uses fonts with size "14pt" and also uses the em and strong tags: Here comes <font face="Helvetica" size="14pt">Helvetica 14</font> with <Strong>strong</Strong> <em>emphasis</em>.''',
                styNormal,
                caseSensitive=0))
        story.append(
            Paragraph(
                '''This uses a font size of 3cm: Here comes <font face="Courier" size="3cm">Courier 3cm</font> and normal again.''',
                styNormal,
                caseSensitive=0))
        story.append(
            Paragraph(
                '''This is just a very long silly text to see if the <FONT face="Courier">caseSensitive</FONT> flag also works if the paragraph is <EM>very</EM> long. '''
                * 20,
                styNormal,
                caseSensitive=0))
        story.append(Indenter("1cm"))
        story.append(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        story.append(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        story.append(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        story.append(Indenter("1cm"))
        story.append(
            XPreformatted(
                "<para leftIndent='0.5cm' backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        story.append(
            XPreformatted(
                "<para leftIndent='0.5cm' backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        story.append(Indenter("-1cm"))
        story.append(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        story.append(Indenter("-1cm"))
        story.append(
            Paragraph(
                "<para>Indented list using seqChain/Format<seqChain order='s0 s1 s2 s3 s4'/><seqReset id='s0'/><seqFormat id='s0' value='1'/><seqFormat id='s1' value='a'/><seqFormat id='s2' value='i'/><seqFormat id='s3' value='A'/><seqFormat id='s4' value='I'/></para>",
                stySpaced))
        story.append(Indenter("1cm"))
        story.append(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        story.append(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        story.append(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        story.append(Indenter("1cm"))
        story.append(
            XPreformatted(
                "<para backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        story.append(
            XPreformatted(
                "<para backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        story.append(Indenter("-1cm"))
        story.append(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        story.append(Indenter("1cm"))
        story.append(
            XPreformatted(
                "<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        story.append(Indenter("1cm"))
        story.append(
            XPreformatted(
                "<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line1</para>",
                styNormal))
        story.append(
            XPreformatted(
                "<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line2</para>",
                styNormal))
        story.append(Indenter("-1cm"))
        story.append(
            XPreformatted(
                "<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        story.append(Indenter("-1cm"))
        story.append(Indenter("-1cm"))

        template = SimpleDocTemplate(outputfile('test_paragraphs.pdf'),
                                     showBoundary=1)
        template.build(story,
                       onFirstPage=myFirstPage,
                       onLaterPages=myLaterPages)
コード例 #32
0
chapterNum = 1  # 记录章节
for i in range(10):  # 共10章
    story.append(Paragraph('Chapter {}: Chapters always starts a new page'.format(chapterNum), h1))
    # 每一个章节的标题
    chapterNum += chapterNum
    story.append(DocAssign('chapterNum', chapterNum))
    for j in range(3):
        story.append(Paragraph('Heading1 paragraphs should always'
                               'have a page break before.  Heading 2 on the other hand'
                               'should always have a FRAME break before ({})'.format(len(story)), bt))
        # 普通文本
        story.append(Paragraph('Heading 2 should always be kept with the next thing ({})'.format(len(story)), h2))
        # 二级标题
        for p in range(3):
            story.append(Paragraph(randomText(theme=PYTHON, sentences=2) + ' ({})'.format(len(story)), bt))
            # 两句,内容随机产生,普通文本
            story.append(Paragraph('I should never be at the bottom of a frame ({})'.format(len(story)), h2))
            # 二级标题
            story.append(Paragraph(randomText(theme=PYTHON, sentences=1) + ' ({})'.format(len(story)), bt))
            # 一句,内容随机产生,普通文本
    story.extend([
        DocAssign('currentFrame', 'doc.frame.id'),
        DocAssign('currentPageTemplate', 'doc.pageTemplate.id'),
        DocAssign('aW', 'availableWidth'),
        DocAssign('aH', 'availableHeight'),
        DocAssign('aWH', 'availableWidth,availableHeight'),
        DocAssign('i', 3),
        DocIf('i>3', Paragraph('The value of i is larger than 3', bt),
              Paragraph('The value of i is not larger than 3', bt)),
        DocIf('i==3', Paragraph('The value of i is equal to 3', bt),