Exemple #1
0
    def create_intro(self):
        self.elements += [
            pdf.Spacer(0, 0.25 * inch),
            pdf.Paragraph(self.crawler.novel_title or 'N/A',
                          style=self.styles['Title']),
            pdf.Spacer(0, 0.1 * inch),
            pdf.Table(
                [[self.crawler.novel_author or 'N/A']],
                style=pdf.TableStyle([
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('SIZE', (0, 0), (-1, -1), 12),
                ]),
            ),
            pdf.Spacer(0, 0.5 * inch),
        ]

        if self.app.book_cover:
            self.elements += [pdf.Image(self.app.book_cover, height=5 * inch)]
        else:
            self.elements += [pdf.Spacer(0, 5 * inch)]
        # end if

        self.elements += [
            pdf.Spacer(0, 0.5 * inch),
            pdf.Table(
                [['Generated by <Lightnovel Crawler>'],
                 ['https://github.com/dipu-bd/lightnovel-crawler']],
                style=pdf.TableStyle([
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ]),
            ),
        ]
        self.elements += [pdf.PageBreak()]
    def _make_figure_table(image_files):
        # Add the images to a list of lists
        cols = 2
        table = []
        row = []
        for (i, fn) in enumerate(image_files):
            row.append(p.Image(fn, 3.4 * u.inch, 3.0 * u.inch))
            if (i % cols) == (cols - 1):
                table.append(row)
                row = []

        # Determine if there are any images left to print
        if len(row) != 0:
            for i in range(len(row), cols):
                row.append(p.Paragraph('', styles['body_style']))
            table.append(row)

        # Style this into a reportlab table and add to the story
        width = 3.75 * u.inch
        t = p.Table(table, colWidths=[width, width])
        t.setStyle(
            p.TableStyle([
                ('ALIGNMENT', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('TOPPADDING', (0, 0), (-1, -1), 6.0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6.0),
            ]))
        return t
Exemple #3
0
 def make_rating(self, label, val):
     """Make a pretty representation of our rating.
     """
     try:
         assert (type(val) == int)
     except:
         raise TypeError("Rating %s is not an integer" % val)
     i = FiveStars(10, filled=(val / 2.0))  # 12 point
     lwidth = len(label + ': ') * 4  # A very cheap approximation of width
     t = platypus.Table(
         [[label + ': ', i]],
         colWidths=[lwidth, inch],
     )
     t.hAlign = 'LEFT'
     t.setStyle(
         platypus.TableStyle([
             ('LEFTPADDING', (0, 0), (-1, 0), 0),
             ('LEFTPADDING', (1, 0), (1, 0), 6),
             ('TOPPADDING', (0, 0), (-1, -1), 0),
             ('ALIGNMENT', (1, 0), (1, 0), 'LEFT'),
             ('VALIGN', (0, 0), (0, 0), 'TOP'),
             # for debugging
             #('INNERGRID',(0,0),(-1,-1),.25,colors.black),
             #('BOX',(0,0),(-1,-1),.25,colors.black),
         ]))
     return t
Exemple #4
0
 def pdf_elements(self):
     # layout
     grid = [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
             ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
             ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
             ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold')]
     # typeset some rows in bold
     for i in range(len(self.entries)):
         e = self.entries[i]
         if not 'bold' in e:
             continue
         if not 'indent' in e:
             grid.append(
                 ('FONTNAME', (0, i + 1), (-1, i + 1), 'Helvetica-Bold'))
         elif e['indent'] == 1:
             grid.append(('FONTNAME', (0, i + 1), (-1, i + 1),
                          'Helvetica-BoldOblique'))
         elif e['indent'] >= 2:
             grid.append(
                 ('FONTNAME', (0, i + 1), (-1, i + 1), 'Helvetica-Oblique'))
     # build list of 'Flowable' objects
     elements = []
     elements.append(pl.Spacer(1, 0.8 * inch))
     t = pl.Table([self.headings] + self.data)
     t.setStyle(pl.TableStyle(grid))
     elements.append(t)
     return elements
Exemple #5
0
 def getTableEl(self, tableRowEntriesList):
     data = []
     for tableRowData in tableRowEntriesList:
         data.append(tableRowData)
     t = platypus.Table(data)
     ts = platypus.TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica', 8)])
     t.setStyle(ts)
     return t
Exemple #6
0
def print_employees_badges(dao):
    global header_text
    global sub_header_text

    header_text = ""
    sub_header_text = _("Employees badges")
    s = ParagraphStyle(name="zou", fontName='Helvetica', alignment=TA_CENTER)

    badges_per_line = 3
    array = []
    row = []

    employees = dao.employee_dao.all()

    if len(employees) == 0:
        return

    i = 0
    for employee in employees:
        row.append([
            Paragraph(employee.fullname, s),
            platypus.Spacer(0, 0.25 * cm),
            createBarcodeDrawing('EAN13',
                                 value=str(
                                     BarCodeIdentifier.code_for(employee)),
                                 barHeight=1 * cm)
        ])
        i = i + 1
        if i == badges_per_line:
            array.append(row)
            row = []
            i = 0
    if i > 0:
        array.append(row)

    t = platypus.Table(array,
                       repeatRows=0,
                       colWidths=[6 * cm] * badges_per_line,
                       rowHeights=[3 * cm] *
                       len(array))  # Repeat the table header

    ts = platypus.TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica', 8)])
    ts.add('ALIGN', (0, 0), (-1, -1), 'CENTER')
    ts.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE')

    ts.add("LEFTPADDING", (0, 0), (-1, -1), 0)
    ts.add("RIGHTPADDING", (0, 0), (-1, -1), 0)
    ts.add('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)
    ts.add('BOX', (0, 0), (-1, -1), 0.25, colors.black)

    t.setStyle(ts)
    complete_document = []
    complete_document.append(t)

    filename = make_pdf_filename("EmployeeBadges")
    ladderDoc = start_PDF(filename)
    ladderDoc.build(complete_document, canvasmaker=NumberedCanvas)
    open_pdf(filename)
Exemple #7
0
def _build_report():
    stylesheet = getSampleStyleSheet()
    builder = [
        platypus.Paragraph("Report document", stylesheet["Heading1"]),
        platypus.Paragraph(to_paragraph(HEADER), stylesheet["Normal"]),
    ]

    for scan_prefix, scan_info in results.items():
        excel_filename = f"{scan_prefix}.xlsx"
        workbook = openpyxl.load_workbook(excel_filename)
        df = pd.read_excel(excel_filename, engine="openpyxl")
        df = df[list(table_fields)]

        for attr, col_info in table_fields.items():
            precision = col_info.get("precision")
            if precision is not None:
                col = getattr(df, attr)
                setattr(df, attr, [f"%.{precision}f" % item for item in col])

        style = platypus.TableStyle([
            ("FACE", (0, 0), (-1, 0), "Times-Bold"),
            ("ALIGN", (0, 0), (-1, 0), "CENTER"),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("ALIGN", (1, 0), (-1, -1), "RIGHT"),
        ])

        header = [
            col_info.get("label", attr)
            for attr, col_info in table_fields.items()
        ]
        table = platypus.Table([header] + np.array(df).tolist(), repeatRows=1)
        table.setStyle(style)
        plot = platypus.Image(f"{scan_prefix}.png")
        plot.drawWidth = 8.0 * units.inch
        plot.drawHeight = 6.67 * units.inch
        builder.extend([
            platypus.Paragraph(scan_info["title"], stylesheet["Heading1"]),
            platypus.Paragraph(
                f"Data generated: {workbook.properties.created}",
                stylesheet["Normal"],
            ),
            platypus.Paragraph(to_paragraph(scan_info["info"]),
                               stylesheet["Normal"]),
            platypus.Paragraph("Scan Information", stylesheet["Heading2"]),
            platypus.Paragraph(to_paragraph(SCAN_INFO), stylesheet["Normal"]),
            platypus.PageBreakIfNotEmpty(),
            plot,
            platypus.Paragraph("Plot / Table Information",
                               stylesheet["Heading2"]),
            platypus.Paragraph(to_paragraph(PLOT_INFO), stylesheet["Normal"]),
            platypus.Paragraph(f"{scan_info['title']}: Scan Data Table",
                               stylesheet["Heading2"]),
            table,
            platypus.PageBreakIfNotEmpty(),
        ])

    return builder
Exemple #8
0
 def getDefListEls(self, listDict):
     # The Table in ReportLab tends to look better than a list for defining
     #  this stuff.
     data = []
     for spec, value in listDict.iteritems():
         data.append([spec, value])
     t = platypus.Table(data)
     ts = platypus.TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica', 8)])
     t.setStyle(ts)
     t.hAlign = 'LEFT'
     return [t]
Exemple #9
0
 def add_table(self, rows, column_sizes, style=[]):
     real_style = platypus.TableStyle([
         ("GRID", (0, 0), (-1, -1), 0.8, (0, 0, 0)),
         ("BACKGROUND", (0, 0), (-1, 0), (0.8471, 0.8941, 0.7373)),
     ] + style)
     sizes = [s * mm for s in column_sizes]
     self.story.extend([
         platypus.Spacer(1, 3 * mm),
         platypus.Table(rows, colWidths=sizes, style=real_style),
         platypus.Spacer(1, 3 * mm),
     ])
Exemple #10
0
def make_pdf_table(df: pd.DataFrame):
    """Формирует и форматирует pdf-таблицу доходности портфеля и индекса."""
    list_of_lists_table = make_list_of_lists_table(df)
    style = platypus.TableStyle([
        ("LINEBEFORE", (1, 0), (1, -1), LINE_WIDTH, LINE_COLOR),
        ("LINEABOVE", (0, 1), (-1, 2), LINE_WIDTH, LINE_COLOR),
        ("ALIGN", (1, 1), (-1, -1), "RIGHT"),
        ("ALIGN", (0, 0), (-1, 0), "CENTRE"),
    ])
    table = platypus.Table(list_of_lists_table, style=style)
    table.hAlign = "LEFT"
    return table
Exemple #11
0
def make_pdf_dividends(df: pd.DataFrame):
    """Формирует и форматирует pdf таблицу с дивидендными выплатами"""
    data = make_list_of_lists_dividends(df)
    style = platypus.TableStyle([
        ("LINEBEFORE", (1, 0), (1, -1), LINE_WIDTH, LINE_COLOR),
        ("LINEABOVE", (0, 1), (-1, 2), LINE_WIDTH, LINE_COLOR),
        ("ALIGN", (1, 1), (-1, -1), "RIGHT"),
        ("ALIGN", (0, 0), (0, -1), "CENTRE"),
    ])
    table = platypus.Table(data=data, style=style)
    table.hAlign = "LEFT"
    return table
Exemple #12
0
    def add_table(self, header_table, table, column_widths, formats):
        def array_join(array, spacer=None):
            if not array:
                return array
            else:
                r = [array[0]]
                for i in range(1, len(array)):
                    r.append(spacer)
                    r.append(array[i])
                return r

        platypus_table = []

        header = array_join(header_table, '')
        #print(header)
        platypus_table.append(header)

        for t_row in table:
            i = 0
            row = []
            for cell in t_row:
                # print(cell)
                # print(formats[i].format(cell))
                row.append(formats[i].format(cell))
                i += 1
            #print(row)
            platypus_table.append(array_join(row, ''))

        col_widths = array_join(column_widths, 0.2 * cm)

        t = MyTable(platypus_table, repeatRows=1,
                    colWidths=col_widths)  # Repeat the table header
        t.spaceAfter = 1 * cm

        ts = platypus.TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica-Bold',
                                   12)])
        ts.add('ALIGN', (0, 0), (-1, -1), 'LEFT')
        ts.add('VALIGN', (0, 0), (-1, -1), 'TOP')

        ts.add("LEFTPADDING", (0, 0), (-1, -1), 0)
        ts.add("RIGHTPADDING", (0, 0), (-1, -1), 0)

        # This is the header row

        for i in range(len(header_table)):
            ts.add('LINEBELOW', (2 * i, 0), (2 * i, 0), 0.5, colors.black)
        ts.add('VALIGN', (0, 0), (-1, 0), 'MIDDLE')

        # for row in titles_row:
        #     ts.add('FONT', (0, row), (-1, row), 'Helvetica', 10)

        t.setStyle(ts)
        self.complete_document.append(t)
