Python reportlab.lib.styles.ParagraphStyle() Examples

The following are 28 code examples of reportlab.lib.styles.ParagraphStyle(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module reportlab.lib.styles , or try the search function .
Example #1
Source File: generic_pdf.py    From multiscanner with Mozilla Public License 2.0 7 votes vote down vote up
def __init__(self, pdf_components):
        self.style = getSampleStyleSheet()
        self.style['Normal'].leading = 16
        self.style.add(ParagraphStyle(name='centered', alignment=TA_CENTER))
        self.style.add(ParagraphStyle(name='centered_wide', alignment=TA_CENTER,
                                      leading=18))
        self.style.add(ParagraphStyle(name='section_body',
                                      parent=self.style['Normal'],
                                      spaceAfter=inch * .05,
                                      fontSize=11))
        self.style.add(ParagraphStyle(name='bullet_list',
                                      parent=self.style['Normal'],
                                      fontSize=11))
        if six.PY3:
            self.buffer = six.BytesIO()
        else:
            self.buffer = six.StringIO()
        self.firstPage = True
        self.document = SimpleDocTemplate(self.buffer, pagesize=letter,
                                          rightMargin=12.7 * mm, leftMargin=12.7 * mm,
                                          topMargin=120, bottomMargin=80)

        self.tlp_color = pdf_components.get('tlp_color', '')
        self.pdf_components = pdf_components
        self.pdf_list = [] 
Example #2
Source File: report.py    From flask-restful-example with MIT License 6 votes vote down vote up
def paragraph_model(msg):
    """
    添加一段文字
    :param msg:
    :return:
    """
    # 设置文字样式
    style = ParagraphStyle(
        name='Normal',
        fontName='SimSun',
        fontSize=50,
    )

    return Paragraph(msg, style=style) 
Example #3
Source File: pdf_rpts.py    From tia with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self):
        cp = rlab.CoverPage(self.title, subtitle2=self.author)
        self.pdf = pdf = rlab.PdfBuilder(self.path, coverpage=cp)
        # Setup stylesheet
        tb = ParagraphStyle('TitleBar', parent=pdf.stylesheet['Normal'], fontName='Helvetica-Bold', fontSize=10,

                    leading=10, alignment=TA_CENTER)
        'TitleBar' not in pdf.stylesheet and pdf.stylesheet.add(tb)
        # define templates
        self.define_portfolio_summary_template()
        self.define_position_summary_template()
        self.define_summary_template()
        # Show the summary page
        self.add_summary_page()
        # Build the portfolio and position details for each result
        for r in self.results:
            self.add_portfolio_page(r)
            self.add_position_page(r)
        pdf.save() 
Example #4
Source File: para.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test2(canv,testpara):
    #print test_program; return
    from reportlab.lib.units import inch
    from reportlab.lib.styles import ParagraphStyle
    from reportlab.lib import rparsexml
    parsedpara = rparsexml.parsexmlSimple(testpara,entityReplacer=None)
    S = ParagraphStyle("Normal", None)
    P = Para(S, parsedpara)
    (w, h) = P.wrap(5*inch, 10*inch)
    print("wrapped as", (h,w))
    canv.saveState()
    canv.translate(1*inch, 1*inch)
    canv.rect(0,0,5*inch,10*inch, fill=0, stroke=1)
    P.canv = canv
    canv.saveState()
    P.draw()
    canv.restoreState()
    canv.setStrokeColorRGB(1, 0, 0)
    #canv.translate(0, 3*inch)
    canv.rect(0,0,w,h, fill=0, stroke=1)
    canv.restoreState()
    canv.showPage() 
Example #5
Source File: doctemplate.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: figures.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def demo1(canvas):
    frame = Frame(
                    2*inch,     # x
                    4*inch,     # y at bottom
                    4*inch,     # width
                    5*inch,     # height
                    showBoundary = 1  # helps us see what's going on
                    )
    bodyStyle = ParagraphStyle('Body', fontName=_baseFontName, fontSize=24, leading=28, spaceBefore=6)
    para1 = Paragraph('Spam spam spam spam. ' * 5, bodyStyle)
    para2 = Paragraph('Eggs eggs eggs. ' * 5, bodyStyle)
    mydata = [para1, para2]

    #this does the packing and drawing.  The frame will consume
    #items from the front of the list as it prints them
    frame.addFromList(mydata,canvas) 
