Python reportlab.platypus.Table() Examples

The following are 12 code examples of reportlab.platypus.Table(). 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: report.py    From flask-restful-example with MIT License 10 votes vote down vote up
def table_model():
    """
    添加表格
    :return:
    """
    template_path = current_app.config.get("REPORT_TEMPLATES")
    image_path = os.path.join(template_path, 'test.jpg')
    new_img = Image(image_path, width=300, height=300)
    base = [
        [new_img, ""],
        ["大类", "小类"],
        ["WebFramework", "django"],
        ["", "flask"],
        ["", "web.py"],
        ["", "tornado"],
        ["Office", "xlsxwriter"],
        ["", "openpyxl"],
        ["", "xlrd"],
        ["", "xlwt"],
        ["", "python-docx"],
        ["", "docxtpl"],
    ]

    style = [
        # 设置字体
        ('FONTNAME', (0, 0), (-1, -1), 'SimSun'),

        # 合并单元格 (列,行)
        ('SPAN', (0, 0), (1, 0)),
        ('SPAN', (0, 2), (0, 5)),
        ('SPAN', (0, 6), (0, 11)),

        # 单元格背景
        ('BACKGROUND', (0, 1), (1, 1), HexColor('#548DD4')),

        # 字体颜色
        ('TEXTCOLOR', (0, 1), (1, 1), colors.white),
        # 对齐设置
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),

        # 单元格框线
        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
        ('BOX', (0, 0), (-1, -1), 0.5, colors.black),

    ]

    component_table = Table(base, style=style)
    return component_table 
Example #2
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 #3
Source File: pdf.py    From testplan with Apache License 2.0 6 votes vote down vote up
def create_base_tables(data, style, col_widths, max_rows=MAX_TABLE_ROWS):
    """
    Create tables for the specified data and style
    commands, partitioning where necessary.

    :param data: the table data
    :type data: ``list`` of ``list``
    :param style: the style commands
    :type style: ``list`` of ``tuple``
    :param col_widths: column widths for the new tables
    :type col_widths: ``iterable``
    :param max_rows: the maximum number of rows in each table
    :type max_rows: ``int``
    :return: a list of new tables
    :rtype: ``list`` of ``Table``
    """
    zipped = six.moves.zip(
        _partition_data(data, max_rows=max_rows),
        _partition_style(style, len(data), max_rows=max_rows),
    )

    return [
        Table(data=_data, colWidths=col_widths, style=_style)
        for _data, _style in zipped
    ] 
Example #4
Source File: letters.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def add_paragraph(self, text):
        "Add a paragraph (represented as a string) to the letter: used by OfficialLetter.add_letter"
        if text.startswith('||'):
            # it's our table microformat
            lines = text.split('\n')
            cells = [line.split('|')[2:] for line in lines] # [2:] effectively strips the leading '||'
            self.flowables.append(Table(cells, style=self.table_style))
        else:
            [self.flowables.append(Paragraph(line, self.content_style)) for line in text.split("\n")]
        self.flowables.append(Spacer(1, self.line_height)) 
Example #5
Source File: letters.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def _contents(self, memo):
        """
        Produce a list of Flowables to form the body of the memo
        """
        contents = []
        space_height = self.line_height
        # the header block
        contents.append(MemoHead(key='Attention', value=', '.join(self.to_addr_lines), bold=True))
        contents.append(MemoHead(key='From', value=', '.join(self.from_name_lines)))
        contents.append(MemoHead(key='Re', value=self.subject[0]))
        for subjectline in self.subject[1:]:
            contents.append(MemoHead(key='', value=subjectline))
        contents.append(MemoHead(key='Date', value=self.date.strftime('%B %d, %Y').replace(' 0', ' ')))
        contents.append(Spacer(1, 2*space_height))

        # insert each paragraph
        for f in self.flowables:
            contents.append(f)
            #contents.append(Spacer(1, space_height))

        # the CC lines
        if self.cc_lines:
            data = []
            for cc in self.cc_lines:
                data.append(['', Paragraph(cc, self.content_style)])

            cc = Paragraph('cc:', self.content_style)
            data[0][0] = cc

            cc_table = Table(data, colWidths=[0.3 * inch, 5 * inch])
            cc_table.hAlign = "LEFT"
            cc_table.setStyle(TableStyle(
                [('LEFTPADDING', (0, 0), (-1, -1), 0),
                 ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                 ('TOPPADDING', (0, 0), (-1, -1), 0),
                 ('BOTTOMPADDING', (0, 0), (-1, -1), 0)]))

            contents.append(cc_table)
        return contents 
Example #6
Source File: report.py    From nanopype with MIT License 5 votes vote down vote up
def add_summary(self, summary_table=[]):
        self.story.append(Spacer(1, 8*cm))
        self.story.append(Paragraph("Sequencing Report", self.title_style))
        style = self.normal_style
        style.alignment = TA_CENTER
        self.story.append(Paragraph("{}".format(self.tag), style))
        self.story.append(Spacer(1, 4*cm))
        summary_table_style = [('ALIGN',(0,0),(0,-1),'RIGHT'),
                               ('ALIGN',(1,0),(1,-1),'LEFT')]
        if len(summary_table):
            self.story.append(Table(summary_table, style=summary_table_style))
        self.story.append(Spacer(1, 1*cm))
        self.story.append(Paragraph("Nanopype {}".format(self.version), style))
        self.story.append(PageBreak()) 