Exemple #13
0
 def getSimpleDataTableEl(self, headerEntries, dataEntries):
     data = []
     data.append(headerEntries)
     for tableRowData in dataEntries:
         data.append(tableRowData)
     t = platypus.Table(data)
     tStyle = platypus.TableStyle([
         ('BOX', (0, 0), (-1, -1), 1, colors.black),
         ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
         ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold')
     ])
     t.setStyle(tStyle)
     return t
 def _make_title(title_str):
     para = p.Paragraph(title_str, styles['section_style'])
     t = p.Table([[para]], colWidths=[7.5 * u.inch])
     t.setStyle(
         p.TableStyle([
             ('TOPPADDING', (0, 0), (-1, -1), 6),
             ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
             ('BACKGROUND', (0, 0), (-1, -1), '#957348'),
             ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'),
             ('VALIGN', (0, 0), (-1, -1), 'TOP'),
             ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
         ]))
     return t
Exemple #15
0
def make_pdf_table(portfolio: Portfolio):
    """Создает и форматирует pdf-таблицу."""
    data = make_list_of_lists_table(portfolio)
    style = platypus.TableStyle([
        ("LINEBEFORE", (1, 0), (1, -1), LINE_WIDTH, LINE_COLOR),
        ("LINEABOVE", (0, 1), (-1, 1), LINE_WIDTH, LINE_COLOR),
        ("LINEABOVE", (0, -1), (-1, -1), LINE_WIDTH, LINE_COLOR),
        ("ALIGN", (-2, 1), (-1, -1), "RIGHT"),
        ("ALIGN", (0, 0), (-1, 0), "CENTRE"),
        ("FONTNAME", (0, -1), (-1, -1), BOLD_FONT),
    ])
    table = platypus.Table(data=data, style=style)
    table.hAlign = "LEFT"
    return table
Exemple #16
0
def make_pdf_table(df: pd.DataFrame) -> platypus.Table:
    """Формирует и форматирует pdf-таблицу доходности портфеля и индекса."""
    list_of_lists_table = make_list_of_lists_table(df)
    style = platypus.TableStyle(
        [
            ("LINEBEFORE", *_SECOND_COLUMN, LINE_WIDTH, LINE_COLOR),
            ("LINEABOVE", *_SECOND_AND_THIRD_ROW, LINE_WIDTH, LINE_COLOR),
            ("ALIGN", *_SECOND_TO_LAST_COLUMN, "RIGHT"),
            ("ALIGN", *_FIRST_COLUMN, "CENTRE"),
        ],
    )
    table = platypus.Table(list_of_lists_table, style=style)
    table.hAlign = "LEFT"

    return table
Exemple #17
0
def simple_gen_testpage(fname):
    """Generate a simple test page"""
    # NOTE: this example taken from
    # https://www.blog.pythonlibrary.org/2010/09/21/reportlab-tables-creating-tables-in-pdfs-with-python/
    doc = plat.SimpleDocTemplate(fname, pagesize=letter)
    elements = []
    data = [['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'],
            ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']]
    t = plat.Table(data)
    t.setStyle(
        plat.TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green),
                         ('TEXTCOLOR', (0, 0), (1, -1), colors.red)]))
    elements.append(t)
    # write the document to disk
    doc.build(elements)