Example #7
Source File: figures.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def _getCaptionPara(self):
        caption = self.caption
        captionFont = self.captionFont
        captionSize = self.captionSize
        captionTextColor = self.captionTextColor
        captionBackColor = self.captionBackColor
        if self._captionData!=(caption,captionFont,captionSize,captionTextColor,captionBackColor):
            self._captionData = (caption,captionFont,captionSize,captionTextColor,captionBackColor)
            self.captionStyle = ParagraphStyle(
                'Caption',
                fontName=captionFont,
                fontSize=captionSize,
                leading=1.2*captionSize,
                textColor = captionTextColor,
                backColor = captionBackColor,
                #seems to be getting ignored
                spaceBefore=self.captionGap or 0.5*captionSize,
                alignment=TA_CENTER)
            #must build paragraph now to get sequencing in synch with rest of story
            self.captionPara = Paragraph(self.caption, self.captionStyle) 
Example #8
Source File: doctemplate.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #9
Source File: para.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def test2(canv,testpara):
    #print test_program; return
    from reportlab.lib.units import inch
    from reportlab.lib.styles import ParagraphStyle
    from reportlab.lib import rparsexml
    parsedpara = rparsexml.parsexmlSimple(testpara,entityReplacer=None)
    S = ParagraphStyle("Normal", None)
    P = Para(S, parsedpara)
    (w, h) = P.wrap(5*inch, 10*inch)
    print "wrapped as", (h,w)
    canv.saveState()
    canv.translate(1*inch, 1*inch)
    canv.rect(0,0,5*inch,10*inch, fill=0, stroke=1)
    P.canv = canv
    canv.saveState()
    P.draw()
    canv.restoreState()
    canv.setStrokeColorRGB(1, 0, 0)
    #canv.translate(0, 3*inch)
    canv.rect(0,0,w,h, fill=0, stroke=1)
    canv.restoreState()
    canv.showPage() 
Example #10
Source File: pdf_form_display.py    From intake with MIT License 5 votes vote down vote up
def Style(name, font='Helvetica', size=12, leading=None, color=colors.black):
    return ParagraphStyle(
        name,
        fontName=font,
        fontSize=size,
        leading=leading or size * LEADING_FACTOR,
        textColor=color
    ) 
Example #11
Source File: generic_pdf.py    From multiscanner with Mozilla Public License 2.0 5 votes vote down vote up
def add_banner(self, canvas, doc):
        height_adjust = 1
        if self.tlp_color:
            if self.tlp_color == 'WHITE':
                text_color = white
            elif self.tlp_color == 'RED':
                text_color = red
            elif self.tlp_color == 'AMBER':
                text_color = orange
            else:
                text_color = lawngreen
                self.tlp_color = 'GREEN'

            if 'banner_style' not in self.style:
                self.style.add(ParagraphStyle(name='banner_style',
                                              textColor=text_color,
                                              textTransform='uppercase',
                                              alignment=TA_RIGHT))

            banner = Paragraph(
                self.span_text(self.bold_text('TLP:' + self.tlp_color), bgcolor='black'),
                self.style['banner_style'])
            w, h = banner.wrap(doc.width, doc.topMargin)
            banner.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin + (h + 12 * mm))
            w, h = banner.wrap(doc.width, doc.bottomMargin)
            banner.drawOn(canvas, doc.leftMargin, h + 12 * mm)

            height_adjust = 3

        return height_adjust 
Example #12
Source File: builder.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def new_title_bar(self, title, color=None):
        """Return an array of Pdf Objects which constitute a Header"""
        # Build a title bar for top of page
        w, t, c = '100%', 2, color or HexColor('#404040')
        title = '<b>{0}</b>'.format(title)
        if 'TitleBar' not in self.stylesheet:
            tb = ParagraphStyle('TitleBar', parent=self.stylesheet['Normal'], fontName='Helvetica-Bold', fontSize=10,
                                leading=10, alignment=TA_CENTER)
            self.stylesheet.add(tb)
        return [HRFlowable(width=w, thickness=t, color=c, spaceAfter=2, vAlign='MIDDLE', lineCap='square'),
                self.new_paragraph(title, 'TitleBar'),
                HRFlowable(width=w, thickness=t, color=c, spaceBefore=2, vAlign='MIDDLE', lineCap='square')] 
