Python reportlab.platypus.Paragraph() Examples

The following are 30 code examples of reportlab.platypus.Paragraph(). 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.platypus , or try the search function .
Example #1
Source File: pygments2xpre.py    From stdm with GNU General Public License v2.0 7 votes vote down vote up
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' 
Example #2
Source File: generatereport.py    From kobo-predict with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def afterFlowable(self, flowable):
        if flowable.__class__.__name__ == 'Paragraph':
            text = flowable.getPlainText()
            style = flowable.style.name
            if style == 'Heading1':
                 key = 'h1-%s' % self.seq.nextf('heading1')
                 self.canv.bookmarkPage(key)
                 self.notify('TOCEntry', (0, text, self.page, key))
            if style == 'Heading2':
                 key = 'h2-%s' % self.seq.nextf('heading2')
                 self.canv.bookmarkPage(key)
                 self.notify('TOCEntry', (1, text, self.page, key))
                 
            if style == 'Heading3':
                 key = 'h3-%s' % self.seq.nextf('heading3')
                 self.canv.bookmarkPage(key)
                 self.notify('TOCEntry', (2, text, self.page, key)) 
Example #3
Source File: api.py    From callisto-core with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_cover_page(self, report_id, recipient):
        # title = f"{self.report_title} No.: {report_id}"

        styles = getSampleStyleSheet()
        headline_style = styles["Heading1"]
        headline_style.alignment = TA_CENTER
        headline_style.fontSize = 48
        subtitle_style = styles["Heading2"]
        subtitle_style.fontSize = 24
        subtitle_style.leading = 26
        subtitle_style.alignment = TA_CENTER

        CoverPage = []
        logo = os.path.join(settings.BASE_DIR, self.logo_path)

        image = Image(logo, 3 * inch, 3 * inch)
        CoverPage.append(image)
        CoverPage.append(Spacer(1, 18))
        CoverPage.append(Paragraph("CONFIDENTIAL", headline_style))
        # paragraph = Paragraph(
        #     f"Intended for: {recipient}, Title IX Coordinator", subtitle_style)
        # CoverPage.append(paragraph)
        CoverPage.append(PageBreak())
        return CoverPage

    # entrypoints 
Example #4
Source File: templates.py    From HH---POS-Accounting-and-ERP-Software with MIT License 6 votes vote down vote up
def _item_raw_data_and_subtotal(self):
        item_data = []
        item_subtotal = 0

        for item in self._items:
            if not isinstance(item, Item):
                continue

            item_data.append(
                (
                    item.name,
                    Paragraph(item.description, self._defined_styles.get('TableParagraph')),
                    item.units,
                    item.unit_price,
                    item.unit_price_discounted,
                    ( item.unit_price - item.unit_price_discounted ) * item.units,
                    item.amount
                )
            )
            item_subtotal += item.amount

        return item_data, item_subtotal 
Example #5
Source File: genelements.py    From rst2pdf with MIT License 6 votes vote down vote up
def gather_elements(self, client, node, style):
        odd = []
        even = []
        if node.children:
            if isinstance(node.children[0], docutils.nodes.paragraph):
                if node.children[0].get('classes'):
                    s = client.styles[node.children[0].get('classes')[0]]
                else:
                    s = style
                odd = [Paragraph(client.gather_pdftext(node.children[0]), s)]
            else:
                # A compound element
                odd = client.gather_elements(node.children[0])
        if len(node.children) > 1:
            if isinstance(node.children[1], docutils.nodes.paragraph):
                if node.children[1].get('classes'):
                    s = client.styles[node.children[1].get('classes')[0]]
                else:
                    s = style
                even = [Paragraph(client.gather_pdftext(node.children[1]), s)]
            else:
                even = client.gather_elements(node.children[1])

        return [OddEven(odd=odd, even=even)] 