Exemple #18
0
 def write_attr_foot (self):
     # If we have 3 or fewer attributes and no images, we don't
     # need a table
     if len(self.attributes)<=3 and not hasattr(self,'image'):
         self.txt.extend(self.attributes)
         return
     if not self.attributes and hasattr(self,'image'):
         # If we only have an image...
         self.txt.append(self.image)
         return
     elif hasattr(self,'image') and self.image.drawWidth > (self.doc.frame_width / 2.25):
         self.txt.append(self.image)
         self.txt.extend(self.attributes)
         return
     # Otherwise, we're going to make a table...
     if hasattr(self,'image'):
         # If we have an image, we put attributes on the
         # left, image on the right
         table_data = [
             [# 1 row
             # column 1 = attributes
             self.attributes,
             # column 2 = image
             self.image
             ],
             # End of "table"
             ]
     else:
         nattributes = len(self.attributes)
         first_col_size = nattributes//2 + nattributes % 2
         first = self.attributes[:first_col_size]
         second = self.attributes[first_col_size:]
         table_data = []
         for n,left in enumerate(first):
             right = len(second)>n and second[n] or ''
             table_data.append([left,right])
     t = platypus.Table(table_data)
     t.setStyle(
         platypus.TableStyle([
         ('VALIGN',(0,0),(0,-1),'TOP'),
         ('LEFTPADDING',(0,0),(0,-1),0),
         # for debugging
         #('INNERGRID',(0,0),(-1,-1),.25,colors.red),
         #('BOX',(0,0),(-1,-1),.25,colors.red),
         ]
                             )
         )
     self.txt.append(t)
Exemple #19
0
def make_operation_boxes(operation_ndx, op, opNumberStyle):
    s = ParagraphStyle(name = "zou", fontName = 'Helvetica', fontSize=12) #, borderWidth=1, borderColor=colors.black)
    centered = ParagraphStyle(name = "zou", fontName = 'Helvetica-bold', fontSize=14) #, borderWidth=1, borderColor=colors.black) alignment=TA_CENTER,

    operation_number = Paragraph("{}".format(operation_ndx), opNumberStyle)

    if op.operation_model and op.operation_model.description:
        model = Paragraph(op.operation_model.short_id,centered) # short_id / description
    else:
        model = None

    if op.operation_model and op.operation_model.imputable:
        code = BarCodeIdentifier.code_for(op)
        # humanReadable : remove the numbers under the barcode
        barcode = createBarcodeDrawing('EAN13',value=str(code),width=4*cm,barHeight=1*cm,humanReadable=False)
        mainlog.debug("Barcode for {} is {}".format(op, code))
        #graphic = GraphicalAnnotation(code,1*cm)
    else:
        barcode = None
        graphic = None

    full_desc = ""
    if op.description:
        # full_desc = u"<b>{}</b>".format(crlf_to_br(op.description))
        assignee = ''
        if op.assignee:
            assignee = op.assignee.fullname
        full_desc = u"<b>{}</b><br/>{}".format(escape_html(op.description), escape_html(assignee))
    else:
        full_desc = "---"

    data_ops = [[operation_number,
                 barcode,
                 model,
                 Paragraph(full_desc,s)]]
    t = platypus.Table(data_ops, repeatRows=0, colWidths=compute_strut( [1.5*cm, 4.5*cm, 1.5*cm, None], 19.5*cm) )
    ts = platypus.TableStyle()

    # ts.add('LINEABOVE', (0, len(data_ops)-1), (-1, len(data_ops)-1), 0.5, colors.black)
    ts.add('GRID',(0,0),(-1,-1),0.5,colors.black)
    ts.add('LINEBEFORE', (0, 0), (0, -1), 1, colors.black)
    ts.add('LINEAFTER', (-1, 0), (-1, -1), 1, colors.black)
    ts.add('LINEABOVE', (0, 0), (-1, 0), 1, colors.black)
    ts.add('LINEBELOW', (0, 0), (-1, 0), 0, colors.white)
    ts.add('VALIGN', (2, 0), (-1, -1), 'TOP')
    t.setStyle(ts)

    return t
Exemple #20
0
 def write_ingfoot(self):
     # Ugly -- we know that heads comprise two elements -- a
     # condbreak and a head...
     ings = self.txt[2:]
     if len(ings) > 4:
         half = (len(ings) / 2)
         first_half = ings[:-half]
         second_half = ings[-half:]
         t = platypus.Table([[first_half, second_half]])
         t.hAlign = 'LEFT'
         t.setStyle(
             platypus.TableStyle([
                 ('VALIGN', (0, 0), (1, 0), 'TOP'),
             ]))
         self.txt = self.txt[:2] + [t]
     self.txt = self.save_txt + [platypus.KeepTogether(self.txt)]
Exemple #21
0
    def QuickReport(conn, fileName, *args, **kwargs):
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib.units import inch

        styles = getSampleStyleSheet()
        title = 'Db Report'
        if 'title' in kwargs:
            title = kwargs['title']
            del kwargs['title']

        names = [x.upper() for x in conn.GetColumnNames()]
        try:
            smiCol = names.index('SMILES')
        except ValueError:
            try:
                smiCol = names.index('SMI')
            except ValueError:
                smiCol = -1
        if smiCol > -1:
            if hasCDX:
                tform = CDXImageTransformer(smiCol)
            elif 1:
                tform = ReportLabImageTransformer(smiCol)
            else:
                tform = CactvsImageTransformer(smiCol)

        else:
            tform = None
        kwargs['transform'] = tform
        tbl = conn.GetReportlabTable(*args, **kwargs)
        tbl.setStyle(
            platypus.TableStyle([
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
                ('FONT', (0, 0), (-1, -1), 'Times-Roman', 8),
            ]))

        if smiCol > -1 and tform:
            tbl._argW[smiCol] = tform.width * 1.2
        elements = [tbl]
        reportTemplate = PDFReport()
        reportTemplate.pageHeader = title

        doc = platypus.SimpleDocTemplate(fileName)
        doc.build(elements,
                  onFirstPage=reportTemplate.onPage,
                  onLaterPages=reportTemplate.onPage)
Exemple #22
0
def append_header_block(complete_document, title, ddate):
    # Header frame

    data_ops = [[
        Paragraph(title, header_fnt),
        Paragraph(date_to_dmy(ddate, full_month=True), header_small_fnt)
    ]]

    t = MyTable(data_ops, colWidths=[A4[0] - 5 * cm - 2 * cm, 5 * cm])
    t.spaceAfter = 1 * cm

    ts = platypus.TableStyle([('BACKGROUND', (0, 0), (-1, -1),
                               colors.Color(0.8, 0.8, 0.8))])
    ts.add('BOX', (0, 0), (-1, -1), 1, colors.black)
    ts.add('ALIGN', (0, 0), (0, 0), 'LEFT')
    ts.add('ALIGN', (1, 0), (1, 0), 'RIGHT')
    t.setStyle(ts)
    complete_document.append(t)
Exemple #23
0
def make_pdf_flow(df: pd.DataFrame):
    """Формирует и форматирует pdf таблицу движения средств."""
    data = make_list_of_lists_flow(df)
    style = platypus.TableStyle([
        ("LINEBEFORE", (1, 0), (1, -1), LINE_WIDTH, LINE_COLOR),
        ("LINEBEFORE", (-1, 0), (-1, -1), LINE_WIDTH, LINE_COLOR),
        ("LINEABOVE", (0, 1), (-1, 1), LINE_WIDTH, LINE_COLOR),
        ("LINEABOVE", (0, 3), (-1, 3), LINE_WIDTH, LINE_COLOR),
        ("LINEABOVE", (0, 5), (-1, 6), LINE_WIDTH, LINE_COLOR),
        ("ALIGN", (1, 1), (-1, -1), "RIGHT"),
        ("ALIGN", (0, 0), (-1, 0), "CENTRE"),
        ("ALIGN", (0, 2), (0, 2), "CENTRE"),
        ("ALIGN", (0, 4), (0, 4), "CENTRE"),
        ("ALIGN", (0, -1), (0, -1), "CENTRE"),
    ])
    table = platypus.Table(data, style=style)
    table.hAlign = "LEFT"
    return table