Example #13
Source File: tableofcontents.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def getLevelStyle(self, n):
        '''Returns the style for level n, generating and caching styles on demand if not present.'''
        if not hasattr(self.textStyle, '__iter__'):
            self.textStyle = [self.textStyle]
        try:
            return self.textStyle[n]
        except IndexError:
            self.textStyle = list(self.textStyle)
            prevstyle = self.getLevelStyle(n-1)
            self.textStyle.append(ParagraphStyle(
                    name='%s-%d-indented' % (prevstyle.name, n),
                    parent=prevstyle,
                    firstLineIndent = prevstyle.firstLineIndent+.2*cm,
                    leftIndent = prevstyle.leftIndent+.2*cm))
            return self.textStyle[n] 
Example #14
Source File: tableofcontents.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def setup(self, style=None, dot=None, tableStyle=None, headers=True, name=None, format='123', offset=0):
        """
        This method makes it possible to change styling and other parameters on an existing object.
        
        style is the paragraph style to use for index entries.
        dot can either be None or a string. If it's None, entries are immediatly followed by their
            corresponding page numbers. If it's a string, page numbers are aligned on the right side
            of the document and the gap filled with a repeating sequence of the string.
        tableStyle is the style used by the table which the index uses to draw itself. Use this to
            change properties like spacing between elements.
        headers is a boolean. If it is True, alphabetic headers are displayed in the Index when the first
        letter changes. If False, we just output some extra space before the next item 
        name makes it possible to use several indexes in one document. If you want this use this
            parameter to give each index a unique name. You can then index a term by refering to the
            name of the index which it should appear in:
            
                <index item="term" name="myindex" />

        format can be 'I', 'i', '123',  'ABC', 'abc'
        """
        
        if style is None:
            style = ParagraphStyle(name='index',
                                        fontName=_baseFontName,
                                        fontSize=11)
        self.textStyle = style
        self.tableStyle = tableStyle or defaultTableStyle
        self.dot = dot
        self.headers = headers
        if name is None:
            from reportlab.platypus.paraparser import DEFAULT_INDEX_NAME as name
        self.name = name
        self.formatFunc = self.getFormatFunc(format)
        self.offset = offset 
Example #15
Source File: tableofcontents.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def getLevelStyle(self, n):
        '''Returns the style for level n, generating and caching styles on demand if not present.'''
        try:
            return self.levelStyles[n]
        except IndexError:
            prevstyle = self.getLevelStyle(n-1)
            self.levelStyles.append(ParagraphStyle(
                    name='%s-%d-indented' % (prevstyle.name, n),
                    parent=prevstyle,
                    firstLineIndent = prevstyle.firstLineIndent+delta,
                    leftIndent = prevstyle.leftIndent+delta))
            return self.levelStyles[n] 
Example #16
Source File: fd_api_doc.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def create_img_table(self, dir):
        item_tbl_data = []
        item_tbl_row = []
         
        for i, file in enumerate(os.listdir(dir)):
            last_item = len(os.listdir(dir)) - 1
            if ".png" in file:
                img = Image(os.path.join(dir, file), inch, inch)
                img_name = file.replace(".png", "")
                              
                if len(item_tbl_row) == 4:
                    item_tbl_data.append(item_tbl_row)
                    item_tbl_row = []
                elif i == last_item:
                    item_tbl_data.append(item_tbl_row)
                      
                i_tbl = Table([[img], [Paragraph(img_name, ParagraphStyle("item name style", wordWrap='CJK'))]])
                item_tbl_row.append(i_tbl)    
                    
        if len(item_tbl_data) > 0:
            item_tbl = Table(item_tbl_data, colWidths=125)
            self.elements.append(item_tbl)
            self.elements.append(Spacer(1, inch * 0.5)) 