Example #6
Source File: report.py    From nanopype with MIT License 6 votes vote down vote up
def add_section_sequences(self, plots=[], stats=None):
        section = self.get_section_number()
        subsection = itertools.count(1)
        if stats is not None:
            self.story.append(Paragraph("{:d} Basecalling".format(section), self.heading_style))
            self.story.append(Spacer(1, 0))
            self.story.append(Paragraph("{:d}.{:d} Summary".format(section, next(subsection)), self.heading2_style))
            #['Tag', 'Basecalling', 'Sum', 'Mean', 'Median', 'N50', 'Maximum']
            header = ['', ''] + list(stats.columns.values[2:])
            table_data = [header] + [[y if isinstance(y, str) else '{:.0f}'.format(y) for y in x] for x in stats.values]
            table_style = [ ('FONTSIZE', (0,0), (-1, -1), 10),
                            ('LINEABOVE', (0,1), (-1,1), 0.5, colors.black),
                            ('LINEBEFORE', (2,0), (2,-1), 0.5, colors.black),
                            ('ALIGN', (0,0), (1,-1), 'LEFT'),
                            ('ALIGN', (2,0), (-1,-1), 'RIGHT')]
            self.story.append(Table(table_data, style=table_style))
            self.story.append(Spacer(1, 0))
        for key, group in itertools.groupby(plots, lambda x : x[1].basecalling):
            self.story.append(Paragraph('{:d}.{:d} {}:'.format(section, next(subsection), key.capitalize()), self.heading2_style))
            for plot_file, plot_wildcards in sorted(list(group), key=lambda x : x[1].i):
                im = svg2rlg(plot_file)
                im = Image(im, width=im.width * self.plot_scale, height=im.height * self.plot_scale)
                im.hAlign = 'CENTER'
                self.story.append(im)
                self.story.append(Spacer(1, 0))
        self.story.append(Spacer(1, 0.5*cm)) 
Example #7
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 #8
Source File: genelements.py    From rst2pdf with MIT License 6 votes vote down vote up
def gather_elements(self, client, node, style):
        if isinstance(node.parent, docutils.nodes.sidebar):
            elements = [
                Paragraph(client.gen_pdftext(node), client.styles['sidebar-subtitle'])
            ]
        elif isinstance(node.parent, docutils.nodes.document):
            # elements = [Paragraph(client.gen_pdftext(node),
            # client.styles['subtitle'])]
            # The visible output is now done by the cover template
            elements = []
            # FIXME: looks like subtitles don't have a rawsource like
            # titles do.
            # That means that literals and italics etc in subtitles won't
            # work.
            client.doc_subtitle = getattr(node, 'rawtext', node.astext()).strip()
        else:
            elements = node.elements  # FIXME Can we get here???
        return elements 
Example #9
Source File: pdf_form_display.py    From intake with MIT License 6 votes vote down vote up
def draw_paragraph(self, text, max_width, max_height, style):
        if not text:
            text = ''
        if not isinstance(text, str):
            text = str(text)
        text = text.strip(string.whitespace)
        text = text.replace('\n', "<br/>")
        p = Paragraph(text, style)
        used_width, used_height = p.wrap(max_width, max_height)
        line_widths = p.getActualLineWidths0()
        number_of_lines = len(line_widths)
        if number_of_lines > 1:
            actual_width = used_width
        elif number_of_lines == 1:
            actual_width = min(line_widths)
            used_width, used_height = p.wrap(actual_width + 0.1, max_height)
        else:
            return 0, 0
        p.drawOn(self.canvas, self.cursor.x, self.cursor.y - used_height)
        return used_width, used_height 
Example #10
Source File: gen_cert.py    From edx-certificates with GNU Affero General Public License v3.0 6 votes vote down vote up
def autoscale_text(page, string, max_fontsize, max_leading, max_height, max_width, style):
    """Calculate font size and text placement given some base values

    These values passed by reference are modified in this function, and not passed back:
        - style.fontSize
        - style.leading
    """
    width = max_width + 1
    height = max_height + 1
    fontsize = max_fontsize
    leading = max_leading

    # Loop while size of text bigger than max allowed size as passed through
    while width > max_width or height > max_height:
        style.fontSize = fontsize
        style.leading = leading
        paragraph = Paragraph(string, style)
        width, height = paragraph.wrapOn(page, max_width, max_height)
        fontsize -= 1
        leading -= 1

    return paragraph 
Example #11
Source File: templates.py    From PyInvoice with MIT License 6 votes vote down vote up
def _item_raw_data_and_subtotal(self):
        item_data = []
        item_subtotal = 0

        for item in self._items:
            if not isinstance(item, Item):
                continue

            item_data.append(
                (
                    item.name,
                    Paragraph(item.description, self._defined_styles.get('TableParagraph')),
                    item.units,
                    item.unit_price,
                    item.amount
                )
            )
            item_subtotal += item.amount

        return item_data, item_subtotal 