Exemple #24
0
def make_quality_boxes():
    data_ops = [["Stop",
                 "Element",
                 "Q. acc",
                 "Q. ref",
                 "Visa 2" ],
                [None,None,None,None,None]]
    t = platypus.Table(data_ops, repeatRows=0, colWidths=compute_strut( [3*cm,None,3*cm,3*cm,3*cm], 19.5*cm) )
    ts = platypus.TableStyle()
    ts.add('GRID',(0,0),(-1,-1),0.5,colors.black)
    # ts.add('VALIGN', (0, 0), (-1, -1), 'TOP')
    ts.add('ALIGN', (0, 0), (-1, -1), 'LEFT')
    ts.add('LEADING', (0, 1), (-1, -1), 1.5*cm) # Sets the row height

    ts.add('LINEBEFORE', (0, 0), (0, -1), 1, colors.black)
    ts.add('LINEAFTER', (-1, 0), (-1, -1), 1, colors.black)

    t.setStyle(ts)

    return t
    def _create_story(self):

        # Set up an empty list to hold the story
        story = []

        # Import the report styles
        styles = report_styles.get_report_styles()

        # Create a page break
        story = self._make_page_break(story, self.PORTRAIT)

        # Section title
        title_str = '<strong>References</strong>'
        para = p.Paragraph(title_str, styles['section_style'])
        t = p.Table([[para]], colWidths=[7.5 * u.inch])
        t.setStyle(
            p.TableStyle([
                ('TOPPADDING', (0, 0), (-1, -1), 6),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
                ('BACKGROUND', (0, 0), (-1, -1), '#957348'),
                ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
            ]))
        story.append(t)
        story.append(p.Spacer(0, 0.1 * u.inch))

        # List of references used
        references = [
            '''
            Cohen, J. 1960. "A coefficient of agreement for
            nominal scales." Educational and Psychological Measurement
            20: 37-46.
            ''',
            '''
            Kennedy, RE, Z Yang and WB Cohen. 2010. "Detecting trends
            in forest disturbance and recovery using yearly Landsat
            time series: 1. Landtrendr -- Temporal segmentation
            algorithms." Remote Sensing of Environment 114(2010): 
            2897-2910.
            ''',
            '''
            Ohmann, JL, MJ Gregory and HM Roberts. 2014 (in press). "Scale
            considerations for integrating forest inventory plot data and
            satellite image data for regional forest mapping." Remote
            Sensing of Environment.
            ''',
            '''
            O'Neil, TA, KA Bettinger, M Vander Heyden, BG Marcot, C Barrett,
            TK Mellen, WM Vanderhaegen, DH Johnson, PJ Doran, L Wunder, and
            KM Boula. 2001. "Structural conditions and habitat elements of
            Oregon and Washington. Pages 115-139 in: Johnson, DH and TA
            O'Neil, editors. 2001. "Wildlife-habitat relationships in Oregon
            and Washington." Oregon State University Press, Corvallis, OR.
            ''',
        ]

        # Print all references
        for reference in references:
            para = p.Paragraph(reference, styles['body_style'])
            story.append(para)
            story.append(p.Spacer(0, 0.10 * u.inch))

        # Return this story
        return story
    def _create_story(self, scatter_files):

        # Set up an empty list to hold the story
        story = []

        # Import the report styles
        styles = report_styles.get_report_styles()

        # Create a page break
        story = self._make_page_break(story, self.PORTRAIT)

        # Section title
        title_str = '<strong>Local-Scale Accuracy Assessment: '
        title_str += 'Scatterplots of Observed vs. Predicted '
        title_str += 'Values for Continuous Variables at '
        title_str += 'Plot Locations</strong>'

        para = p.Paragraph(title_str, styles['section_style'])
        t = p.Table([[para]], colWidths=[7.5 * u.inch])
        t.setStyle(
            p.TableStyle([
                ('TOPPADDING', (0, 0), (-1, -1), 6),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
                ('BACKGROUND', (0, 0), (-1, -1), '#957348'),
                ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
            ]))
        story.append(t)
        story.append(p.Spacer(0, 0.2 * u.inch))

        # Scatter explanation
        scatter_str = '''
            These scatterplots compare the observed plot values against
            predicted (modeled) values for each plot used in the GNN model.
            We use a modified leave-one-out (LOO) approach.  In traditional
            LOO accuracy assessment, a model is run with <i>n</i>-1
            plots and then accuracy is determined at the plot left out of
            modeling, for all plots used in modeling.  Because of computing
            limitations, we use a 'second-nearest-neighbor' approach.  We
            develop our models with all plots, but in determining accuracy, we
            don't allow a plot to assign itself as a neighbor at the plot
            location.  This yields similar accuracy assessment results as
            a true cross-validation approach, but probably slightly
            underestimates the true accuracy of the distributed
            (first-nearest-neighbor) map.<br/><br/>
            The observed value comes directly from the plot data,
            whereas the predicted value comes from the GNN prediction
            for the plot location.  The GNN prediction is the mean of
            pixel values for a window that approximates the
            field plot configuration.<br/><br/>
            The correlation coefficients, normalized Root Mean Squared
            Errors (RMSE), and coefficients of determination (R-square) are
            given. The RMSE is normalized by dividing the RMSE by the
            observed mean value.
        '''

        para = p.Paragraph(scatter_str, styles['body_style'])
        story.append(para)
        story.append(p.Spacer(0, 0.1 * u.inch))

        # Add the scatterplot images to a list of lists
        table_cols = 2
        scatter_table = []
        scatter_row = []
        for (i, fn) in enumerate(scatter_files):
            scatter_row.append(p.Image(fn, 3.4 * u.inch, 3.0 * u.inch))
            if (i % table_cols) == (table_cols - 1):
                scatter_table.append(scatter_row)
                scatter_row = []

        # Determine if there are any scatterplots left to print
        if len(scatter_row) != 0:
            for i in range(len(scatter_row), table_cols):
                scatter_row.append(p.Paragraph('', styles['body_style']))
            scatter_table.append(scatter_row)

        # Style this into a reportlab table and add to the story
        width = 3.75 * u.inch
        t = p.Table(scatter_table, colWidths=[width, width])
        t.setStyle(
            p.TableStyle([
                ('ALIGNMENT', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('TOPPADDING', (0, 0), (-1, -1), 6.0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6.0),
            ]))
        story.append(t)

        # Return this story
        return story
def getExamples():
    """Returns all the example flowable objects"""
    styleSheet = getSampleStyleSheet()

    story = []

    #make a style with indents and spacing
    sty = ParagraphStyle('obvious', None)
    sty.leftIndent = 18
    sty.rightIndent = 18
    sty.firstLineIndent = 18
    sty.spaceBefore = 6
    sty.spaceAfter = 6
    story.append(
        Paragraph(
            """Now for some demo stuff - we need some on this page,
        even before we explain the concepts fully""", styleSheet['BodyText']))
    p = Paragraph(
        """
        Platypus is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.""",
        sty)

    p.debug = 1  #show me the borders
    story.append(p)

    story.append(
        Paragraph(
            """Same but with justification 1.5 extra leading and green text.""",
            styleSheet['BodyText']))
    p = Paragraph(
        """
        <para align=justify leading="+1.5" fg=green><font color=red>Platypus</font> is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.</para>""",
        sty)

    p.debug = 1  #show me the borders
    story.append(p)

    story.append(
        platypus.XBox(4 * inch, 0.75 * inch,
                      'This is a box with a fixed size'))

    story.append(
        Paragraph(
            """
        All of this is being drawn within a text frame which was defined
        on the page.  This frame is in 'debug' mode so you can see the border,
        and also see the margins which it reserves.  A frame does not have
        to have margins, but they have been set to 6 points each to create
        a little space around the contents.
        """, styleSheet['BodyText']))

    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 2
    #######################################################################

    story.append(
        Paragraph(
            """
        Here's the base class for Flowable...
        """, styleSheet['Italic']))

    code = '''class Flowable:
        """Abstract base class for things to be drawn.  Key concepts:
    1. It knows its size
    2. It draws in its own coordinate system (this requires the
        base API to provide a translate() function.
        """
    def __init__(self):
        self.width = 0
        self.height = 0
        self.wrapped = 0

    def drawOn(self, canvas, x, y):
        "Tell it to draw itself on the canvas.  Do not override"
        self.canv = canvas
        self.canv.saveState()
        self.canv.translate(x, y)

        self.draw()   #this is the bit you overload

        self.canv.restoreState()
        del self.canv

    def wrap(self, availWidth, availHeight):
        """This will be called by the enclosing frame before objects
        are asked their size, drawn or whatever.  It returns the
        size actually used."""
        return (self.width, self.height)
    '''

    story.append(Preformatted(code, styleSheet['Code'], dedent=4))
    story.append(FrameBreak())
    #######################################################################
    #     Examples Page 3
    #######################################################################

    story.append(
        Paragraph("Here are some examples of the remaining objects above.",
                  styleSheet['Italic']))

    story.append(
        Paragraph("This is a bullet point",
                  styleSheet['Bullet'],
                  bulletText='O'))
    story.append(
        Paragraph("Another bullet point", styleSheet['Bullet'],
                  bulletText='O'))

    story.append(
        Paragraph(
            """Here is a Table, which takes all kinds of formatting options...""",
            styleSheet['Italic']))
    story.append(platypus.Spacer(0, 12))

    g = platypus.Table(
        (('', 'North', 'South', 'East', 'West'),
         ('Quarter 1', 100, 200, 300, 400), ('Quarter 2', 100, 200, 300, 400),
         ('Total', 200, 400, 600, 800)), (72, 36, 36, 36, 36),
        (24, 16, 16, 18))
    style = platypus.TableStyle([
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('ALIGN', (0, 0), (-1, 0), 'CENTRE'),
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black),
        ('LINEBELOW', (1, -1), (-1, -1), 2, (0.5, 0.5, 0.5)),
        ('TEXTCOLOR', (0, 1), (0, -1), colors.black),
        ('BACKGROUND', (0, 0), (-1, 0), (0, 0.7, 0.7))
    ])
    g.setStyle(style)
    story.append(g)
    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 4 - custom fonts
    #######################################################################
    # custom font with LettError-Robot font
    import reportlab.rl_config
    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    from reportlab.pdfbase import pdfmetrics
    fontDir = os.path.join(_RL_DIR, 'fonts')
    face = pdfmetrics.EmbeddedType1Face(
        os.path.join(fontDir, 'DarkGardenMK.afm'),
        os.path.join(fontDir, 'DarkGardenMK.pfb'))
    faceName = face.name  # should be 'DarkGardenMK'
    pdfmetrics.registerTypeFace(face)
    font = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(font)

    # put it inside a paragraph.
    story.append(
        Paragraph(
            """This is an ordinary paragraph, which happens to contain
        text in an embedded font:
        <font name="DarkGardenMK">DarkGardenMK</font>.
        Now for the real challenge...""", styleSheet['Normal']))

    styRobot = ParagraphStyle('Robot', styleSheet['Normal'])
    styRobot.fontSize = 16
    styRobot.leading = 20
    styRobot.fontName = 'DarkGardenMK'

    story.append(
        Paragraph("This whole paragraph is 16-point DarkGardenMK.", styRobot))
    story.append(FrameBreak())

    if _GIF:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string filename.",
                styleSheet['Italic']))
        story.append(platypus.Image(_GIF))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 filename.",
                styleSheet['Italic']))
        #story.append(platypus.Image(fileName2FSEnc(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string file url.",
                styleSheet['Italic']))
        story.append(platypus.Image(getFurl(_GIF)))
        story.append(
            Paragraph("Here is an Image flowable obtained from an open file.",
                      styleSheet['Italic']))
        story.append(platypus.Image(open_for_read(_GIF, 'b')))
        story.append(FrameBreak())
        try:
            img = platypus.Image(
                'http://www.reportlab.com/rsrc/encryption.gif')
            story.append(
                Paragraph(
                    "Here is an Image flowable obtained from a string http url.",
                    styleSheet['Italic']))
            story.append(img)
        except:
            story.append(
                Paragraph(
                    "The image could not be obtained from a string http url.",
                    styleSheet['Italic']))
        story.append(FrameBreak())

    if _JPG:
        img = platypus.Image(_JPG)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from a filename.",
                styleSheet['Italic']))
        story.append(img)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from an open file.",
                styleSheet['Italic']))
        img = platypus.Image(open_for_read(_JPG, 'b'))
        story.append(img)
        story.append(FrameBreak())

    return story