Example #17
Source File: figures.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def demo1(canvas):
    frame = Frame(
                    2*inch,     # x
                    4*inch,     # y at bottom
                    4*inch,     # width
                    5*inch,     # height
                    showBoundary = 1  # helps us see what's going on
                    )
    bodyStyle = ParagraphStyle('Body', fontName=_baseFontName, fontSize=24, leading=28, spaceBefore=6)
    para1 = Paragraph('Spam spam spam spam. ' * 5, bodyStyle)
    para2 = Paragraph('Eggs eggs eggs. ' * 5, bodyStyle)
    mydata = [para1, para2]

    #this does the packing and drawing.  The frame will consume
    #items from the front of the list as it prints them
    frame.addFromList(mydata,canvas) 
Example #18
Source File: figures.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _getCaptionPara(self):
        caption = self.caption
        captionFont = self.captionFont
        captionSize = self.captionSize
        captionTextColor = self.captionTextColor
        captionBackColor = self.captionBackColor
        captionAlign = self.captionAlign
        captionPosition = self.captionPosition
        if self._captionData!=(caption,captionFont,captionSize,captionTextColor,captionBackColor,captionAlign,captionPosition):
            self._captionData = (caption,captionFont,captionSize,captionTextColor,captionBackColor,captionAlign,captionPosition)
            if isinstance(caption,Paragraph):
                self.captionPara = caption
            elif isinstance(caption,strTypes):
                self.captionStyle = ParagraphStyle(
                    'Caption',
                    fontName=captionFont,
                    fontSize=captionSize,
                    leading=1.2*captionSize,
                    textColor = captionTextColor,
                    backColor = captionBackColor,
                    #seems to be getting ignored
                    spaceBefore=self.captionGap,
                    alignment=TA_LEFT if captionAlign=='left' else TA_RIGHT if captionAlign=='right' else TA_CENTER,
                    )
                #must build paragraph now to get sequencing in synch with rest of story
                self.captionPara = Paragraph(self.caption, self.captionStyle)
            else:
                raise ValueError('Figure caption of type %r is not a string or Paragraph' % type(caption)) 
Example #19
Source File: tableofcontents.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def getLevelStyle(self, n):
        '''Returns the style for level n, generating and caching styles on demand if not present.'''
        if not hasattr(self.textStyle, '__iter__'):
            self.textStyle = [self.textStyle]
        try:
            return self.textStyle[n]
        except IndexError:
            self.textStyle = list(self.textStyle)
            prevstyle = self.getLevelStyle(n-1)
            self.textStyle.append(ParagraphStyle(
                    name='%s-%d-indented' % (prevstyle.name, n),
                    parent=prevstyle,
                    firstLineIndent = prevstyle.firstLineIndent+.2*cm,
                    leftIndent = prevstyle.leftIndent+.2*cm))
            return self.textStyle[n] 
Example #20
Source File: tableofcontents.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def setup(self, style=None, dot=None, tableStyle=None, headers=True, name=None, format='123', offset=0):
        """
        This method makes it possible to change styling and other parameters on an existing object.

        style is the paragraph style to use for index entries.
        dot can either be None or a string. If it's None, entries are immediatly followed by their
            corresponding page numbers. If it's a string, page numbers are aligned on the right side
            of the document and the gap filled with a repeating sequence of the string.
        tableStyle is the style used by the table which the index uses to draw itself. Use this to
            change properties like spacing between elements.
        headers is a boolean. If it is True, alphabetic headers are displayed in the Index when the first
        letter changes. If False, we just output some extra space before the next item
        name makes it possible to use several indexes in one document. If you want this use this
            parameter to give each index a unique name. You can then index a term by refering to the
            name of the index which it should appear in:

                <index item="term" name="myindex" />

        format can be 'I', 'i', '123',  'ABC', 'abc'
        """

        if style is None:
            style = ParagraphStyle(name='index',
                                        fontName=_baseFontName,
                                        fontSize=11)
        self.textStyle = style
        self.tableStyle = tableStyle or defaultTableStyle
        self.dot = dot
        self.headers = headers
        if name is None:
            from reportlab.platypus.paraparser import DEFAULT_INDEX_NAME as name
        self.name = name
        self.formatFunc = self.getFormatFunc(format)
        self.offset = offset 
