Пример #1
0
    def _print_coverage(self, amount, coverage):
        from reportlab.lib import colors
        from reportlab.platypus import Table, TableStyle, XPreformatted, Spacer
        self.lst.append(Spacer(0, 20))
        self.lst.append(
            XPreformatted(
                "<b><i><font size=20>Coverage information</font></i></b>\n\nCovered %3.2f%% of the code."
                % coverage.total_coverage_percentage(), self._normal_style()))
        if (amount != "slim"):
            self.lst.append(Spacer(0, 20))
            data = [("Lines", "Covered lines", "Percentage", "Module", "Path")]
            modname = coverage.modname
            for filename, stats in coverage.getstatistics().items():
                data.append(
                    (str(stats["lines"]), str(stats["covered"]),
                     str(stats["percent"]) + "%", modname(filename), filename))

            data.append(
                (str(coverage.total_lines()),
                 str(coverage.total_lines_covered()),
                 str(coverage.total_coverage_percentage()) + '%', "TOTAL", ""))
            table = Table(data)
            table.setStyle(
                TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25,
                             colors.black),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                            ('VALIGN', (0, 0), (-1, -1), "TOP"),
                            ('BACKGROUND', (0, 0), (-1, 0), colors.grey)]))
            self.lst.append(table)
    def split(self, aW, aH):
        """
        Figure out a nice range of splits

        Assume we would prefer 5 lines (at least) on a splitted flowable
        before a break, and 4 on the last flowable after a break.
        So, the minimum wrap height for a fragment will be 5 * leading
        """
        rW, rH = self.wrap(aW, aH)
        if rH > aH:

            minH1 = getattr(self.style, 'allowOrphans', 5) * self.style.leading
            minH2 = getattr(self.style, 'allowWidows', 4) * self.style.leading

            # If there's no way to fid a decent fragment,
            # refuse to split
            if aH < minH1:
                return []

            # Now, don't split too close to the end either
            pw, ph = self.wrap(aW, aH)
            if ph - aH < minH2:
                aH = ph - minH2

        return XPreformatted.split(self, aW, aH)
Пример #3
0
def add_file(fname, paragraphs):
    extensions = {
        'py': 'python',
        'ml': 'ocaml',
        'mll': 'ocaml',
        'mly': 'ocaml',
        'c': 'c',
        'h': 'c++',
        'cpp': 'c++',
        'cc': 'c++',
        'll': 'llvm',
        'java': 'java',
    }

    paragraphs.append(Paragraph(fname, style=styles['title']))
    with open(fname) as source_file:
        language = 'python'
        if '.' in fname:
            ext = fname.split('.')[-1]
            if ext == 'md':
                add_markdown(fname, paragraphs)
                return
            if ext in extensions:
                language = extensions[ext]

        source = source_file.read()
        pretty = p2x(source, language=language)
        formatted = XPreformatted(pretty, style=styles['code'])
        paragraphs.append(formatted)
Пример #4
0
    def split(self, aW, aH):
        """
        Figure out a nice range of splits

        Assume we would prefer 5 lines (at least) on a splitted flowable
        before a break, and 4 on the last flowable after a break.
        So, the minimum wrap height for a fragment will be 5 * leading
        """
        rW, rH = self.wrap(aW, aH)
        if rH > aH:

            minH1 = getattr(self.style, 'allowOrphans', 5) * self.style.leading
            minH2 = getattr(self.style, 'allowWidows', 4) * self.style.leading

            # If there's no way to fid a decent fragment,
            # refuse to split
            if aH < minH1:
                return []

            # Now, don't split too close to the end either
            pw, ph = self.wrap(aW, aH)
            if ph - aH < minH2:
                aH = ph - minH2

        return XPreformatted.split(self, aW, aH)
Пример #5
0
    def _print_code(self, code, root=False):
        style = self._styles['code' if root else 'subcode']

        if isinstance(code, CodeListing) and not self.print_sources:
            self._story.append(
                RLParagraph(
                    'Source file: <a href="{url}/{fname}" color="blue">{fname}</a>'
                    .format(url=self.SOURCE_URL, fname=code.fname),
                    style=self._styles['default']))
            return

        out = cStringIO.StringIO()
        for part in code.parts:
            # TODO: support bold/italic text in preformatted
            text = str(part).replace('\t', '    ')

            for line in text.splitlines(True):
                tags = self.CODE_TAGS.get(type(part), ('', ''))
                self._print_code_line(line, out, style, tags)

        if isinstance(code, CodeListing):
            self._story.append(_ListingInfoFlowable(code.fname))

        self._begin_incut(code)
        self._story.append(XPreformatted(out.getvalue(), style))
        self._end_incut(code)