Example #7
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 #8
Source File: pdf.py    From correios with Apache License 2.0 5 votes vote down vote up
def _posting_list_table(self, canvas, x1, y1, x2, y2, shipping_labels):
        style = self.table_style[:]
        table = [self.table_header]
        for i, shipping_label in enumerate(shipping_labels, start=1):
            row = (
                str(shipping_label.tracking_code),
                str(shipping_label.receiver.zip_code),
                str(shipping_label.package.weight),
                self.yes if ExtraService.get(EXTRA_SERVICE_AR) in shipping_label else self.no,
                self.yes if ExtraService.get(EXTRA_SERVICE_MP) in shipping_label else self.no,
                self.yes if shipping_label.has_declared_value() else self.no,
                str(shipping_label.value).replace(".", ",") if shipping_label.value is not None else "",
                str(shipping_label.invoice_number),
                shipping_label.get_package_sequence(),
                shipping_label.receiver.name[: self.max_receiver_name_size],
            )

            # noinspection PyTypeChecker
            table.append(row)

            if i % 2:
                style.append(("BACKGROUND", (0, i), (-1, i), colors.lightgrey))

        table_flow = Table(table, colWidths=self.col_widths, style=TableStyle(style))
        w, h = table_flow.wrap(0, 0)
        table_flow.drawOn(canvas, x1, y2 - h - 50 * mm) 
Example #9
Source File: report.py    From nanopype with MIT License 4 votes vote down vote up
def add_section_flowcells(self, runnames=[]):
        self.story.append(Paragraph("{:d} Flow cells".format(self.get_section_number()), self.heading_style))
        self.story.append(Spacer(1, 0))
        table_data = [('{:3d}: '.format(i), runname) for i, runname in enumerate(runnames)]
        table_style = [('FONTSIZE', (0,0), (-1, -1), 10),
                        ('BOTTOMPADDING', (0,0), (-1,-1), 1),
                        ('TOPPADDING', (0,0), (-1,-1), 1),
                        ('VALIGN', (0,0), (-1,-1), 'MIDDLE')]
        self.story.append(Table(table_data, style=table_style))
        self.story.append(Spacer(1, 0.5*cm)) 
Example #10
Source File: generatereport.py    From kobo-predict with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def append_answers(self, json_question, instance, sub_count):
        elements = []
        if instance.form_status ==  0:
            form_status = "Pending"
        elif instance.form_status == 1:
            form_status = "Rejected"
        elif instance.form_status == 2:
            form_status = "Flagged"
        elif instance.form_status == 3:
            form_status = "Approved"
        sub_count += 1
        elements.append(Spacer(0,10))
        elements.append(Paragraph("Submision "+ str(sub_count), self.paragraphstyle))
        elements.append(Paragraph("Status : "+form_status, self.paragraphstyle))
        elements.append(Paragraph("Submitted By:"+instance.submitted_by.username, self.paragraphstyle))
        elements.append(Paragraph("Submitted Date:"+str(instance.date), self.paragraphstyle))
        elements.append(Spacer(0,10))
        self.data = []
        self.additional_data=[]
        self.main_answer = instance.instance.json
        question = json.loads(json_question)

        self.parse_individual_questions(question['children'])
        

        t1 = Table(self.data, colWidths=(60*mm, None))
        t1.setStyle(self.ts1)
        elements.append(t1)
        elements.append(Spacer(0,10))

        if self.additional_data:
            elements.append(Paragraph("Full Answers", styles['Heading4']))
            for items in self.additional_data:
                for k,v in items.items():
                    elements.append(Paragraph(k + " : ", styles['Heading5']))
                    elements.append(Paragraph(v, self.paragraphstyle))
                    elements.append(Spacer(0,10))
        return elements 
Example #11
Source File: pdf.py    From testplan with Apache License 2.0 4 votes vote down vote up
def _create_sub_table(
    columns,
    rows,
    column_start,
    column_end,
    style,
    row_indices=None,
    colour_matrix=None,
):
    """
    Create ReportLab table from a subsection of the columns and rows data using
    the column_start and column_end indices. Row indices may be added to the
    sub table if provided.

    :param columns: List of the column names, maintains the display order.
    :type columns: ``list`` of ``str``
    :param rows: List of lists containing row data.
    :type rows: ``list`` of ``list``
    :param column_start: The index of the first column to be included.
    :type column_start: ``int``
    :param column_end: The index of the last column to be included.
    :type column_end: ``int``
    :param style: The style of the ReportLab table.
    :type style: ``list`` of ``tuple``
    :param row_indices: List of row indices for each row in the table.
    :type row_indices: ``list`` of ``int``
    :param colour_matrix: A matrix listing whether each cell has passed (P),
                          failed (F) or ignored (I) which will result in the
                          cell text being green, red or black respectively. If
                          no matrix is passed all cells will be black.
    :type colour_matrix: ``list`` of ``list``
    :return: The formatted ReportLab table.
    :rtype: ``list``
    """
    # Select subsection of columns and rows.
    sub_columns = columns[column_start:column_end]
    sub_rows = [row[column_start:column_end] for row in rows]

    # If needed add row indices.
    if row_indices:
        sub_columns, sub_rows = _add_row_index(
            columns=sub_columns, rows=sub_rows, indices=row_indices
        )

    # Create the table and set it's style.
    table = Table([sub_columns] + sub_rows)

    if colour_matrix:
        colour_matrix = [row[column_start:column_end] for row in colour_matrix]
        cell_styles = _create_cell_styles(
            colour_matrix=colour_matrix, display_index=bool(row_indices)
        )
        style.extend(format_table_style(cell_styles))
    table.setStyle(style)

    return table 
Example #12
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)