Example #21
Source File: tableofcontents.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def getLevelStyle(self, n):
        '''Returns the style for level n, generating and caching styles on demand if not present.'''
        try:
            return self.levelStyles[n]
        except IndexError:
            prevstyle = self.getLevelStyle(n-1)
            self.levelStyles.append(ParagraphStyle(
                    name='%s-%d-indented' % (prevstyle.name, n),
                    parent=prevstyle,
                    firstLineIndent = prevstyle.firstLineIndent+delta,
                    leftIndent = prevstyle.leftIndent+delta))
            return self.levelStyles[n] 
Example #22
Source File: report.py    From flask-restful-example with MIT License 5 votes vote down vote up
def pdf_write(generated_pdf_path):
    """
    生成pdf
    :return:
    """
    # 增加的字体,支持中文显示,需要自行下载支持中文的字体
    font_path = current_app.config.get("SIM_SUN")

    pdfmetrics.registerFont(TTFont('SimSun', os.path.join(font_path, 'SimSun.ttf')))
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(fontName='SimSun', name='SimSun', leading=20, fontSize=12))
    data = list()
    # 添加一段文字
    paragraph = paragraph_model("测试添加一段文字")
    data.append(paragraph)
    data.append(PageBreak())  # 分页标识
    # 添加table和图片
    table = table_model()
    data.append(table)
    data.append(PageBreak())  # 分页标识
    img = image_model()
    data.append(img)

    # 设置生成pdf的名字和编剧
    pdf = SimpleDocTemplate(generated_pdf_path, rightMargin=0, leftMargin=0, topMargin=40, bottomMargin=0, )
    # 设置pdf每页的大小
    pdf.pagesize = (9 * inch, 10 * inch)

    pdf.multiBuild(data)
    return generated_pdf_path 
Example #23
Source File: letters.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, to_addr_lines, from_name_lines, date=None,
                 closing="Yours truly", signer=None, paragraphs=None, cosigner_lines=None, use_sig=True,
                 body_font_size=None, cc_lines=None):
        self.date = date or datetime.date.today()
        self.closing = closing
        self.flowables = []
        self.to_addr_lines = to_addr_lines
        self.from_name_lines = from_name_lines
        self.cosigner_lines = cosigner_lines
        self.signer = signer
        self.use_sig = use_sig
        if cc_lines:
            self.cc_lines = [cc for cc in cc_lines if cc.strip()]
        else:
            self.cc_lines = None
        if paragraphs:
            self.add_paragraphs(paragraphs)

        # styles
        self.line_height = (body_font_size or 12) + 1
        self.content_style = ParagraphStyle(name='Normal',
                                            fontName='BemboMTPro',
                                            fontSize=body_font_size or 12,
                                            leading=self.line_height,
                                            allowWidows=0,
                                            allowOrphans=0,
                                            alignment=TA_JUSTIFY,
                                            textColor=black)
        self.table_style = TableStyle([
                    ('FONT', (0,0), (-1,-1), 'BemboMTPro', 12, self.line_height),
                    ('TOPPADDING', (0,0), (-1,-1), 0),
                    ('BOTTOMPADDING', (0,0), (-1,-1), 0),
                    ]) 