Exemple #28
0
def print_monthly_report(dao, month_date):

    strip_style = ParagraphStyle(name="regular",
                                 fontName='Helvetica-Bold',
                                 fontSize=16,
                                 spaceAfter=0,
                                 spaceBefore=0)
    s = ParagraphStyle(name="regular", fontName='Courrier', fontSize=7)
    order_style = ParagraphStyle(name="regular",
                                 fontName='Helvetica-Bold',
                                 fontSize=14,
                                 spaceAfter=6,
                                 spaceBefore=12)
    small = ParagraphStyle(name="regular", fontName='Helvetica', fontSize=8)
    small_right = ParagraphStyle(name="regular",
                                 fontName='Helvetica',
                                 fontSize=8,
                                 alignment=TA_RIGHT)
    client = ParagraphStyle(name="regular",
                            fontName='Helvetica-Bold',
                            fontSize=9)
    right_align = ParagraphStyle(name="right_align",
                                 fontName='Courier',
                                 fontSize=8,
                                 alignment=TA_RIGHT)
    right_align_bold = ParagraphStyle(name="right_align",
                                      fontName='Courier-Bold',
                                      fontSize=8,
                                      alignment=TA_RIGHT)
    complete_document = []
    spacer = platypus.Spacer(1, 50)

    ts_begin = _first_moment_of_month(month_date)
    ts_end = _last_moment_of_month(month_date)

    # mainlog.debug("Turnover from {} to {} ({})".format(ts_begin, ts_end, month_date))

    # data_ops = [[crlf_to_br(h) for h in [_('Ord.'),_('Description'),_('Hours'),_('Qties'),_('Sell\nprice'),_('To bill\nthis month'),_('Encours')]]]
    data_ops = [[
        _('Ord.'),
        _('Description'),
        _('Hours'),
        _('Qties'),
        _('Sell\nprice'),
        _('To bill\nthis month'),
        _('Encours')
    ]]

    ts = platypus.TableStyle([('FONT', (0, 0), (-1, -1), 'Courier', 8)])

    last_order_id = None

    total_sell_price = 0
    total_encours = 0
    total_to_facture = 0

    sub_total_sell_price = 0
    sub_total_encours = 0
    sub_total_h_done = sub_total_h_planned = 0
    sub_total_to_facture = 0

    row = 1
    first_row = True
    row_in_order = 0

    mainlog.debug("dao.order_dao.order_parts_for_monthly_report(month_date):")
    for part_data in dao.order_dao.order_parts_for_monthly_report(month_date):

        if last_order_id != part_data.order_id:

            last_order_id = part_data.order_id

            if not first_row and row_in_order >= 2:
                # Display sums only if there is more than one row
                # for the order (if only one row, then showing a
                # sum doesn't add any information to the user)

                ts.add('LINEABOVE', (5, row), (-1, row), 0.5, colors.black)
                ts.add('LINEABOVE', (2, row), (2, row), 0.5, colors.black)
                data_ops.append([
                    '',
                    '',
                    Paragraph(
                        '{} / {}'.format(duration_to_s(sub_total_h_done),
                                         duration_to_s(sub_total_h_planned)),
                        small_right),
                    '',
                    '',  # Paragraph(amount_to_short_s(sub_total_sell_price) or "0,00" ,right_align),
                    Paragraph(
                        amount_to_short_s(sub_total_to_facture) or "0,00",
                        right_align_bold),
                    Paragraph(
                        amount_to_short_s(sub_total_encours) or "0,00",
                        right_align)
                ])
                row += 1

            sub_total_sell_price = 0
            sub_total_encours = 0
            sub_total_h_done = sub_total_h_planned = 0
            sub_total_to_facture = 0
            row_in_order = 0

            ts.add('LINEABOVE', (0, row), (-1, row), 0.5, colors.black)
            data_ops.append([
                '',
                Paragraph(part_data.customer_name, client), '', '', '', '', ''
            ])
            row += 1

        facture_explain = ""
        q_out_this_month = part_data.part_qty_out - part_data.q_out_last_month
        # Only give an explanation if all the qty were not done
        # together
        if part_data.q_out_last_month > 0 and q_out_this_month > 0 and q_out_this_month < part_data.qty:
            facture_explain = "({}) ".format(q_out_this_month)

        if part_data.total_estimated_time > 0:
            qty_work = "{} / {}".format(
                duration_to_s(part_data.part_worked_hours) or "0,00",
                duration_to_s(part_data.total_estimated_time))
        else:
            qty_work = "-"

        if part_data.qty > 0:
            qty_str = "{} / {}".format(part_data.part_qty_out, part_data.qty)
        else:
            qty_str = "-"

        data_ops.append([
            Paragraph(part_data.human_identifier, small),
            Paragraph(part_data.description, small),
            Paragraph(qty_work, small_right),
            Paragraph(qty_str, small_right),
            Paragraph(amount_to_short_s(part_data.total_sell_price),
                      right_align),
            Paragraph(
                facture_explain + amount_to_short_s(part_data.bill_this_month),
                right_align_bold),
            Paragraph(amount_to_short_s(part_data.encours), right_align)
        ])

        # if part_data.bill_this_month or True:
        #     print("{} {} {}".format(part_data.human_identifier, part_data.part_qty_out, amount_to_short_s(part_data.bill_this_month)))

        row_in_order += 1
        row += 1

        sub_total_sell_price += total_sell_price
        sub_total_to_facture += part_data.bill_this_month
        sub_total_encours += part_data.encours

        sub_total_h_done += part_data.part_worked_hours or 0
        sub_total_h_planned += part_data.total_estimated_time or 0

        total_to_facture += part_data.bill_this_month
        total_encours += part_data.encours

        first_row = False

    data_ops.append([
        '',
        '',
        '',
        '',
        '',  # Removed total_sell_price because it is misleading
        Paragraph(amount_to_short_s(total_to_facture), right_align_bold),
        Paragraph(amount_to_short_s(total_encours), right_align)
    ])

    ts.add('LINEABOVE', (0, len(data_ops) - 1), (-1, len(data_ops) - 1), 1,
           colors.black)

    ts.add('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 9)
    ts.add('LINEBELOW', (0, 0), (-1, 0), 1, colors.black)

    t = platypus.Table(data_ops,
                       repeatRows=1,
                       colWidths=[
                           1.50 * cm, 6 * cm, 2.5 * cm, 1.75 * cm, 2.25 * cm,
                           2.25 * cm
                       ])

    t.setStyle(ts)
    t.hAlign = "LEFT"
    complete_document.append(t)
    complete_document.append(platypus.Spacer(0, 10))

    filename = make_pdf_filename("MonthlyOverview_")
    ladderDoc = basic_PDF(filename)

    ladderDoc.subject = _("Monthly financial report")
    ladderDoc.title = date_to_my(month_date, True)

    ladderDoc.build(complete_document, canvasmaker=NumberedCanvas)
    open_pdf(filename)
    return True
    def _create_story(self):

        # Set up an empty list to hold the story
        story = []

        # Import the report styles
        styles = report_styles.get_report_styles()

        # Create a page break
        story = self._make_page_break(story, self.PORTRAIT)

        # Section title
        title_str = '<strong>Data Dictionary</strong>'
        para = p.Paragraph(title_str, styles['section_style'])
        t = p.Table([[para]], colWidths=[7.5 * u.inch])
        t.setStyle(
            p.TableStyle([
                ('TOPPADDING', (0, 0), (-1, -1), 6),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
                ('BACKGROUND', (0, 0), (-1, -1), '#957348'),
                ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
            ]))
        story.append(t)
        story.append(p.Spacer(0, 0.1 * u.inch))

        # Read in the stand attribute metadata
        mp = xsmp.XMLStandMetadataParser(self.stand_metadata_file)

        # Subset the attributes to those that are accuracy attributes, are
        # identified to go into the report, and are not species variables
        attrs = []
        for attr in mp.attributes:
            if attr.accuracy_attr == 1 and attr.project_attr == 1 and \
                    attr.species_attr == 0:
                attrs.append(attr.field_name)

        # Set up the master dictionary table
        dictionary_table = []

        # Iterate through the attributes and print out the field information
        # and codes if present
        for attr in attrs:
            metadata = mp.get_attribute(attr)
            field_name = metadata.field_name
            units = metadata.units
            description = metadata.description

            field_para = p.Paragraph(field_name, styles['body_style_10'])
            if units != 'none':
                description += ' (' + units + ')'
            field_desc_para = p.Paragraph(description, styles['body_style_10'])

            # If this field has codes, create a sub table underneath the
            # field description
            if metadata.codes:

                # Set up a container to hold the code rows
                code_table = []

                # Iterate over all code rows and append to the code_table
                for code in metadata.codes:
                    code_para = \
                        p.Paragraph(code.code_value, styles['code_style'])
                    description = self.txt_to_html(code.description)
                    code_desc_para = \
                        p.Paragraph(description, styles['code_style'])
                    code_table.append([code_para, code_desc_para])

                # Convert this to a reportlab table
                t = p.Table(code_table,
                            colWidths=[0.75 * u.inch, 4.5 * u.inch])
                t.setStyle(
                    p.TableStyle([
                        ('TOPPADDING', (0, 0), (-1, -1), 3),
                        ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
                        ('BACKGROUND', (0, 0), (-1, -1), '#f7f7ea'),
                        ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'),
                        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                        ('GRID', (0, 0), (-1, -1), 0.25, colors.white),
                    ]))

                # Create a stack of the field description and field codes
                elements = \
                    [[field_desc_para], [t]]

            # If no codes exist, just add the field description
            else:
                elements = [[field_desc_para]]

            # Create a reportlab table of the field description and
            # (if present) field codes
            description_table = \
                p.Table(elements, colWidths=[5.25 * u.inch])
            description_table.setStyle(
                p.TableStyle([
                    ('TOPPADDING', (0, 0), (-1, 0), 0),
                    ('BOTTOMPADDING', (0, -1), (-1, -1), 0),
                    ('LEFTPADDING', (0, 0), (-1, -1), 0),
                    ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                    ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'),
                    ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ]))

            dictionary_table.append([field_para, description_table])

        # Format the dictionary table into a reportlab table
        t = p.Table(dictionary_table, colWidths=[1.6 * u.inch, 5.4 * u.inch])
        t.setStyle(
            p.TableStyle([
                ('TOPPADDING', (0, 0), (0, -1), 5),
                ('BOTTOMPADDING', (0, 0), (0, -1), 5),
                ('GRID', (0, 0), (-1, -1), 1, colors.white),
                ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('BACKGROUND', (0, 0), (-1, -1), '#f1efe4'),
            ]))
        story.append(t)

        # Description of the species information that is attached to ArcInfo
        # grids.  We don't enumerate the codes here, but just give this
        # summary information
        spp_str = """
            Individual species abundances are attached to ArcInfo grids that
            LEMMA distributes.  For this model, fields designate species
            codes based on the <link color="#0000ff"
            href="http://plants.usda.gov/">USDA PLANTS database</link> from
            the year 2000, and values represent species
        """
        if self.model_type in ['sppsz', 'sppba']:
            spp_str += " basal area (m^2/ha)."
        elif self.model_type in ['trecov', 'wdycov']:
            spp_str += " percent cover."

        para = p.Paragraph(spp_str, styles['body_style'])
        story.append(p.Spacer(0, 0.1 * u.inch))
        story.append(para)

        # Return this story
        return story
Exemple #30
0
        def __init__(self, context, filename, headings, all_first_heads,
                     all_other_heads, all_ars, all_results, all_cats, all_oor,
                     all_dries, all_attachments, all_remarks, all_managers,
                     all_disclaimers, lab_title):
            def myFirstPage(canvas, doc):
                canvas.saveState()
                drawLogos(canvas, doc)
                canvas.restoreState()

            def myLaterPages(canvas, doc):
                canvas.saveState()
                drawLogos(canvas, doc)
                canvas.restoreState()

            def drawLogos(canvas, doc):
                if self.logos[self.logo_imgs[0]] is not None:
                    # draws the logo if it exists
                    (image, width, height) = self.logos[self.logo_imgs[0]]
                    canvas.drawImage(image, 0.75 * inch,
                                     doc.pagesize[1] - inch * 1.2, width / 1.5,
                                     height / 1.5)
                if self.logos[self.logo_imgs[1]] is not None:
                    # draws the accreditation logo if it exists
                    (image, width, height) = self.logos[self.logo_imgs[1]]
                    canvas.drawImage(image, 5.5 * inch,
                                     doc.pagesize[1] - inch * 1.2, width / 1.5,
                                     height / 1.5)
                canvas.setFont('Helvetica', 10)
                canvas.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page)

            # save some datas
            self.context = context
            self.built = 0
            self.objects = []

            # get all the images we need now, in case we've got
            # several pages this will save some CPU

            self.logos = {}
            self.logo_imgs = ['logo_print.jpg', 'accreditation_print.jpg']
            for pic in self.logo_imgs:
                image = self.getImageFP(pic)
                self.logos[pic] = image

            images = {}
            icons = [
                'no_invoice.png',
                'dry.png',
                'accredited.jpg',
                'exclamation.jpg',
                'telephone.jpg',
                'email.jpg',
            ]
            for pic in icons:
                image = self.getImageFromFS(pic, width=12)
                images[pic] = image
            for manager in all_managers:
                owner = manager
                pic = 'Signature'
                image = self.getImageFromZODB(pic, owner)
                images[manager.getId()] = image

            #   save some colors
            bordercolor = colors.HexColor(0x999933)
            #backgroundcolor = colors.HexColor(0xD3D3AD)
            backgroundcolor = colors.HexColor(0xFFFFFF)
            dryheadcolor = colors.HexColor(0xA6B5DB)
            #drybodycolor = colors.HexColor(0xDAE0F0)
            drybodycolor = colors.HexColor(0xFFFFFF)
            #catcolor = colors.HexColor(0xB6C0D1)
            catcolor = colors.HexColor(0xFFFFFF)

            # we will build an in-memory document
            # instead of creating an on-disk file.
            self.report = cStringIO.StringIO()

            # initialise a PDF document using ReportLab's platypus
            self.doc = SimpleDocTemplate(self.report)

            # get page size
            page_width = self.doc.pagesize[0] - 1.5 * inch
            h_col_width = page_width / 2
            page_height = self.doc.pagesize[1]

            # get the default style sheets
            self.StyleSheet = styles.getSampleStyleSheet()
            self.StyleSheet['Normal'].fontName = 'Helvetica'
            self.StyleSheet['Heading1'].fontName = 'Helvetica'

            # then build a simple doc with ReportLab's platypus
            self.append(Spacer(0, 20))

            h_table = platypus.Table(headings,
                                     colWidths=(h_col_width, h_col_width))

            style = platypus.TableStyle([
                ('ALIGN', (0, 0), (0, -1), 'LEFT'),
                ('ALIGN', (-1, 0), (-1, -1), 'RIGHT'),
                ('FONT', (0, 0), (-1, -1), 'Helvetica'),
            ])
            h_table.setStyle(style)
            self.append(h_table)

            self.append(Spacer(0, 10))

            no_ars = all_ars[0]

            col = page_width / ((no_ars * 2) + 4)

            for i in range(len(all_results)):
                these_ars = all_ars[i]
                these_results = all_results[i]
                these_dries = all_dries[i]
                cols = [
                    col * 4,
                ]
                """ make as fed column wider than dry column """
                for j in range(these_ars):
                    cols.append(col * 1.4)
                    cols.append(col * 0.6)
                col_widths = tuple(cols)
                first_page = True
                if i > 0:
                    self.append(FrameBreak())
                    self.append(Spacer(0, 10))
                """ attachments """
                attachments = all_attachments[i]
                if len(attachments) == 1:
                    attachments[0][1] == 'None'
                else:
                    a_table = platypus.Table(attachments)
                    table_style = [
                        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                        ('GRID', (0, 0), (-1, -1), 0.1, bordercolor),
                        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                        ('BACKGROUND', (0, 0), (0, -1), backgroundcolor),
                        ('BACKGROUND', (0, 0), (-1, 0), backgroundcolor),
                        ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                        ('FONTSIZE', (0, 0), (-1, -1), 10),
                    ]
                    style = platypus.TableStyle(table_style)
                    a_table.setStyle(style)
                    a_table.setStyle(style)
                    self.append(a_table)

                self.append(Spacer(0, 10))
                """ determine no of lines in attachment table """
                attachment_count = 0
                for attachment in attachments:
                    attachment_count += 1
                    attachment_count += attachment.count('\n')
                """ headings and results """

                general_table_style = [
                    ('ALIGN', (0, 0), (0, -1), 'LEFT'),
                    ('ALIGN', (1, 0), (-1, -1), 'CENTER'),
                    ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                    ('BACKGROUND', (0, 0), (0, -1), backgroundcolor),
                    ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 9),
                ]

                page_max = 18 - attachment_count

                these_oor = all_oor[i]
                these_cats = all_cats[i]
                num_lines = len(these_results)

                slice_end = 0

                while slice_end < num_lines:
                    """ headings """
                    table_style = list(general_table_style)
                    if first_page:
                        page_content = list(all_first_heads[i])
                        table_style.append(
                            ('GRID', (0, 0), (0, -1), 0.1, bordercolor))
                        table_style.append(
                            ('BACKGROUND', (0, 11), (-1, 11), backgroundcolor))
                        table_style.append(('LINEBELOW', (0, 10), (
                            -1,
                            10,
                        ), 1, bordercolor))
                        table_style.append(
                            ('LINEBELOW', (0, 11), (-1, 11), 1, bordercolor))
                        """ span and box the header lines """
                        for j in range(11):
                            for k in range(these_ars):
                                table_style.append(('SPAN', ((k * 2) + 1, j),
                                                    ((k * 2) + 2, j)))
                                table_style.append(
                                    ('BOX', ((k * 2) + 1, j), ((k * 2) + 2, j),
                                     0.1, bordercolor))

                    else:
                        self.append(FrameBreak())
                        self.append(Spacer(0, 20))
                        page_content = list(all_other_heads[i])
                        table_style.append(
                            ('GRID', (0, 0), (0, -1), 0.1, bordercolor))
                        table_style.append(
                            ('BACKGROUND', (0, 4), (-1, 4), backgroundcolor))
                        table_style.append(('LINEBELOW', (0, 3), (
                            -1,
                            3,
                        ), 1, bordercolor))
                        table_style.append(
                            ('LINEBELOW', (0, 4), (-1, 4), 1, bordercolor))
                        """ span and box the header lines """
                        for j in range(4):
                            for k in range(these_ars):
                                table_style.append(('SPAN', ((k * 2) + 1, j),
                                                    ((k * 2) + 2, j)))
                                table_style.append(
                                    ('BOX', ((k * 2) + 1, j), ((k * 2) + 2, j),
                                     0.1, bordercolor))

                    offset = len(page_content)

                    slice_start = slice_end
                    slice_end = slice_start + page_max
                    if slice_end > num_lines:
                        slice_end = num_lines
                    page_max = 30

                    page_results = these_results[slice_start:slice_end]
                    """ results """
                    page_content.extend(page_results)
                    c_table = platypus.Table(page_content,
                                             colWidths=col_widths)

                    for orig_highlight in these_oor:
                        if orig_highlight[1] < slice_start:
                            continue
                        if orig_highlight[1] >= slice_end:
                            continue
                        highlight = ((orig_highlight[0] * 2) + 1,
                                     orig_highlight[1] + offset - slice_start)
                        table_style.append(
                            ('TEXTCOLOR', highlight, highlight, colors.red))

                    table_length = len(page_content)
                    if first_page:
                        first_page = False
                        """ span and box the detail lines """
                        for k in range(these_ars):
                            for j in range(11, table_length):
                                if k in these_dries:
                                    table_style.append(
                                        ('BOX', ((k * 2) + 1, j),
                                         ((k * 2) + 1, j), 0.1, bordercolor))
                                    table_style.append(
                                        ('BOX', ((k * 2) + 2, j),
                                         ((k * 2) + 2, j), 0.1, bordercolor))
                                else:
                                    table_style.append(
                                        ('SPAN', ((k * 2) + 1, j),
                                         ((k * 2) + 2, j)))
                                    table_style.append(
                                        ('BOX', ((k * 2) + 1, j),
                                         ((k * 2) + 2, j), 0.1, bordercolor))
                        """ colour the dry matter columns """
                        for k in range(these_ars):
                            if k in these_dries:
                                table_style.append(
                                    ('BACKGROUND', ((k * 2) + 2, 11),
                                     ((k * 2) + 2, 11), dryheadcolor))
                                table_style.append(
                                    ('BACKGROUND', ((k * 2) + 2, 12),
                                     ((k * 2) + 2, -1), drybodycolor))
                    else:
                        """ span and box the detail lines """
                        for j in range(4, table_length):
                            for k in range(these_ars):
                                if k in these_dries:
                                    table_style.append(
                                        ('BOX', ((k * 2) + 1, j),
                                         ((k * 2) + 1, j), 0.1, bordercolor))
                                    table_style.append(
                                        ('BOX', ((k * 2) + 2, j),
                                         ((k * 2) + 2, j), 0.1, bordercolor))
                                else:
                                    table_style.append(
                                        ('SPAN', ((k * 2) + 1, j),
                                         ((k * 2) + 2, j)))
                                    table_style.append(
                                        ('BOX', ((k * 2) + 1, j),
                                         ((k * 2) + 2, j), 0.1, bordercolor))
                        """ colour the dry matter columns """
                        for k in range(these_ars):
                            if k in these_dries:
                                table_style.append(
                                    ('BACKGROUND', ((k * 2) + 2, 4),
                                     ((k * 2) + 2, 4), dryheadcolor))
                                table_style.append(
                                    ('BACKGROUND', ((k * 2) + 2, 5),
                                     ((k * 2) + 2, -1), drybodycolor))
                    """ colour and span the category lines """
                    for cat in these_cats:
                        if cat < slice_start:
                            continue
                        if cat >= slice_end:
                            continue
                        cat_box_start = (0, cat + offset - slice_start)
                        cat_box_end = (-1, cat + offset - slice_start)
                        table_style.append(
                            ('SPAN', cat_box_start, cat_box_end))
                        table_style.append(('BACKGROUND', cat_box_start,
                                            cat_box_end, catcolor))
                    style = platypus.TableStyle(table_style)
                    c_table.setStyle(style)
                    self.append(c_table)

                self.append(Spacer(0, 10))
                """ remarks """
                remarks = all_remarks[i]
                if remarks:
                    r_table = platypus.Table(remarks)
                    table_style = [
                        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                        ('GRID', (0, 0), (-1, -1), 0.1, bordercolor),
                        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                        ('BACKGROUND', (0, 0), (0, -1), backgroundcolor),
                        ('BACKGROUND', (0, 0), (-1, 0), backgroundcolor),
                        ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                        ('FONTSIZE', (0, 0), (-1, -1), 9),
                    ]
                    style = platypus.TableStyle(table_style)
                    r_table.setStyle(style)
                    self.append(KeepTogether(r_table))

                self.append(Spacer(0, 10))
                """ disclaimers """
                disclaimers = all_disclaimers[i]
                table_style = [
                    ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                    ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkgray),
                    ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 9),
                ]
                style = platypus.TableStyle(table_style)
                h_spacer = 10
                d_stuff = []
                for disclaimer in disclaimers:
                    disclaimer.append(' ')
                d_table = platypus.Table(disclaimers,
                                         colWidths=(page_width - 3, 3))
                d_table.setStyle(style)
                self.append(d_table)

                i += 1

            self.append(Spacer(0, 10))
            """ signatures"""

            textStyle = ParagraphStyle('BodyText',
                                       alignment=0,
                                       fontName='Helvetica',
                                       fontSize=10)
            table_style = [
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                ('FONTSIZE', (0, 0), (-1, -1), 10),
            ]
            style = platypus.TableStyle(table_style)
            h_spacer = 6
            for manager in all_managers:
                keepers = []

                signatures = [
                    (images[manager.getId()], ' '),
                ]

                s_table = platypus.Table(signatures,
                                         colWidths=(h_col_width, h_col_width))

                s_table.setStyle(style)
                keepers.append(s_table)

                m_stuff = []
                name = manager.Title()
                phone = manager.getBusinessPhone()
                email = manager.getEmailAddress()

                m_stuff.append([
                    name, images['telephone.jpg'], phone, images['email.jpg'],
                    email
                ])
                x = page_width - (len(name) * h_spacer) - (
                    len(phone) * h_spacer) - len(email) - 36
                m_table = platypus.Table(m_stuff,
                                         colWidths=(len(name) * h_spacer, 18,
                                                    len(phone) * h_spacer, 18,
                                                    len(email) + x))
                m_table.setStyle(style)
                keepers.append(m_table)
                para = Paragraph(lab_title, textStyle)
                keepers.append(para)
                keepers.append(Spacer(0, 10))
                self.append(KeepTogether(keepers))

            # generation du document PDF
            self.doc.build(self.objects,
                           onFirstPage=myFirstPage,
                           onLaterPages=myLaterPages)

            self.built = 1