Example #12
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 #13
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 6 votes vote down vote up
def match_page(self, match_report, match_content):
        if match_content.voicemail:
            voicemail_pref = "Ok to leave voicemail"
        else:
            voicemail_pref = "Not okay to leave voicemail"

        return [
            Paragraph("Matching Report Contents", self.report_title_style),
            Paragraph(
                f"""
                    Perpetrator name given: {match_content.perp_name or "<i>Not available or none provided</i>"}<br />
                    Reported by: {self.get_user_identifier(match_report.report.owner)}<br />
                    Submitted to matching on: {match_report.added.strftime("%Y-%m-%d %H:%M")}<br />
                    Record created: {match_report.report.added.strftime("%Y-%m-%d %H:%M")}<br />
                    <br /><br />
                    Name: {match_content.contact_name or "<i>None provided</i>"}<br />
                    Phone: {match_content.phone}<br />
                    Voicemail preferences: {voicemail_pref}<br />
                    Email: {match_content.email}<br />
                    Notes on preferred contact time of day, gender of admin, etc.:<br />
                """,
                self.body_style,
            ),
            Paragraph(match_content.notes or "None provided", self.notes_style),
        ] 
Example #14
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 #15
Source File: genelements.py    From rst2pdf with MIT License 5 votes vote down vote up
def gather_elements(self, client, node, style):
        return [
            Paragraph(
                client.gather_pdftext(node), style=client.styles['figure-caption'],
            )
        ] 
Example #16
Source File: sphinxnodes.py    From rst2pdf with MIT License 5 votes vote down vote up
def gather_elements(self, client, node, style):
        return [Paragraph(client.gather_pdftext(node), client.styles['centered'])] 
Example #17
Source File: sphinxnodes.py    From rst2pdf with MIT License 5 votes vote down vote up
def gather_elements(self, client, node, style):
        # Need to add ids as targets, found this when using one of the
        # django docs extensions
        targets = [i.replace(' ', '') for i in node['ids']]
        pre = ''
        for i in targets:
            if i not in client.targets:
                pre += '<a name="%s" />' % i
                client.targets.append(i)
        return [Paragraph(pre + client.gather_pdftext(node), style)] 
Example #18
Source File: genelements.py    From rst2pdf with MIT License 5 votes vote down vote up
def gather_elements(self, client, node, style):
        # Sphinx uses a rubric as footnote container
        if (
            self.sphinxmode
            and len(node.children) == 1
            and node.children[0].astext() == 'Footnotes'
        ):
            return []
        else:
            return [Paragraph(client.gather_pdftext(node), client.styles['rubric'])] 
Example #19
Source File: genelements.py    From rst2pdf with MIT License 5 votes vote down vote up
def gather_elements(self, client, node, style):
        return [Paragraph(client.gather_pdftext(node), style)] 
Example #20
Source File: genelements.py    From rst2pdf with MIT License 5 votes vote down vote up
def gather_elements(self, client, node, style):
        return [Paragraph(client.gather_pdftext(node), client.styles['attribution'])] 
Example #21
Source File: pdf.py    From correios with Apache License 2.0 5 votes vote down vote up
def _posting_list_footer(self, pdf, width, x1, y1, x2, y2):
        canvas = pdf.canvas

        canvas.rect(x1, y1, width, 38 * mm)
        canvas.setFont("Helvetica-Bold", size=9)
        canvas.drawCentredString(x2 - (width / 2), y1 + 38 * mm - 10, self.footer_title_text)
        canvas.setFont("Helvetica", size=8)
        canvas.drawString(x1 + 2 * mm, y1 + 28 * mm, self.footer_disclaimer)
        text_width = stringWidth(self.footer_stamp_text, "Helvetica", 8)
        canvas.drawString(x2 - 2 * mm - text_width, y1 + 28 * mm, self.footer_stamp_text)
        text = Paragraph(self.footer_signature_text, style=self.signature_style)
        text.wrap(stringWidth(self.footer_disclaimer, "Helvetica", 8), 10 * mm)
        text.drawOn(canvas, x1 + 2 * mm, y1 + 2 * mm)

    # noinspection PyUnusedLocal 
Example #22
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def cover_page(self):
        return [
            Image(
                os.path.join(settings.BASE_DIR, api.NotificationApi.logo_path),
                3 * inch,
                3 * inch,
            ),
            Spacer(1, 18),
            Paragraph("CONFIDENTIAL", self.headline_style),
            Spacer(1, 30),
            Spacer(1, 40),
            Paragraph(self.title, self.subtitle_style),
            Spacer(1, 40),
            PageBreak(),
        ] 