Example #24
Source File: letters.py    From coursys with GNU General Public License v3.0 4 votes vote down vote up
def _draw_header(self, c, doc):
        """
        Draw the top-of-page part of the letterhead (used only on first page of letter)
        """
        # SFU logo
        c.drawImage(logofile, x=self.lr_margin + 6, y=self.pg_h-self.top_margin-0.5*inch, width=1*inch, height=0.5*inch)

        # unit text
        c.setFont('BemboMTPro', 12)
        c.setFillColor(doc.sfu_blue)
        parent = self.unit.parent
        if not parent or parent.label == 'UNIV':
            # faculty-level unit: just the unit name
            self._drawStringLeading(c, 2*inch, self.pg_h - self.top_margin - 0.375*inch, self.unit.name.translate(doc.sc_trans_bembo), charspace=1.2)
        else:
            # department with faculty above it: display both
            self._drawStringLeading(c, 2*inch, self.pg_h - self.top_margin - 0.325*inch, self.unit.name.translate(doc.sc_trans_bembo), charspace=1.2)
            c.setFillColor(doc.sfu_grey)
            c.setFont('BemboMTPro', 8.5)
            self._drawStringLeading(c, 2*inch, self.pg_h - self.top_margin - 0.48*inch, parent.name, charspace=0.3)

        # address block
        addr_style = ParagraphStyle(name='Normal',
                                      fontName='BemboMTPro',
                                      fontSize=10,
                                      leading=10,
                                      textColor=doc.sfu_grey)
        self._put_lines(doc, c, self.unit.address(), 2*inch, self.pg_h - self.top_margin - 0.75*inch, 2.25*inch, addr_style, 8, 1.5)

        # phone numbers block
        lines = ['Tel'.translate(doc.sc_trans_bembo) + ' ' + self.unit.tel().replace('-', '.')]
        if self.unit.fax():
            lines.append('Fax'.translate(doc.sc_trans_bembo) + ' ' + self.unit.fax().replace('-', '.'))
        self._put_lines(doc, c, lines, 4.5*inch, self.pg_h - self.top_margin - 0.75*inch, 1.5*inch, addr_style, 8, 1.5)

        # web and email block
        lines = []
        if self.unit.email():
            lines.append(self.unit.email())
        web = self.unit.web()
        if web.startswith("http://"):
            web = web[7:]
        if web.endswith("/"):
            web = web[:-1]
        lines.append(web)
        self._put_lines(doc, c, lines, 6.25*inch, self.pg_h - self.top_margin - 0.75*inch, 1.5*inch, addr_style, 8, 1.5) 
Example #25
Source File: fd_api_doc.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def create_hdr(self, name, font_size):
        hdr_style = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                                ('BOTTOMPADDING', (0, 0), (-1, -1), 15),
                                ('TOPPADDING', (0, 0), (-1, -1), 15),
                                ('FONTSIZE', (0, 0), (-1, -1), 8),
                                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                ('ALIGN', (0, 0), (-1, 0), 'LEFT'),
                                ('LINEBELOW', (0, 0), (-1, -1), 2, colors.black),
                                ('BACKGROUND', (0, 1), (-1, -1), colors.white)])        
        
        name_p = Paragraph(name, ParagraphStyle("Category name style", fontSize=font_size))
        hdr_tbl = Table([[name_p]], colWidths = 500, rowHeights = None, repeatRows = 1)
        hdr_tbl.setStyle(hdr_style)
        self.elements.append(hdr_tbl) 
Example #26
Source File: reporting.py    From attack_monitor with GNU General Public License v3.0 4 votes vote down vote up
def pdf_initalize_styles(self):
        self.load_font()
        self.styles = getSampleStyleSheet()

        # ADD CUSTOM STYLES
        self.styles.add(ParagraphStyle(name='subtitle',
                                       parent=self.styles['Normal'],
                                       fontSize=12,
                                       leading=22,
                                       alignment=TA_CENTER,
                                       spaceAfter=6), alias='subtitle',

                        )

        self.styles.add(ParagraphStyle(name='bigtitle',
                                       parent=self.styles['title'],
                                       fontSize=30,
                                       leading=22,
                                       alignment=TA_CENTER,
                                       spaceAfter=6), alias='bigtitle')

        self.styles.add(ParagraphStyle(name='italictitle',
                                   parent=self.styles['Italic'],
                                   fontSize=12,
                                   leading=22,
                                   alignment=TA_CENTER,
                                   spaceAfter=6), alias='italictitle')

        self.styles.add(ParagraphStyle(name="commandline",
                                       parent=self.styles['Italic'],
                                       fontName="freeserif",
                                       fontSize=8,
                                       leading=12,
                                       leftIndent=0,
                                       alignment=TA_RIGHT,
                                       spaceAfter=6),
                        alias="commandline")

        for i in range(0,9):
            style_name = "dynamicindent" + str(i)
            power_factor = 6
            self.styles.add(ParagraphStyle(name=style_name,
                                           parent=self.styles['Normal'],
                                           fontName="freeserif",
                                           fontSize=12,
                                           leading=12,
                                           leftIndent=i*power_factor,
                                           alignment=TA_LEFT,
                                           spaceAfter=6),
                            alias=style_name) 