Пример #6
0
    def convert_code_cell(self, cell):
        code = pygments2xpre(cell.source).rstrip()
        code = add_in_prompt(code, cell.execution_count)
        self.pieces.append(XPreformatted(code, style=self.stylesheet['Code']))

        if cell.outputs:
            self.pieces.append(Spacer(1, 6))

        for output in cell.outputs:
            self.convert_output(output)
Пример #7
0
    def drawTextPages(self,
                      pages,
                      margin=1.0,
                      fontsize=10,
                      leading=10,
                      spacer=0.05):
        s = getSampleStyleSheet()['BodyText']
        s.fontName = self.font_mapping['Monospaced']
        s.alignment = TA_LEFT

        textHorizontalMargin = margin * cm
        textVerticalMargin = margin * cm
        textBoxWidth = self.options.paperwidth - 2 * textHorizontalMargin
        textBoxHeight = self.options.paperheight - 2 * textVerticalMargin
        minSpacerHeight = 0.05 * cm

        for page in pages:
            s.fontsize = fontsize
            s.leading = leading
            spacerHeight = spacer * cm
            text = re.split("\n", page)
            while True:
                paragraphs = []
                # this accounts for the spacers we insert between paragraphs
                h = (len(text) - 1) * spacerHeight
                for line in text:
                    p = XPreformatted(line, s)
                    h += p.wrap(textBoxWidth, textBoxHeight)[1]
                    paragraphs.append(p)

                if h <= textBoxHeight or s.fontSize <= 1 or s.leading <= 1:
                    break
                else:
                    s.fontSize -= 0.2
                    s.leading -= 0.2
                    spacerHeight = max(spacerHeight - 1, minSpacerHeight)

            h = self.options.paperheight - textVerticalMargin
            for p in paragraphs:
                h -= p.height
                p.drawOn(self.canvas, textHorizontalMargin, h)
                h -= spacerHeight
            self.canvas.showPage()
Пример #8
0
def markdown_to_platypus(path):
    "Convert a specific MarkDown file into ReportLab Platypus items."

    cover, qa = extract_markdown(path)
    title, paras = cover
    cover = [Paragraph(title, h1)] + [Paragraph(p, bt) for p in paras]
    items = [{
        "q": Paragraph(q, bt),
        "a": XPreformatted(pygments2xpre(a), code)
    } for q, a in qa]
    return cover, items
Пример #9
0
    def __init__(self, filename):
        BaseReporter.__init__(self)
        from reportlab.platypus import XPreformatted, Spacer
        self.filename = filename
        self.lst = []
        self.lst.append(
            XPreformatted(
                "<b><i><font size=20>Summary of test results</font></i></b>",
                self._normal_style()))
        self.lst.append(Spacer(0, 20))

        self.test_data = [("Name", "Result", "Info")]
def convertSourceFiles(filenames):
    "Helper function - makes minimal PDF document"

    from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, XPreformatted
    from reportlab.lib.styles import getSampleStyleSheet
    styT=getSampleStyleSheet()["Title"]
    styC=getSampleStyleSheet()["Code"]
    doc = SimpleDocTemplate("pygments2xpre.pdf")
    S = [].append
    for filename in filenames:
        S(Paragraph(filename,style=styT))
        src = open(filename, 'r').read()
        fmt = pygments2xpre(src)
        S(XPreformatted(fmt, style=styC))
    doc.build(S.__self__)
    print('saved pygments2xpre.pdf')
def xpreformatted_paragraph():
    doc = SimpleDocTemplate("xpreformatted_paragraph.pdf",
                            pagesize=letter
                            )
    styles = getSampleStyleSheet()

    flowables = []

    text = """<font color="blue">Hello, I'm a Paragraph</font>"""
    para = Paragraph(text, style=styles["Normal"])
    flowables.append(para)

    text = """Hello, I'm a <font color="red">XPreformatted Paragraph</font>"""
    para = XPreformatted(text, style=styles["Normal"])
    flowables.append(para)

    doc.build(flowables)