Example #23
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_pdf_report(self, report_id, recipient):
        # setup
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(
            api.NotificationApi.get_cover_page(report_id=report_id, recipient=recipient)
        )
        self.pdf_elements.extend(self.report_page(self.report))
        self.pdf_elements.append(
            Paragraph("Record Questions", self.section_title_style)
        )
        self.render_questions(self.report_data)

        # teardown
        doc.build(
            self.pdf_elements,
            onFirstPage=self.get_header_footer(recipient),
            onLaterPages=self.get_header_footer(recipient),
            canvasmaker=NumberedCanvas,
        )
        result = report_buffer.getvalue()
        report_buffer.close()
        return result 
Example #24
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def report_page(self, report):
        return [
            Paragraph("Record", self.report_title_style),
            Paragraph("Record Metadata", self.section_title_style),
            Paragraph(
                f"""
                    Record Created: {report.added.strftime("%Y-%m-%d %H:%M")}<br />
                """,
                self.body_style,
            ),
        ] 
Example #25
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_answer_list(self, answers):
        for answer in answers:
            self.pdf_elements.append(Paragraph(answer, self.notes_style))
            self.pdf_elements.append(Spacer(1, 1)) 
Example #26
Source File: report_delivery.py    From callisto-core with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_question(self, question):
        self.pdf_elements.append(Paragraph(question, self.body_style))
        self.pdf_elements.append(Spacer(1, 4)) 
Example #27
Source File: templates.py    From HH---POS-Accounting-and-ERP-Software with MIT License 5 votes vote down vote up
def _build_bottom_tip(self):
        if self._bottom_tip:
            self._story.append(Spacer(5, 5))
            self._story.append(
                Paragraph(
                    self._bottom_tip,
                    ParagraphStyle(
                        'BottomTip',
                        parent=self._defined_styles.get('Normal'),
                        alignment=self._bottom_tip_align
                    )
                )
            ) 
Example #28
Source File: templates.py    From HH---POS-Accounting-and-ERP-Software with MIT License 5 votes vote down vote up
def _build_transactions(self):
        # Transaction
        transaction_table_data = self._transactions_data()

        if transaction_table_data:
            self._story.append(Paragraph('Transaction', self._defined_styles.get('Heading1')))
            self._story.append(TableWithHeader(transaction_table_data, horizontal_align='LEFT')) 
Example #29
Source File: templates.py    From HH---POS-Accounting-and-ERP-Software with MIT License 5 votes vote down vote up
def _build_service_provider_and_client_info(self):
        if isinstance(self.service_provider_info, ServiceProviderInfo) and isinstance(self.client_info, ClientInfo):
            # Merge Table
            table_data = [
                [
                    Paragraph('Service Provider', self._defined_styles.get('Heading1')), '',
                    '',
                    Paragraph('Client', self._defined_styles.get('Heading1')), ''
                ]
            ]
            table_style = [
                ('SPAN', (0, 0), (1, 0)),
                ('SPAN', (3, 0), (4, 0)),
                ('LINEBELOW', (0, 0), (1, 0), 1, colors.gray),
                ('LINEBELOW', (3, 0), (4, 0), 1, colors.gray),
                ('LEFTPADDING', (0, 0), (-1, -1), 0),
            ]
            client_info_data = self._client_info_data()
            service_provider_data = self._service_provider_data()
            diff = abs(len(client_info_data) - len(service_provider_data))
            if diff > 0:
                if len(client_info_data) < len(service_provider_data):
                    client_info_data.extend([["", ""]]*diff)
                else:
                    service_provider_data.extend([["", ""]*diff])
            for d in zip(service_provider_data, client_info_data):
                d[0].append('')
                d[0].extend(d[1])
                table_data.append(d[0])
            self._story.append(
                Table(table_data, style=table_style)
            )
        else:
            self._build_service_provider_info()
            self._build_client_info() 
Example #30
Source File: templates.py    From HH---POS-Accounting-and-ERP-Software with MIT License 5 votes vote down vote up
def _build_client_info(self):
        # ClientInfo
        client_info_data = self._client_info_data()
        if client_info_data:
            self._story.append(Paragraph('Client', self._defined_styles.get('Heading1')))
            self._story.append(SimpleTable(client_info_data, horizontal_align='LEFT'))