Example #27
Source File: flowables.py    From rst2pdf with MIT License 4 votes vote down vote up
def wrap(self, availWidth, availHeight):
        """Adds hyperlink to toc entry."""

        widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth)

        # makes an internal table which does all the work.
        # we draw the LAST RUN's entries!  If there are
        # none, we make some dummy data to keep the table
        # from complaining
        if len(self._lastEntries) == 0:
            if reportlab.Version <= '2.3':
                _tempEntries = [(0, 'Placeholder for table of contents', 0)]
            else:
                _tempEntries = [(0, 'Placeholder for table of contents', 0, None)]
        else:
            _tempEntries = self._lastEntries

        if _tempEntries:
            base_level = _tempEntries[0][0]
        else:
            base_level = 0
        tableData = []
        for entry in _tempEntries:
            level, text, pageNum = entry[:3]
            left_col_level = level - base_level
            if reportlab.Version > '2.3':  # For ReportLab post-2.3
                leftColStyle = self.getLevelStyle(left_col_level)
            else:  # For ReportLab <= 2.3
                leftColStyle = self.levelStyles[left_col_level]
            label = self.refid_lut.get((level, text, pageNum), None)
            if label:
                pre = u'<a href="#%s" color="%s">' % (label, self.linkColor)
                post = u'</a>'
                if isinstance(text, bytes):
                    text = text.decode('utf-8')
                text = pre + text + post
            else:
                pre = ''
                post = ''
            # right col style is right aligned
            rightColStyle = ParagraphStyle(
                name='leftColLevel%d' % left_col_level,
                parent=leftColStyle,
                leftIndent=0,
                alignment=TA_RIGHT,
            )
            leftPara = Paragraph(text, leftColStyle)
            rightPara = Paragraph(pre + str(pageNum) + post, rightColStyle)
            tableData.append([leftPara, rightPara])

        self._table = Table(tableData, colWidths=widths, style=self.tableStyle)

        self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight)
        return self.width, self.height 
Example #28
Source File: flowables.py    From rst2pdf with MIT License 4 votes vote down vote up
def wrap(self, availWidth, availHeight):
        """Adds hyperlink to toc entry."""

        widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth)

        # makes an internal table which does all the work.
        # we draw the LAST RUN's entries!  If there are
        # none, we make some dummy data to keep the table
        # from complaining
        if len(self._lastEntries) == 0:
            if reportlab.Version <= '2.3':
                _tempEntries = [(0, 'Placeholder for table of contents', 0)]
            else:
                _tempEntries = [(0, 'Placeholder for table of contents', 0, None)]
        else:
            _tempEntries = self._lastEntries

        if _tempEntries:
            base_level = _tempEntries[0][0]
        else:
            base_level = 0
        tableData = []
        for entry in _tempEntries:
            level, text, pageNum = entry[:3]
            left_col_level = level - base_level
            if reportlab.Version > '2.3':  # For ReportLab post-2.3
                leftColStyle = self.getLevelStyle(left_col_level)
            else:  # For ReportLab <= 2.3
                leftColStyle = self.levelStyles[left_col_level]
            label = self.refid_lut.get((level, text, pageNum), None)
            if label:
                pre = u'<a href="#%s" color="%s">' % (label, self.linkColor)
                post = u'</a>'
                if isinstance(text, bytes):
                    text = text.decode('utf-8')
                text = pre + text + post
            else:
                pre = ''
                post = ''
            # right col style is right aligned
            rightColStyle = ParagraphStyle(
                name='leftColLevel%d' % left_col_level,
                parent=leftColStyle,
                leftIndent=0,
                alignment=TA_RIGHT,
            )
            leftPara = Paragraph(text, leftColStyle)
            rightPara = Paragraph(pre + str(pageNum) + post, rightColStyle)
            tableData.append([leftPara, rightPara])

        self._table = Table(tableData, colWidths=widths, style=self.tableStyle)

        self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight)
        return self.width, self.height