Пример #12
0
def content(job):
    """Create a list of flowables with all the content for the cutlist."""
    result = []
    result.append(hdr_table(job))
    result.append(FrameBreak())

    result.append(Paragraph('Overview:', heading_style))
    for line in job.summaryln:
        result.append(Paragraph(line, normal_style))
    result.append(Spacer(1, 10))
    for line in job.cabinfo:
        result.append(Paragraph(line, normal_style))
    result.append(Spacer(1, 10))
    for line in job.materialinfo:
        result.append(Paragraph(line, normal_style))
    result.append(Spacer(1, 24))
    result.append(isometric_view(job))
    result.append(FrameBreak())

    result.append(panels_table(job))
    result.append(Paragraph('Parts List:', heading_style))
    for line in job.partslist:
        result.append(XPreformatted(line, fixed_style))
    return result
Пример #13
0
 def __init__(self, *args, **kwargs):
     XPreformatted.__init__(self, *args, **kwargs)
Пример #14
0
    def writeData(self,
                  method=None,
                  params=None,
                  request=None,
                  attacktype=None,
                  idsEvasion=None,
                  roundtrip=None,
                  rawresponse=None,
                  code=None,
                  xmlpayload=None):

        file_str_req = StringIO()
        file_str_resp = StringIO()
        colwidths = (1 * inch, self.PAGE_WIDTH - (2 * inch))
        dataarr = []

        #################################################################
        # Request
        if attacktype:
            dataarr.append(('Type of Attack', attacktype))
        else:
            dataarr.append(('Type of Attack', 'Unknown Attack Type'))

        if method:
            dataarr.append(('Method', method))
        else:
            dataarr.append(('Method', 'Unknown Method'))

        if type(params) is str:
            dataarr.append(('Request Params', params))
        elif type(params) is dict:
            forprint = {}
            # loop on dict escaping HTML entities
            for k, v in params.iteritems():
                forprint[k] = v
            dataarr.append(('Request Params', forprint))
        else:
            dataarr.append(('Request Params', 'Unknown Params'))

        if idsEvasion:
            dataarr.append(('IDS Evasion', idsEvasion))
        else:
            dataarr.append(('IDS Evasion', 'Not Used'))
        #################################################################
        #################################################################
        # Response
        if code:
            dataarr.append(('Status Code', code))
        else:
            dataarr.append(('Status Code', 'Unknown Code'))

        if rawresponse:
            if rawresponse[1] == 1:
                for xx in rawresponse[0]:
                    try:
                        dataarr.append(
                            ('Response', Paragraph(str(xx), self.style)))
                    except ValueError:
                        pass
            elif type(rawresponse) is str:
                dataarr.append(
                    ('Response', Paragraph(str(rawresponse), self.style)))
            else:
                try:
                    dataarr.append(
                        ('Response', Paragraph(str(rawresponse[0]),
                                               self.style)))
                except ValueError:
                    pass
        else:
            dataarr.append(('Response', 'No response extracted'))

        if roundtrip:
            dataarr.append(('Round Trip', roundtrip))
        else:
            dataarr.append(('Round Trip', 'Unknown Roundtrip'))
        #################################################################

        #################################################################
        # Paylaods
        # Request
        c = cgi.escape(xmlpp.get_pprint(request).strip(), 1)
        c = self.convertToN(c)
        file_str_req.write(str(c))

        # Response
        if xmlpayload:
            c = cgi.escape(xmlpp.get_pprint(xmlpayload).strip(), 1)
            c = self.convertToN(c)
            file_str_resp.write(str(c))

        preqheader = Paragraph("Request:", self.style)
        preq = XPreformatted(str(file_str_req.getvalue()), self.style)
        prespheader = Paragraph("Response:", self.style)
        presp = XPreformatted(str(file_str_resp.getvalue()), self.style)

        # create a list (array) of all values to write
        # then cast to tuple of tuples
        # so array/list looks like: [('l', 'xx'), ('ll', 'xxx'), ('lll', 'xxxxx')]
        data = tuple(dataarr)
        t = Table(data, colwidths, rowHeights=None)
        t.setStyle(self.GRID_STYLE)

        self.Story.append(t)
        self.Story.append(Spacer(1, 0.2 * inch))
        self.Story.append(preqheader)
        self.Story.append(Spacer(1, 0.2 * inch))
        self.Story.append(preq)
        self.Story.append(Spacer(1, 0.2 * inch))
        self.Story.append(prespheader)
        self.Story.append(Spacer(1, 0.2 * inch))
        self.Story.append(presp)
        self.Story.append(Spacer(1, 0.2 * inch))
Пример #15
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=' =')

        # 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
 def add_plain_text(self, text):
     self.pieces.append(XPreformatted(text, style=self.stylesheet['Code']))
Пример #17
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)
Пример #18
0
 def block_code(self, code, lang=None):
     if lang:
         code = pygments2xpre(code, language=lang)
     return [XPreformatted(code, style=self.get_style('Code'))]
 def __init__(self, *args, **kwargs):
     XPreformatted.__init__(self, *args, **kwargs)
Пример #20
0
class PdfRenderer(Renderer):

    outputExt = 'pdf'

    def __init__(self):
        self._story = []

##      def beginStory(self):
##          self._story = Story(self._story)

##      def endStory(e):
##          self._story = self._story.parent
##          #story = storyStack.pop()
##          #assert story.env is e
##          #return story

##      def addElement(elem):
##          self._story.addElement(elem)

    def onBeginDocument(self, doc):
        self.document = doc
        self.rldoc = SimpleDocTemplate(self.getFilename())

        # overwrites the default UL
        doc.stylesheet.UL = BulletListStyle(bulletWidth=12)

    def onEndDocument(self, doc):
        for k, v in doc.docstyle.items():
            setattr(self.rldoc, k, v)
        self.rldoc.build(self._story,
                         onFirstPage=self.drawPageHeader,
                         onLaterPages=self.drawPageHeader)
        # print "%d pages." % self.rldoc.page
        # del self._sdoc

    def onBeginEnvironment(self, e):
        if isinstance(e, Body):
            pass  # raise 'allowed only once'
        elif isinstance(e, TableInstance):
            assert not e.__dict__.has_key('_rows')
            e._rows = []
            #return
        elif isinstance(e, TableRow):
            pass
        elif isinstance(e, ListInstance):
            pass
        #elif isinstance(e,ListItem):
        #    return
        elif isinstance(e, BarcodeFlowable):
            pass
        elif isinstance(e, Story):
            pass
        else:
            raise '%s : unknown environment' % repr(e)

    def onEndEnvironment(self, e):
        if isinstance(e, Body):
            pass
            # self.render(e.getStory())
            # raise 'allowed only once'
            # return e.getStory()
        elif isinstance(e, TableInstance):
            e.getParent().toStory(self.compileTable(e))
        elif isinstance(e, TableRow):
            # print 'compileEndEnvironment.TableRow'
            table = e.getParent()
            assert table.__class__ is TableInstance
            row = e.cells
            table._rows.append(row)
        elif isinstance(e, ListInstance):
            pass
            #return None
        #elif isinstance(e,ListItem):
        #    return self.compileListItem(e)
        elif isinstance(e, BarcodeFlowable):
            e.getParent().toStory(self.compileBarcode(e))
        elif isinstance(e, Story):
            pass
        else:
            raise '%s : unknown environment' % repr(e)

    def render(self, elem):
        if elem is None:
            return
        if type(elem) is types.ListType:
            self._story += elem
        else:
            self._story.append(elem)

    def getPageNumber(self):
        return self.rldoc.page

    def drawPageHeader(self, canvas, rldoc):
        assert rldoc == self.rldoc
        style = self.document.docstyle
        textWidth = self.document.getDocumentWidth()

        x = style.leftMargin
        y = style.pagesize[1] - style.topMargin  # headerHeight

        # x and y are the bottom left corner of the frame. The
        # canvas' (0,0) is not the paper's (0,0) but the bottom left
        # corner of the printable area

        self.drawFrame(canvas,
                       style.header,
                       x,
                       y,
                       textWidth,
                       style.topMargin,
                       vAlign="BOTTOM")

        y = style.bottomMargin
        self.drawFrame(canvas,
                       style.footer,
                       x,
                       y,
                       textWidth,
                       style.bottomMargin,
                       vAlign="TOP")

    def drawFrame(self,
                  canvas,
                  func,
                  x,
                  y,
                  textWidth,
                  availableHeight,
                  vAlign="TOP"):
        story = self.document.makeStory(func, textWidth)
        if story is not None:
            height = 0
            for e in story:
                unused, h = e.wrap(textWidth, availableHeight)
                height += h
                availableHeight -= h

            if vAlign == "BOTTOM":
                pass
            elif vAlign == "MIDDLE":
                y -= (height / 2)
            elif vAlign == "TOP":
                y -= height

            canvas.saveState()
            f = Frame(x,
                      y,
                      textWidth,
                      height,
                      leftPadding=0,
                      rightPadding=0,
                      bottomPadding=0,
                      topPadding=0)
            #showBoundary=True)
            f.addFromList(story, canvas)
            canvas.restoreState()

    def setTitle(self, title):
        "Sets the document title. Does not print it."
        self.rldoc.title = title

    def getTitle(self):
        "Returns the document title."
        return self.rldoc.title

    def compilePara(self, txt, style, wrap):
        try:
            txt.decode('utf8')
        except UnicodeDecodeError, e:
            print repr(txt)
            raise

        if wrap:
            elem = Paragraph(txt, style)
        else:
            elem = XPreformatted(txt, style)
        return elem
Пример #21
0
def format_doc(filename, local_notams, area_notams, boring_notams,
               local_coords, header, date, mapinfo, mapdata):

    date_str = date.strftime('%a, %d %b %y')

    # Define Platypus template and paragraph styles
    doc = DocTemplate(filename,
                      date_str,
                      local_coords,
                      mapinfo,
                      mapdata,
                      leftMargin=15 * mm,
                      rightMargin=15 * mm,
                      bottomMargin=10 * mm,
                      topMargin=15 * mm,
                      title='NOTAM',
                      author='Freeflight')

    subStyle = ParagraphStyle('Sub',
                              fontName='Helvetica-Oblique',
                              fontSize=16,
                              spaceBefore=2 * mm,
                              spaceAfter=5 * mm)

    notamStyle = ParagraphStyle('Notam',
                                fontName='Helvetica',
                                fontSize=9,
                                bulletFontName='Helvetica-Bold',
                                bulletFontSize=10,
                                leftIndent=8 * mm,
                                spaceAfter=3 * mm)

    otherStyle = ParagraphStyle('Other',
                                fontName='Helvetica',
                                fontSize=9,
                                bulletFontName='Symbol',
                                bulletFontSize=10,
                                leftIndent=8 * mm,
                                spaceAfter=3 * mm)

    # Generate the NOTAM document.
    story = []
    story.append(PageBreak())

    story.append(Paragraph('<b>NOTAM Header</b>', subStyle))
    h = '\n'.join([hl for hl in header.splitlines() if hl])
    story.append(XPreformatted(h, otherStyle))
    story.append(Paragraph('<b>Plotted Navigation Warnings</b>', subStyle))
    story.append(Paragraph(
        'Plotted Navigation Warnings are Restrictions of all types '\
        'and Warnings of type: <i>Air Display</i>, <i>Aerobatics</i>, '\
        '<i>Glider Flying</i>, <i>Missile, Gun or Rocket Firing</i>, '\
        '<i>Parachute Dropping Area</i> and <i>Radioactive '\
        'Materials and Toxic Chemicals</i>. Also plotted are activation or '\
        'installation of Airspace types <i>CTZ</i>, <i>CTA</i>, <i>ATS '\
        'route</i>, <i>TMA</i> and <i>ATZ</i>', otherStyle))
    for n, notam in enumerate(local_notams):
        story.append(
            KeepTogether(
                XPreformatted(notam, notamStyle, bulletText=str(n + 1))))

    if area_notams:
        paras = [
            XPreformatted(n, otherStyle, bulletText="\N{BULLET}")
            for n in area_notams
        ]

        head = '<b>Non-Plotted Navigation Warnings</b> (Radius > 30nm)'
        story.append(KeepTogether([Paragraph(head, subStyle), paras[0]]))
        for p in paras[1:]:
            story.append(KeepTogether(p))

    if boring_notams:
        paras = [
            XPreformatted(n, otherStyle, bulletText="\N{BULLET}")
            for n in boring_notams
        ]

        head = '<b>All Other Navigation Warnings</b> (Sorted South to North)'
        story.append(KeepTogether([Paragraph(head, subStyle), paras[0]]))
        for p in paras[1:]:
            story.append(KeepTogether(p))

    doc.build(story, onFirstPage=drawFirstPage)