Example #1
0
def buildTable(data):
  doc = SimpleDocTemplate("MOOSE_requirements_tracability.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
  doc.pagesize = landscape(A4)
  elements = []

  #Configure style and word wrap
  s = getSampleStyleSheet()
  s = s["BodyText"]
  s.wordWrap = 'CJK'

  pdf_data = [["Requirement", "Description", "Test Case(s)"]]

  #TODO: Need a numerical sort here
  keys = sorted(data.keys())

  for key in keys:
    data[key][2] = '\n'.join(data[key][2])
    pdf_data.append([Paragraph(cell, s) for cell in data[key]])


  # Build the Table and Style Information
  tableThatSplitsOverPages = Table(pdf_data, repeatRows=1)
  tableThatSplitsOverPages.hAlign = 'LEFT'
  tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),colors.black),
                         ('VALIGN',(0,0),(-1,-1),'TOP'),
                         ('LINEBELOW',(0,0),(-1,-1),1,colors.black),
                         ('INNERGRID', (0,0), (-1,-1),1,colors.black),
                         ('BOX',(0,0),(-1,-1),1,colors.black),
                         ('BOX',(0,0),(0,-1),1,colors.black)])
  tblStyle.add('BACKGROUND',(0,0),(-1,-1),colors.lightblue)
  tblStyle.add('BACKGROUND',(0,1),(-1,-1),colors.white)
  tableThatSplitsOverPages.setStyle(tblStyle)
  elements.append(tableThatSplitsOverPages)

  doc.build(elements)
Example #2
0
    def gather_elements(self, client, node, style):
        if node.children and isinstance(node.children[0], docutils.nodes.title):
            title=[]
        else:
            title= [Paragraph(client.text_for_label(node.tagname, style),
                style=client.styles['%s-heading'%node.tagname])]
        rows=title + client.gather_elements(node, style=style)
        st=client.styles[node.tagname]
        if 'commands' in dir(st):
            t_style = TableStyle(st.commands)
        else:
            t_style = TableStyle()
        t_style.add("ROWBACKGROUNDS", [0, 0], [-1, -1],[st.backColor])
        t_style.add("BOX", [ 0, 0 ], [ -1, -1 ], st.borderWidth , st.borderColor)

        if client.splittables:
            node.elements = [MySpacer(0,st.spaceBefore),
                                SplitTable([['',rows]],
                                style=t_style,
                                colWidths=[0,None],
                                padding=st.borderPadding),
                                MySpacer(0,st.spaceAfter)]
        else:
            padding, p1, p2, p3, p4=tablepadding(padding=st.borderPadding)
            t_style.add(*p1)
            t_style.add(*p2)
            t_style.add(*p3)
            t_style.add(*p4)
            node.elements = [MySpacer(0,st.spaceBefore),
                                DelayedTable([['',rows]],
                                style=t_style,
                                colWidths=[0,None]),
                                MySpacer(0,st.spaceAfter)]
        return node.elements
Example #3
0
def make_table(printable):
	style = TableStyle()
	style.add('VALIGN', (0,0), (-1,-1), 'TOP')
	style.add('GRID', (0,0), (-1,-1), 1, colors.black)
	table = Table(printable, [col_width*0.4,col_width*0.6])
	table.setStyle(style)
	return table
Example #4
0
def table(data):
	"""
	return list, so "extend" method should be used.
	"""
	"""
	para_style = STYLES["BodyText"]
	para_style.wordWrap = 'CJK'
	para_style.backColor = colors.red
	table_data = [[Paragraph(cell, para_style) for cell in row] for row in data]
	"""
	table_data = data
	table_style = TableStyle([
		('ALIGN',(0,0),(-1,0),'CENTER'),
		('ALIGN',(0,1),(0,-1),'LEFT'),
		('ALIGN',(1,1),(-1,-1),'RIGHT'),
		('VALIGN',(0,0),(-1,-1),'MIDDLE'),
		('BOX', (0,0), (-1,0), 2, colors.black),
		('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
		('TEXTCOLOR',(1,1),(-2,-2),colors.red),
		('BACKGROUND', (0,0), (-1,0), colors.black),
		('TEXTCOLOR',(0,0),(-1,0),colors.white),
		('TEXTCOLOR',(0,1),(-1,-1),colors.black),
		#('VALIGN',(0,0),(0,-1),'TOP'),
		#('TEXTCOLOR',(0,0),(0,-1),colors.blue),
		])
	for i in range(1, len(table_data)):
		if i%2 == 0:
			table_style.add('BACKGROUND', (0,i), (-1,i), 
					colors.Color(.835,.91,.976))

	t = Table(table_data)
	t.setStyle(table_style)
	return [t]
Example #5
0
 def print_entries(self, eh, ehds):
     buffer = self.buffer
     styles = getSampleStyleSheet()
     data = []
     ts = TableStyle()
     d = []
     hs = styles['Heading1']
     hs.alignment = TA_CENTER
     d.append(Paragraph('<b>Producto</b>', hs))
     d.append(Paragraph('<b>Descripci&oacute;n</b>', hs))
     d.append(Paragraph('<b>Cantidad</b>', hs))
     if eh.printed:
         if(eh.action == 'altas'):
             title = Paragraph('<b> Entrada de Mercanc&iacute;a - REIMPRESI&Oacute;N</b>', hs)
         else:
             title = Paragraph('<b> Salida de Mercanc&iacute;a - REIMPRESI&Oacute;N</b>', hs)
     else:   
         if(eh.action == 'altas'):
             title = Paragraph('<b> Entrada de Mercanc&iacute;a </b>', hs)
         else:
             title = Paragraph('<b> Salida de Mercanc&iacute;a </b>', hs)
     data.append(d)
     total_qty = 0
     sp = styles['BodyText']
     sp.alignment = TA_CENTER
     sq = styles['BodyText']
     sq.alignment = TA_RIGHT
     spb = styles['Heading3']
     spb.alignment = TA_RIGHT
     sl = styles['Normal']
     sl.alignment = TA_CENTER
     for ehd in ehds:
         d = []
         d.append(ehd.product.name)
         p = Paragraph(ehd.product.description.encode('utf-8'), sp)
         d.append(p)
         pq = Paragraph(str(ehd.quantity), sq)
         d.append(pq)
         data.append(d)
         total_qty += ehd.quantity
     t = Table(data, colWidths = [(letter[0] * .20), (letter[0] * .50), (letter[0] * .20)])
     ts.add('LINEBELOW', (0,1), (-1,-1), 0.25, colors.black)
     t.setStyle(ts)
     elements = []
     elements.append(title)
     elements.append(t)
     elements.append(Paragraph('<br /><p> <b>Cantidad total de art&iacute;culos:</b> ' + str(total_qty) + '</p>', spb))
     if(eh.action == 'altas'):
         elements.append(Paragraph('<br /><p> Al firmar este documento acepto que estoy recibiendo la mercanc&iacute;a listada y me responsabilizo por la mercanc&iacute;a. <br /><br /><br/> Nombre:_____________________ Firma: _____________________________</p>',sl))
     else:
         elements.append(Paragraph('<br /><p> Al firmar este documento acepto la salida de esta mercanc&iacute;a. <br /><br /><br/> Nombre:_____________________ Firma: _____________________________</p>',sl))
     doc = SimpleDocTemplate(buffer, pagesize=letter)
     doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer, canvasmaker = NumberedCanvas)
     return buffer
Example #6
0
 def second_paragraph(self):    
     self.story.append(myParagraph(u"Nom du bénéficiaire : <b>" + self.facture_view.nom_prenom() + u"</b>", 'style1', spaceAfter=10))
     self.story.append(myParagraph(u"Montant de la prestation", 'style1'))
     self.story.append(myParagraph(u"<b>(" + self.facture_view.jours_prestation_string() + u")</b> Jours....................................<b>%.2f " % (self.facture_view.montant_presta()) + u"</b>€uros", 'style1', spaceAfter=25))
     self.story.append(myParagraph(u"Arrêtée et certifiée conforme la présente facture à la somme de :", 'style1', spaceAfter=25))
     
     table_style = TableStyle([('BOX', (0,0), (-1,-1), 0.25, black),
                               ('BOX', (0,0), (-1,-1), 0.25, black),])
     table_style.spaceAfter=25
     table_data = [[myParagraph(u"<b>" + self.facture_view.montant_presta_word().upper() + u"</b>", 'style1', alignment=TA_CENTER),],]               
     self.story.append(Table(data=table_data, style=table_style))
Example #7
0
def generate_monthly_summary_table(huc12):
    """Make a table of monthly summary stats."""
    data = []
    data.append(['Year', 'Month', 'Precip', "Runoff", "Loss", "Delivery",
                '2+" Precip', 'Events'])
    data.append(['', '', '[inch]', "[inch]", "[tons/acre]", "[tons/acre]",
                 "[days]", "[days]"])
    pgconn = get_dbconn('idep')
    huc12col = "huc_12"
    if len(huc12) == 8:
        huc12col = "substr(huc_12, 1, 8)"
    df = read_sql("""
    WITH data as (
        SELECT extract(year from valid)::int as year,
        extract(month from valid)::int as month, huc_12,
        (sum(qc_precip) / 25.4)::numeric as sum_qc_precip,
        (sum(avg_runoff) / 25.4)::numeric as sum_avg_runoff,
        (sum(avg_loss) * 4.463)::numeric as sum_avg_loss,
        (sum(avg_delivery) * 4.463)::numeric as sum_avg_delivery,
        sum(case when qc_precip >= 50.8 then 1 else 0 end) as pdays,
        sum(case when avg_loss > 0 then 1 else 0 end) as events
        from results_by_huc12 WHERE scenario = 0 and
        """ + huc12col + """ = %s
        and valid >= '2016-01-01'
        GROUP by year, month, huc_12)
    SELECT year, month,
    round(avg(sum_qc_precip), 2),
    round(avg(sum_avg_runoff), 2),
    round(avg(sum_avg_loss), 2),
    round(avg(sum_avg_delivery), 2),
    round(avg(pdays)::numeric, 1),
    round(avg(events)::numeric, 1)
    from data GROUP by year, month ORDER by year, month
    """, pgconn, params=(huc12, ), index_col=None)
    for _, row in df.iterrows():
        vals = [int(row['year']), calendar.month_abbr[int(row['month'])]]
        vals.extend(["%.2f" % (f, ) for f in list(row)[2:-2]])
        vals.extend(["%.0f" % (f, ) for f in list(row)[-2:]])
        data.append(vals)
    data[-1][1] = "%s*" % (data[-1][1], )
    totals = df.iloc[:-1].mean()
    vals = ['', 'Average']
    vals.extend(["%.2f" % (f, ) for f in list(totals[2:])])
    data.append(vals)

    style = TableStyle(
        [('LINEBELOW', (2, 1), (-1, 1), 0.5, '#000000'),
         ('LINEAFTER', (1, 2), (1, -2), 0.5, '#000000'),
         ('LINEABOVE', (2, -1), (-1, -1), 0.5, '#000000'),
         ('ALIGN', (0, 0), (-1, -1), 'RIGHT')]
    )
    for rownum in range(3, len(data)+1, 2):
        style.add('LINEBELOW', (0, rownum), (-1, rownum), 0.25, '#EEEEEE')
    return Table(data, style=style, repeatRows=2)
Example #8
0
 def frein_type_result(self, frein_type, resultat_list):
     en_tete = ((StatParagraph("<b><i>" + frein_type + "</i></b>", 'style3'),
                 StatParagraph("<b><i>" + u"Frein le plus important" + "</i></b>", 'style3'),
                 StatParagraph("<b><i>" + u"Frein présent" + "</i></b>", 'style3')),)
     data = tuple([(StatParagraph(categorie, 'style3'),
                    StatParagraph(str(nb_plus_imp), 'style3'),
                    StatParagraph(str(nb_all), 'style3'))
                    for (categorie, nb_plus_imp, nb_all) in resultat_list])
     table_data = en_tete + data
     table_style = TableStyle([('GRID', (0,0), (-1,-1), 0.25, black),])
     table_style.spaceAfter=25
     table_style.spaceBefore=25
     self.story.append(Table(data=table_data, style=table_style))
    def get_underline():
        data = [[None], [None]]

        line = Table(
            data,
            colWidths=[6.2 * inch],
            rowHeights=[0.03 * inch, 0.14 * inch])

        table_style = TableStyle()
        table_style.add('LINEBELOW', (0, 0), (0, 0), 1, colors.black)
        line.setStyle(table_style)

        return line
Example #10
0
def getTableStyle():
    ts = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                     ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                     ('LINEBELOW', (0, 0), (-1, -1), 0.8, colors.black),
                     ('BOX', (0, 0), (-1, -1), 0.75, colors.black),
                     ('BOX', (0, 0), (0, -1), 0.75, colors.black),
                     ('BOX', (1, 0), (1, -1), 0.75, colors.black),
                     ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
                     ('FONTNAME', (0, 0), (-1, -1), 'Arabic'),
                     ('FONTSIZE', (0, 0), (-1, -1), TABLE_FONT_SIZE),
                     ])
    ts.add('BACKGROUND', (0, 0), (-1, 1), colors.lightgrey)  # header lightgrey
    ts.add('BACKGROUND', (0, 1), (-1, -1), colors.white)  # rest of table
    return ts
Example #11
0
    def _new_style(self, header_line_idx=None, header_line_width=1, header_line_color="black", debug_grid=False):

        ts = TableStyle()
        if debug_grid:
            ts.add("GRID", (0, 0), (-1, -1), 1, colors.red)

        if isinstance(header_line_color, str):
            try:
                header_line_color = getattr(colors, header_line_color)
            except AttributeError:
                header_line_color = colors.black

        if header_line_idx is not None:
            ts.add("LINEBELOW", (0, header_line_idx), (-1, header_line_idx), header_line_width, header_line_color)

        return ts
Example #12
0
def getTableStyleThreeCol():
    ts = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                     ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                     ('LINEBELOW', (0, 0), (-1, -1), 0.8, colors.black),
                     ('BOX', (0, 0), (-1, -1), 0.75, colors.black),
                     ('BOX', (0, 0), (0, -1), 0.75, colors.black),
                     ('BOX', (1, 0), (1, -1), 0.75, colors.black),
                     ('ALIGN', (0, 0), (0, -1), 'CENTER'),  # center number column
                     ('ALIGN', (1, 0), (1, -1), 'RIGHT'),   # right align name column
                     ('ALIGN', (2, 0), (2, -1), 'CENTER'),  # center number column
                     ('FONTNAME', (0, 0), (-1, -1), 'Arabic'),
                     ('FONTSIZE', (0, 0), (-1, -1), TABLE_FONT_SIZE),
                     ])
    ts.add('BACKGROUND', (0, 0), (-1, 1), colors.lightgrey)  # header lightgrey
    ts.add('BACKGROUND', (0, 1), (-1, -1), colors.white)  # rest of table
    return ts
Example #13
0
 def tableau_intro(self):
     style_tableau = TableStyle([('BOX', (0,0), (0,-1), 0.25, black),
                                 ('BOX', (1,0), (1,-1), 0.25, black),
                                 ('BOX', (2,0), (2,-1), 0.25, black),
                                 ('BOX', (0,0), (-1,0), 0.25, black),
                                 ('VALIGN',(0,0),(-1,-1),'TOP'),
                                 ])
     style_tableau.spaceAfter = 10
     tableau_data = [[MyParagraph(style='style3', text=u"<b>Bénéficiaire</b>"), MyParagraph(style='style3', text=u"<b>Référent</b>"), MyParagraph(style='style3', text=u"<b>Correspondant ALE</b>")],    
                     [MyParagraph(style='style3', text=u"<b>Nom Prénom : <font color=black>"+self.bilanView.nomprenom()+"</font></b>"), MyParagraph(style='style3', text=u"<b>Nom Prénom : <font color=black>"+self.bilanView.CInomprenom()+"</font></b>"), MyParagraph(style='style3', text=u"<b>Nom Prénom : <font color=black>"+self.bilanView.ALEnomprenom()+"</font></b>")],
                     [MyParagraph(style='style3', text=u"<b>Identifiant n° : <font color=black>"+self.bilanView.idALE()+"</font></b>"), MyParagraph(style='style3', text=u"<b>Organisme : <font color=black>"+self.bilanView.organismeReferent()+"</font></b>"), MyParagraph(style='style3', text=u"<b>ALE : <font color=black>"+self.bilanView.ALEnom()+"</font></b>")],
                     [MyParagraph(style='style3', text=u"<b>Inscrit à ALE de: <font color=black>"+self.bilanView.incritALE()+"</font></b>"), MyParagraph(style='style3', text=u"<b>Tél : <font color=black>"+self.bilanView.refTel()+"</font></b>"), MyParagraph(style='style3', text=u"<b>Tél : <font color=black>"+self.bilanView.ALEtel()+"</font></b>")],
                     [MyParagraph(style='style3', text=u"<b>Tél : <font color=black>"+self.bilanView.LCtel()+"</font></b>"), MyParagraph(style='style3', text=u"<b>Mel : <font color=black>"+self.bilanView.refMail()+"</font></b>"), MyParagraph(style='style3', text=u"<b>Mel : <font color=black>"+self.bilanView.ALEmail()+"</font></b>")],
                     [MyParagraph(style='style3', text=u"<b>Mel : <font color=black>"+self.bilanView.LCmail()+"</font></b>"), None, None],                        
                     ]
     tableau = Table(data=tableau_data, style=style_tableau)
     self.story.append(tableau)
Example #14
0
 def print_inventory_surplus(self, entries, title):
     buffer = self.buffer
     styles = getSampleStyleSheet()
     data = []
     ts = TableStyle()
     d = []
     hs = styles['Heading1']
     hs.alignment = TA_CENTER
     d.append(Paragraph('<b>C&oacute;digo</b>', styles['Normal']))
     d.append(Paragraph('<b>Descripci&oacute;n</b>', styles['Normal']))
     d.append(Paragraph('<b>Existencia</b>', styles['Normal']))
     d.append(Paragraph('<b>Sistema</b>', styles['Normal']))
     d.append(Paragraph('<b>Sobrante</b>', styles['Normal']))
     title = Paragraph('<b> ' + title + '</b>', hs)
     data.append(d)
     total_qty = 0
     sp = styles['BodyText']
     sp.alignment = TA_CENTER
     sq = styles['BodyText']
     sq.alignment = TA_RIGHT
     spb = styles['Heading3']
     spb.alignment = TA_RIGHT
     sl = styles['Normal']
     sl.alignment = TA_CENTER
     for e in entries:
         if e['entry'].product is None:
             continue
         d = []
         d.append(e['entry'].product.name)
         p = Paragraph(e['entry'].product.description.encode('utf-8'), sp)
         d.append(p)
         pq = Paragraph(str(e['entry'].quantity), sq)
         d.append(pq)
         d.append(Paragraph(str(e['tcount']), sq))
         d.append(Paragraph(str(e['diff'] * -1), sq))
         data.append(d)
     t = Table(data, colWidths = [(letter[0] * .15), (letter[0] * .45), (letter[0] * .12), (letter[0] * .12), (letter[0] * .12)])
     ts.add('LINEBELOW', (0,1), (-1, -1), 0.25, colors.black)
     t.setStyle(ts)
     elements = []
     elements.append(title)
     elements.append(t)
     doc = SimpleDocTemplate(buffer, pagesize=letter)
     doc.build(elements, onFirstPage=self._header_footer_inventory, onLaterPages=self._header_footer_inventory, canvasmaker = NumberedCanvas)
     return buffer
Example #15
0
 def print_inventory_existence(self, entries, title):
     buffer = self.buffer
     styles = getSampleStyleSheet()
     data = []
     ts = TableStyle()
     d = []
     hs = styles['Heading1']
     hsc = styles['Heading3']
     hs.alignment = TA_CENTER
     d.append(Paragraph('<b>C&oacute;digo</b>', styles['Normal']))
     d.append(Paragraph('<b>Descripci&oacute;n</b>', styles['Normal']))
     d.append(Paragraph('<b>Cantidad</b>', styles['Normal']))
     title = Paragraph('<b> ' + title + '</b>', styles['Normal'])
     data.append(d)
     total_qty = 0
     sp = styles['BodyText']
     sp.alignment = TA_CENTER
     sq = styles['BodyText']
     sq.alignment = TA_RIGHT
     spb = styles['Heading3']
     spb.alignment = TA_RIGHT
     sl = styles['Normal']
     sl.alignment = TA_CENTER
     for e in entries:
         if e.quantity == 0:
             continue
         d = []
         d.append(e.product.name)
         p = Paragraph(e.product.description.encode('utf-8'), sp)
         d.append(p)
         pq = Paragraph(str(e.quantity), sq)
         d.append(pq)
         data.append(d)
         total_qty += e.quantity
     t = Table(data, colWidths = [(letter[0] * .20), (letter[0] * .50), (letter[0] * .20)])
     ts.add('LINEBELOW', (0,1), (-1, -1), 0.25, colors.black)
     t.setStyle(ts)
     elements = []
     elements.append(title)
     elements.append(t)
     elements.append(Paragraph('<br /><p> <b>Cantidad total de art&iacute;culos:</b> ' + str(total_qty) + '</p>', spb))
     doc = SimpleDocTemplate(buffer, pagesize=letter)
     doc.build(elements, onFirstPage=self._header_footer_inventory, onLaterPages=self._header_footer_inventory, canvasmaker = NumberedCanvas)
     return buffer
Example #16
0
def buildTable(data):
        style = TableStyle()
        style.add('VALIGN', (0,0), (-1,-1), 'TOP')
        style.add('GRID', (0,0), (-1,-1), 1, colors.black)
        style.add('ALIGN', (1,0), (1,-1), 'RIGHT')
        table = Table(data, [width*0.2,width*0.4,width*0.4])
        table.setStyle(style)
        return table
Example #17
0
 def __type_prestation_firstrow(self):
     self.elements.append(Paragraph("<u>Type de prestation</u>", styles.getSampleStyleSheet()['Heading2']))
     typePresta_data = [self.__typepresta_checkbox()]
     colonnesWidths =    (20, 40, 20, 45, 20, 60, 20, 45, 20, 45, 20, 40, 20, 40, 20, 35, 20, 45)
     #colonnesWidths =    (20, 40, 20, 45, 20, 60, 20, 45, 20, 45, 20, 40, 20, 40)                                                          
     typePresta_style = TableStyle([self.fontsize_style,
                                    ('VALIGN',(1,0),(1,0),'MIDDLE'),
                                    ('VALIGN',(3,0),(3,0),'MIDDLE'),
                                    ('VALIGN',(5,0),(5,0),'MIDDLE'),
                                    ('VALIGN',(7,0),(7,0),'MIDDLE'),
                                    ('VALIGN',(9,0),(9,0),'MIDDLE'),
                                    ('VALIGN',(11,0),(11,0),'MIDDLE'),
                                    ('VALIGN',(13,0),(13,0),'MIDDLE'),
                                    ('VALIGN',(13,0),(13,0),'MIDDLE'),
                                    ('VALIGN',(15,0),(15,0),'MIDDLE'),
                                    ('VALIGN',(17,0),(17,0),'MIDDLE'),
                                    ])
     typePresta_style.spaceAfter = 10
     typePresta_table = Table(data=typePresta_data, colWidths=colonnesWidths, style=typePresta_style)
     self.elements.append(typePresta_table)
Example #18
0
    def _build_spectrum_table_style(self):
        tblstyle = TableStyle([
                               ('SPAN', (0, 0), (-1, 0)),
                               ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                               ('FONTSIZE', (0, 0), (-1, -1), 9),
                               ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                               ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
                               ('LINEBELOW', (0, 1), (-1, 1), 1, colors.black),
#                            ('ALIGN', (2, 0), (2, 0), 'LEFT'),
                               ('LINEBELOW', (0, 3), (-1, 3), 1.5, colors.black),
                               # ('LINEBELOW', (0, 0), (-1, -1), 1, colors.red),

#                               ('LINEBEFORE', (0, 0), (-1, -1), 1, colors.black),
                               ('ALIGN', (2, 0), (-1, -1), 'CENTER')
                              ])

        for ir in self.int_plat_age_rowids:
            tblstyle.add('SPAN', (1, ir), (3, ir))
            tblstyle.add('SPAN', (1, ir + 1), (2, ir + 1))

        for si in self.sample_rowids:
            tblstyle.add('SPAN', (1, si), (-1, si))

        return tblstyle
Example #19
0
    def gather_elements(self, client, node, style):

        # Take the style from the parent "table" node
        # because sometimes it's not passed down.

        if node.parent['classes']:
            style = client.styles.combinedStyle(['table']+node.parent['classes'])
        else:
            style = client.styles['table']
        rows = []
        colWidths = []
        hasHead = False
        headRows = 0
        for n in node.children:
            if isinstance(n, docutils.nodes.thead):
                hasHead = True
                for row in n.children:
                    r = []
                    for cell in row.children:
                        r.append(cell)
                    rows.append(r)
                headRows = len(rows)
            elif isinstance(n, docutils.nodes.tbody):
                for row in n.children:
                    r = []
                    for cell in row.children:
                        r.append(cell)
                    rows.append(r)
            elif isinstance(n, docutils.nodes.colspec):
                colWidths.append(int(n['colwidth']))

        # colWidths are in no specific unit, really. Maybe ems.
        # Convert them to %
        colWidths=map(int, colWidths)
        tot=sum(colWidths)
        colWidths=["%s%%"%((100.*w)/tot) for w in colWidths]

        if 'colWidths' in style.__dict__:
            colWidths[:len(style.colWidths)]=style.colWidths

        spans = client.filltable(rows)

        data = []
        cellStyles = []
        rowids = range(0, len(rows))
        for row, i in zip(rows, rowids):
            r = []
            j = 0
            for cell in row:
                if isinstance(cell, str):
                    r.append("")
                else:
                    if i < headRows:
                        st = client.styles['table-heading']
                    else:
                        st = client.styles['table-body']
                    ell = client.gather_elements(cell, style=st)
                    r.append(ell)
                j += 1
            data.append(r)

        st = TableStyle(spans)
        if 'commands' in style.__dict__:
            for cmd in style.commands:
                st.add(*cmd)
        else:
            # Only use the commands from "table" if the
            # specified class has no commands.

            for cmd in client.styles['table'].commands:
                st.add(*cmd)

        if hasHead:
            for cmd in client.styles.tstyleHead(headRows):
                st.add(*cmd)
        rtr = client.repeat_table_rows

        t=DelayedTable(data, colWidths, st, rtr)
        if style.alignment == TA_LEFT:
            t.hAlign='LEFT'
        elif style.alignment == TA_CENTER:
            t.hAlign='CENTER'
        elif style.alignment == TA_RIGHT:
            t.hAlign='RIGHT'
        return [t]
Example #20
0
        def drawCell():
            """ Drawing a cell text """
            # Finding background
            cellBackground = self.pageObject.get('PCOLOR')
            if cellBackground in self.colorList:
                try:
                    hexCellColor = self.colorList[cellBackground]
                    background = colors.HexColor(str(hexCellColor))
                except:
                    background = colors.HexColor('#ffffff')
            else:
                background = colors.HexColor('#ffffff')
            stile = TableStyle([('ROWBACKGROUNDS', (0,0), (0,0), (background, background))])

            # Borders
            bottomLine = int(self.pageObject.get('BottomLine'))
            topLine = int(self.pageObject.get('TopLine'))
            leftLine = int(self.pageObject.get('LeftLine'))
            rightLine = int(self.pageObject.get('RightLine'))
            lineWidth = float(self.pageObject.get('PWIDTH'))
            borderColor = self.pageObject.get('PCOLOR2')
            alignment = " "
            # Finding value and cell's style
            if self.version:
                paras = self.pageObject.findall('para')
            itexts = self.pageObject.findall('ITEXT')
            ch = ''
            matrix = []
            if len(itexts)>=1:
                if len(itexts)>1:
                    for itext in itexts:
                        chtmp = itext.get('CH')
                        ch = ch +" "+ chtmp
                    itext = itexts[0]
                else:
                    itext = itexts[0]
                    ch = itext.get('CH')
                if self.version:
                    try:
                        alignment = paras[0].get('ALIGN')
                    except:
                        alignment = "0"
                else:
                    alignment = itext.get('CAB')
                if alignment == None:
                    alignment = self.defaultAlignment
                if alignment == '0':
                    alignment = 'LEFT'
                elif alignment == '1':
                    alignment = 'CENTER'
                elif alignment == '2':
                    alignment = 'RIGHT'
                else:
                    alignment = "LEFT"
                stile.add('ALIGN', (0,0), (0,0), alignment)

                # Font Name
                if self.version:
                    fontName = getPdfFontName(str(itext.get('FONT')))
                else:
                    fontName = getPdfFontName(str(itext.get('CFONT')))
                stile.add('FONT', (0,0), (0,0), fontName)

                # Font size
                if self.version:
                    fontSize = float(itext.get('FONTSIZE'))
                else:
                    fontSize = float(itext.get('CSIZE'))
                stile.add('FONTSIZE', (0,0), (0,0), fontSize)

                # Hex color
                if self.version:
                    textColor = itext.get('FCOLOR')
                else:
                    textColor = itext.get('CCOLOR')
                if textColor in self.colorList:
                    try:
                        hexTextColor = self.colorList[textColor]
                        foreground = colors.HexColor(str(hexTextColor))
                    except:
                        foreground = colors.HexColor('#000000')
                else:
                    foreground = colors.HexColor('#000000')
                stile.add('TEXTCOLOR', (0,0), (0,0), foreground)

                # Applying attributes
                if borderColor in self.colorList:
                    try:
                        hexBorderColor = self.colorList[borderColor]
                    except:
                        hexBorderColor = '#000000'
                else:
                    hexBorderColor = '#000000'
                stile.add('VALIGN',(0,0),(-1,-1),'TOP')
                if (bottomLine == 1 and topLine == 1 and leftLine == 1 and rightLine == 1) or (lineWidth > 1):
                    stile.add('BOX', (0,0), (-1,-1), lineWidth, hexBorderColor)
                else:
                    if bottomLine == 1:
                        stile.add('LINEBELOW', (0,0), (-1,-1), lineWidth, hexBorderColor)
                    elif topLine == 1:
                        stile.add('LINEABOVE', (0,0), (-1,-1), lineWidth, hexBorderColor)
                    if leftLine == 1:
                        stile.add('LINEBEFORE', (0,0), (-1,-1), lineWidth, hexBorderColor)
                    if rightLine == 1:
                        stile.add('LINEAFTER', (0,0), (-1,-1), lineWidth, hexBorderColor)

                    # Creating and filling
                    data = []
                    data.append(self.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize))
                    matrix.append(data)
            if len(matrix) > 0:
                table=Table(data=matrix, colWidths=width, rowHeights=height, style=stile)

                # Adding cell to the frame and save it
                lst = []
                lst.append(table)
                f = Frame(x1=(xPos - self.pageProperties[self.pdfPage][9]),
                          y1=(self.pageProperties[0][7] - yPos - height + self.pageProperties[self.pdfPage][10] - 12),
                          width=width,
                          height=(height + 12),
                          showBoundary=0)
                f.addFromList(lst, self.canvas)
                self.canvas.saveState()
Example #21
0
def form_01(direction, iss: Issledovaniya, fwb, doc, leftnone, user=None):
    # Утверждено Приказом Министерства здравоохранения Иркутской области от 22 мая 2013 г. N 83-МПР
    pdfmetrics.registerFont(TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))

    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 11
    style.leading = 12
    style.spaceAfter = 1.5 * mm

    styleBold = deepcopy(style)
    styleBold.fontName = 'PTAstraSerifBold'

    styleCenterBold = deepcopy(style)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.fontSize = 12
    styleCenterBold.leading = 15
    styleCenterBold.fontName = 'PTAstraSerifBold'

    styleT = deepcopy(style)
    styleT.alignment = TA_LEFT
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm
    styleT.face = 'PTAstraSerifReg'

    styleTCentre = deepcopy(styleT)
    styleTCentre.alignment = TA_CENTER
    styleTCentre.fontSize = 13

    data = title_fields(iss)

    opinion = [
        [
            Paragraph(f'<font size=11>{direction.hospital_title}<br/>Адрес: {direction.hospital_address}<br/>ОГРН: {direction.hospital.ogrn} <br/> </font>', styleT),
            Paragraph('<font size=9 >Утверждено<br/>Приказом Министерства здравоохранения<br/>Иркутской области от 22 мая 2013 г. N 83-МПР</font>', styleT),
        ],
    ]

    tbl = Table(opinion, 2 * [100 * mm])
    tbl.setStyle(TableStyle([('GRID', (0, 0), (-1, -1), 0.75, colors.white), ('LEFTPADDING', (1, 0), (-1, -1), 55 * mm), ('VALIGN', (0, 0), (-1, -1), 'TOP')]))

    fwb.append(tbl)
    fwb.append(Spacer(1, 3 * mm))
    fwb.append(Paragraph(f'НАПРАВЛЕНИЕ № {direction.pk}', styleCenterBold))
    fwb.append(Paragraph('в медицинские организации Иркутской области', styleCenterBold))
    fwb.append(Spacer(1, 3 * mm))
    space_symbol = '&nbsp;'
    fwb.append(Paragraph(f'От: {strdate(direction.data_sozdaniya)}', style))
    fwb.append(Paragraph(f'Фамилия, Имя, Отчество: {direction.client.individual.fio()}', style))
    sex = direction.client.individual.sex
    if sex == "м":
        sex = f'{sex}-1'
    else:
        sex = f'{sex}-2'
    born = direction.client.individual.bd().split('.')
    fwb.append(Paragraph(f'Дата <u>{born[0]}</u> Месяц <u>{born[1]}</u> Год рождения <u>{born[2]}</u> Пол {sex} ', style))
    fwb.append(Paragraph(f'Рабочий, домашний телефон : {direction.client.phone}', style))
    polis_num = ''
    polis_issue = ''
    ind_data = direction.client.get_data_individual()
    if ind_data['oms']['polis_num']:
        polis_num = ind_data['oms']['polis_num']
    if ind_data['oms']['polis_issued']:
        polis_issue = ind_data['oms']['polis_issued']
    address = ind_data['main_address']
    fwb.append(Paragraph(f'Регистрация по месту жительства: {address}', style))
    fwb.append(Paragraph(f"Страховой полис серия: _______ №{polis_num}", style))
    fwb.append(Paragraph(f"Страховая компания (наименование): {polis_issue}", style))
    fwb.append(Paragraph(f"Направляется в: {data['Куда направляется']}", style))
    fwb.append(Paragraph("Дата приема _______________________ Время приема _________________", style))
    fwb.append(Paragraph(f"Наименование медицинской организации по месту прикрепления: {direction.hospital_address} {direction.hospital_title}", style))
    fwb.append(Paragraph(f"Наименование направившей медицинской организации: {direction.hospital_address} {direction.hospital_title}", style))
    fwb.append(Paragraph("Направлен(а) на:", style))
    fwb.append(Paragraph("1) консультацию (вписать специалистов)", style))
    if data["Направлен(а) на"] == "Консультацию":
        fwb.append(Paragraph(f"{data['Наименование (консультации, исследования, отделения)']}", styleBold))
    fwb.append(Paragraph("2) исследование (указать вид исследования)", style))
    if data["Направлен(а) на"] == "Исследование":
        fwb.append(Paragraph(f"{data['Наименование (консультации, исследования, отделения)']}", styleBold))
    fwb.append(Paragraph("3) госпитализацию", style))
    if data["Направлен(а) на"] == "Госпитализацию":
        fwb.append(Paragraph(f"{data['Наименование (консультации, исследования, отделения)']}", styleBold))
    fwb.append(Paragraph("Цель консультации (и, или) исследования (нужное обвести):", style))
    descriptive_values = []
    laboratory_value, purpose, table_value = None, None, None
    main_diagnos, near_diagnos, anamnes, other_purpose = '', '', '', ''
    for key, value in data.items():
        if key == "Результаты лабораторные":
            laboratory_value = value
        if key in ["Результаты диагностические", "Результаты консультационные"]:
            descriptive_values.append(value)
        if key == 'Цель':
            purpose = value
        if key == 'Прочие цели':
            other_purpose = value
        if key == 'Диагноз основной':
            main_diagnos = value
        if key == 'Диагноз сопутствующий':
            near_diagnos = f"{near_diagnos} {value}"
        if key == 'Данные анамнеза':
            anamnes = value
    if purpose:
        fwb.append(Paragraph(f"{space_symbol * 10} {purpose} {other_purpose}", style))
    else:
        fwb.append(Paragraph(f"{space_symbol * 10}01 - дообследование при неясном диагнозе;", style))
        fwb.append(Paragraph(f"{space_symbol * 10}02 - уточнение диагноза;", style))
        fwb.append(Paragraph(f"{space_symbol * 10}03 - для коррекции лечения;", style))
        fwb.append(Paragraph(f"{space_symbol * 10}04 - дообследование для госпитализации;", style))
        fwb.append(Paragraph(f"{space_symbol * 10}05 - и прочие цели (нужное вписать) {data['Прочие цели']}", style))
    fwb.append(Paragraph("Диагноз направившей медицинской организации (диагноз/ код диагноза в соответствии с МКБ10):", style))
    if main_diagnos:
        fwb.append(Paragraph(f"Основной {main_diagnos}", style))
    if near_diagnos:
        fwb.append(Paragraph(f"Сопутствующий {near_diagnos}", style))
    else:
        fwb.append(Paragraph("Сопутствующий ______________________________________________________________________________________", style))
    fwb.append(Spacer(1, 3 * mm))
    fwb.append(Paragraph("Выписка из амбулаторной карты:", style))
    fwb.append(Paragraph("(данные анамнеза, клиники, предварительного обследования и проведенного лечения)", style))
    fwb.append(Paragraph(f"{anamnes}", style))
    for v in descriptive_values:
        fwb = previous_doc_refferal_result(v, fwb)
    if laboratory_value:
        lab_values = previous_laboratory_result(laboratory_value)
        if lab_values:
            fwb.extend(lab_values)
    if table_value:
        table_value_result = table_part_result(table_value)
        if table_value_result:
            fwb.extend(table_value_result)

    fwb.append(Paragraph("Сведения о профилактических прививках (для детей до 18 лет) ________________________", style))
    fwb.append(Paragraph(f"{data['Сведения о профилактических прививках']} ", style))
    fwb.append(Paragraph("Справка об отсутствии инфекционных контактов (для детей до 18 лет), выданная не ранее 3 дней на дату поступления в ОГУЗ ", style))
    fwb.append(Paragraph("______________________________________________________________________________________", style))
    doctor_data = "________________________________"
    if data["Врач"]:
        doctor_data = data["Врач"]["fio"]
    fwb.append(Paragraph(f"Врач: {doctor_data}", style))
    fwb.append(Paragraph('телефон ____________________________ "_____" _____________ 20__ г.', style))
    fwb.append(Paragraph(f"Руководитель: направившей медицинской организации {data['Руководитель МО']}", style))
    fwb.append(Paragraph("Согласие пациента на передачу сведений электронной почтой для осуществления предварительной записи и передачи заключения:", style))

    return fwb
Example #22
0
    def Apercu(self):
        """ Impression tableau de données """
        if self.GetNumberRows() == 0 or self.GetNumberCols() == 0 :
            dlg = wx.MessageDialog(self, _(u"Il n'y a rien à imprimer !"), "Erreur", wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return None

        avecCouleurs = True
        
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle

        def ConvertCouleur(couleur):
            r, g, b = couleur[0], couleur[1], couleur[2]
            return r/255.0, g/255.0, b/255.0
        
        # Récupération des données du tableau
        tableau = self
        nbreColonnes = tableau.GetNumberCols()
        nbreLignes = tableau.GetNumberRows()
        
        # Initialisation du tableau
        story = []
        dataTableau = []
        listeCouleurs = []
        
        # Création des colonnes
        largeursColonnes = []
        largeurColonne = 45
        largeurColonneLabel = 90
        for col in range(0, nbreColonnes+1) :
            if col == 0 : largeursColonnes.append(largeurColonneLabel)
            else: largeursColonnes.append(largeurColonne)
        
        listeStyles = [
            ('GRID', (0, 0), (-1, -1), 0.25, colors.black), # Crée la bordure noire pour tout le tableau
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # Centre verticalement toutes les cases
            ('ALIGN', (0, 0), (-1, 0), 'CENTRE'), # Centre les labels de colonne
            ('ALIGN', (1, 1), (-1, - 1), 'CENTRE'), # Valeurs à gauche
            ('ALIGN', (0, 1), (0, -1), 'CENTRE'), # Colonne Label Ligne centrée
            ('FONT', (0, 0), (-1, -1), "Helvetica", 6), # Donne la police de caract. + taille de police de la ligne de total
            ('FONT', (0, 0), (-1, 0), "Helvetica-Bold", 6), # Donne la police de caract. + taille de police de la ligne de total
            ]
        
        # Création de l'entete
        style_label_col = ParagraphStyle(name="label", fontName="Helvetica", alignment=1, fontSize=6, spaceAfter=0, leading=8, spaceBefore=0)
        valeursLigne = ["",]
        for numColonne in range(0, nbreColonnes) :
            labelColonne = tableau.GetColLabelValue(numColonne)
            valeursLigne.append(Paragraph(labelColonne, style_label_col))
        dataTableau.append(valeursLigne)
        
        # Création des lignes
        styleA = ParagraphStyle(name="A", fontName="Helvetica", alignment=1, fontSize=6, leading=7, spaceAfter=0)

        for numLigne in range(0, nbreLignes) :
            labelLigne = tableau.GetRowLabelValue(numLigne)
            valeursLigne = [labelLigne,]
            for numCol in range(0, nbreColonnes) :
                valeurCase = tableau.GetCellValue(numLigne, numCol)
                couleurCase = tableau.GetCellBackgroundColour(numLigne, numCol)
                if couleurCase != (255, 255, 255, 255) and avecCouleurs == True :
                    r, g, b = ConvertCouleur(couleurCase)
                    listeStyles.append( ('BACKGROUND', (numCol+1, numLigne+1), (numCol+1, numLigne+1), (r, g, b) ) )
                # if numLigne == 0 :
                #     valeurCase = valeurCase.replace(" ", "\n")
                # valeursLigne.append(valeurCase)
                valeursLigne.append(Paragraph(valeurCase, styleA))

            dataTableau.append(valeursLigne)

    
        # Style du tableau
        style = TableStyle(listeStyles)
        
        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes,  hAlign='LEFT')
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0,20))
        
        # Calcul du format de la page
        tailleMarge = 20
        if sum(largeursColonnes) > A4[0] - (tailleMarge*2) :
            hauteur, largeur = A4
        else :
            largeur, hauteur = A4

        # Création du titre du document
        dataTableau = []
        largeurContenu = largeur - (tailleMarge*2)
        largeursColonnes = ( (largeurContenu-100, 100) )
        dateDuJour = DateEngFr(str(datetime.date.today()))
        dataTableau.append( (_(u"Synthèse des déductions"), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour)) )
        style = TableStyle([
                ('BOX', (0,0), (-1,-1), 0.25, colors.black), 
                ('VALIGN', (0,0), (-1,-1), 'TOP'), 
                ('ALIGN', (0,0), (0,0), 'LEFT'), 
                ('FONT',(0,0),(0,0), "Helvetica-Bold", 16), 
                ('ALIGN', (1,0), (1,0), 'RIGHT'), 
                ('FONT',(1,0),(1,0), "Helvetica", 6), 
                ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.insert(0, tableau)
        story.insert(1, Spacer(0, 10))       
        
        # Insertion du label Paramètres
        styleA = ParagraphStyle(name="A", fontName="Helvetica", fontSize=6, spaceAfter=20)
        story.insert(2, Paragraph(self.labelParametres, styleA))       

        # Enregistrement du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("SYNTHESE_DEDUCTIONS", "pdf")
        if sys.platform.startswith("win") : nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, pagesize=(largeur, hauteur), leftMargin=tailleMarge, rightMargin=tailleMarge, topMargin=tailleMarge, bottomMargin=tailleMarge)
        doc.build(story)
        
        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
def pdf_generator(snp_id,datetime,owner,NRIC,newOwner,agreed_price,owner_address,new_owner_address,interest_rate,RPGT,company,property_description,house_title,sold_house_address,master_title,charge_or_assign):

    doc = SimpleDocTemplate(snp_id+".pdf",rightMargin=72,leftMargin=72,
                        topMargin=72,bottomMargin=18)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    Story=[]
    logo = "static/img/logo.svg"
    im   =  Image(logo, 2*inch, 2*inch)

    ptext = '<font size=11><b>AN AGREEMENT</b> made on %s</font>' %datetime
    Story.append(Paragraph(ptext,styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = '<font size=11>BETWEEN</font>'

    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))

    ptext = '<font size=11>The individual(s)/entity(ies) whose particulars are set out in <b> Item B of Schedule 1 </b>hereto (hereinafter individually/collectively referred to as "<b>the Vendor</b>" of the one part;</font>'
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = '<font size=11>AND</font>'
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = '<font size=11><b>%s </b> with its registered address at %s (hereinafter referred to as "<b>the Purchaser</b>" of the other part</font> '
    ptext =  ptext %(newOwner,new_owner_address)
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext ='<font size=11><b>WHEREAS</b></font>'
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))

    ptext1  = "<font size=11>It is the Vendor's presentation that he/she/it is the legal and beneficial owner of the property described in <b>Item C of Schedule 1 </b> hereto (hereinafter referred to as ""<b>the said Property</b>"").""</font>"
    ptext2  = "<font size=11>It is the Vendor’s representation that the said Property is free from any encumbrances save and except as described in Item D of Schedule 1 (if applicable).</font>"
    ptext3  = "<font size=11>The Vendor has agreed to sell and the Purchaser has agreed to purchase the said Property with vacant possession on an “as is where is basis” and free from all encumbrances and upon the terms and conditions hereinafter appearing.</font>"
    ptext4  = "<font size=11>The Vendor elects not to be represented by any solicitors and the Purchaser is represented by Messrs L P Gee & Co. in this sale and purchase transaction.</font>"
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    ptext_4 = Paragraph(ptext4, styles['Justify'])
    able    = [['1. ',ptext_1],['2. ',ptext_2],['3. ',ptext_3],['4. ',ptext_4]]
    t       = Table(able,(1*cm,15*cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><b>NOW THIS AGREEMENT WITNESSETH </b> as follows:- </font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>.  <b>AGREEMENT TO SELL AND PURCHASE</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>In consideration of the terms and considerations of this Agreement and Purchase Price as set out in <b>Item 2A of Schedule 2 herein</b> (hereinafter referred to as “<b>the Purchase Pric</b>”), the Vendor hereby agrees to sell and the Purchaser hereby agrees to purchase the said Property free from all encumbrances and with vacant possession on an “as is where is basis” together with Fixtures and Fittings. </font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(PageBreak())
    ptext = "<font size=11><seq>.  <b>AGREEMENT TO SELL AND PURCHASE</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11> The Purchaser shall pay the Purchase Price [where applicable, less any Redemption Sum payable to the Vendor’s Chargee/Assignee, outstanding Quit Rent and/or Assessments, outstanding maintenance charges, outstanding utilities and any other deductions as may be agreed between the Vendor and Purchaser (collectively referred to as “<b>Deductions</b>”)] to the Vendor on or before the date stipulated in <b>Item 2B of Schedule 2</b> hereto (hereinafter referred to as “<b>Completion Date</b>”) <b>PROVIDED THAT</b>:</font>"
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    able    = [['(a) ', ptext_1]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11>the Vendor has deposited with the Purchaser’s Solicitors all necessary valid instruments and documents to complete the sale and purchase transaction herein including but not limited to the original individual title for the Property and Memorandum of Transfer (if applicable); original application form for authority’s consent for transfer (if applicable); original previous Sale and Purchase Agreement(s) and Deed(s) of Assignment together with original ‘Sijil Setem’ and ‘Notis Taksiran’ (if applicable); certified true copy of Vendor’s identity card / Company Forms 24, 44 and 49, Memorandum of Articles & Association and Shareholders’ Resolution for the sale; current Quit Rent and Assessment Receipts and all other documents required by the Purchaser;</font>"
    ptext2  = "<font size=11>Where applicable, all necessary instruments and documents from the Vendor’s Chargee/Assignee including but not limited to Redemption Statement, duly executed and stamped Discharge of Charge / duly executed and stamped Deed of Receipt and Reassignment, duly revoked Power of Attorney and all other related documents;</font>"
    ptext3  = "<font size=11>Legal / Vacant possession of the Property is delivered to the Purchaser simultaneously with the payment of the Purchase Price (less Deductions). </font>"
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    able    = [[' ','i)', ptext_1],[' ','ii)', ptext_2],[' ','iii)', ptext_3]]
    t       = Table(able, (2 * cm, 0.5 * cm,15*cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (2, 2), 0.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 0.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>. <b>MEMORANDUM OF TRANSFER / DEED OF ASSIGNMENT</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11> The parties hereby undertake to perform and comply with the requirements to be fulfilled by them on their part for the execution of the Memorandum of Transfer [“<b>MOT</b>”] / Deed of Assignment by way of Transfer [“<b>DOA</b>”] where applicable, in favour of the Purchaser. Upon the execution of the MOT / DOA, the MOT / DOA shall be held by the Purchaser’s Solicitors who are irrevocably authorized to submit the MOT / DOA for adjudication at the appropriate time subject to the instructions of the Purchaser.</font>"
    ptext2  = "<font size=11>Upon the MOT / DOA being adjudicated, the Purchaser shall pay the stamp duty thereon upon being informed by the Purchaser’s Solicitors.</font>"
    ptext3  = "<font size=11>For the avoidance of doubt, notwithstanding the reference of “Completion Date” in this Agreement, this sale and purchase transaction is not and shall not be deemed complete unless and until the Memorandum of Transfer is registered in favour of the Purchaser.   </font>"
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    able    = [['(a) ', ptext_1],['(b) ',ptext_2],['(c) ',ptext_3]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>.  <b>DELIVERY OF DOCUMENTS</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>Notwithstanding anything to the contrary in the event that the Vendor fails to deliver the documents in Clause 2(a) and any other documents required by the Purchaser, the obligation of the Purchaser to pay the Purchase Price (less Deductions) shall be automatically suspended and the Completion Date shall accordingly be extended by such number of days of delay by the Vendor in performing the above covenants without any interest being payable by the Purchaser whatsoever but without prejudice to the other rights of the Purchaser against the Vendor at law and/or in equity. </font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(PageBreak())
    ptext = "<font size=11><seq>.  <b>DEFAULT BY PURCHASER</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>It is hereby agreed between the parties hereto that if the Purchaser fail to pay the Purchase Price and the Vendor are willing, able and ready to complete the sale of the said Property in accordance with the terms of this Agreement, the Vendor shall the right to terminate this Agreement by giving 14 days written notice to the Purchaser. Upon the termination of the Agreement by the Vendor, the Purchaser shall return to the Vendor all documents furnished by the Vendor including original individual document of title and all instruments executed for the purposes of this Agreement shall be null and void. Thereafter, neither party hereto shall have any claims against the other, and the Vendor shall be at liberty to re-sell the said Property in such manner as the Vendor shall think fit. </font>"
    Story.append(Paragraph(ptext,styles['Justify']))
    Story.append(Spacer(1,11))
    ptext = "<font size=11><seq>.  <b>DEFAULT BY VENDOR</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>It is also further agreed between the parties hereto that if the Purchaser have or is able, ready and willing to pay the Purchase Price (less Deductions) and the Vendor fails and/or is unable and/or refuse to complete the sale in accordance with the terms of this Agreement, the Purchaser shall be entitled to either:-</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11>specific performance and/or other legal remedies available to them; OR </font>"
    ptext2  = "<font size=11>terminate this Agreement and demand the return of all monies so paid by the Purchaser to the Vendor or on account of the Vendor pursuant to this Agreement and the Vendor hereby further agrees and shall in addition pay to the Purchaser a further sum of Ringgit Malaysia Twenty Thousand (RM20,000-00) only absolutely as agreed liquidated damages failing which the Vendor shall pay interest at the rate of %s per annum calculated on a daily basis on any part of the sums remaining unrefunded and unpaid to the Purchaser from the date of demand until the full refund is made to the Purchaser. After such refund and payment, this Agreement shall become null and void with each party having no claim whatsoever against the other.</font>"
    ptext2  = ptext2 %interest_rate
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    able    = [['(a) ', ptext_1],['(b) ',ptext_2]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>.  <b>PASSING OF INTEREST IN THE PROPERTY</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>The Vendor hereby expressly agrees and confirms that as from the date of the Purchaser depositing the Purchase Price (less Deductions) with the Vendor, he shall have no right, title, interest or anything whatsoever in and to the said Property and the Vendor hereby expressly further acknowledges that as from the date thereof the Purchaser is the person entitled to the legal and equitable title and interest in and to the said Property.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>.  <b>DELIVERY OF VACANT POSSESSION</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>The Vendor shall deliver vacant possession of the said Property on an “as is where is basis” to the Purchaser in the state and condition as at the date of this Agreement, simultaneously with the payment of the Purchase Price (less Deductions) to the Vendor.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>.  <b>NON-REGISTRATION OF DOCUMENTS</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11>Without prejudice to Clause 6, if after completion of this Agreement, the Memorandum of Transfer of the said Property cannot be registered in favour of the Purchaser free from all encumbrances by any reason whatsoever including but not limited to any caveat, prohibitory orders or other encumbrances save for any caveats prohibitory orders or encumbrances lodged or entered by Purchaser or any one lawfully claiming through the Purchaser, it shall be the duty of the Vendor to remove or cause to be removed forthwith at the Vendor’s own cost and expense such reason of obstruction including but not limited to caveat, prohibitory orders, or other encumbrances in order to enable the Purchaser to be registered as proprietor free from all encumbrances. </font>"
    ptext2  = "<font size=11>In the alternative, the Purchaser shall be entitled at their option to request the Vendor to refund all monies paid to the Vendor or in favour of the Vendor pursuant to this Agreement free of interest within Seven (7) days of demand whereupon the Vendor shall make such refund within the said Seven (7) days failing which the Vendor shall pay interest at the rate of %s per annum calculated on a daily basis on all monies remaining unrefunded to the Purchaser from the expiry of the said Seven (7) working days until the full refund is made to the Purchaser and thereafter this Agreement shall be treated as terminated.</font>"
    ptext2  = ptext2 % interest_rate
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    able    = [['(a) ', ptext_1], ['(b) ', ptext_2]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>.  <b>REAL PROPERTY GAINS TAX</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11>Each party shall respectively notify the Director-General of Inland Revenue, Malaysia (hereinafter referred as “the Director General”) of the acquisition and disposal of the said Property within sixty (60) days from the date of this Agreement. </font>"
    ptext2  = "<font size=11>If applicable, the Purchaser agrees to pay on behalf of the Sum amounting to %s of the Purchase Price to be paid to the Director General of Inland Revenue in accordance with the provisions of the Real Property Gains Tax Act, 1976, and the difference between the total tax imposed by the Director General and the said Sum upon receipt of the notice of assessment from the Director General within the period prescribed therein. </font>"
    ptext3  = "<font size=11>Upon the issuance by the Director-General of a Certificate of Clearance or a Certificate of Non-Chargeability or payment of the Real Property Gains Tax, as the case maybe, any excess payment derived from the said Sum after the deduction of any real property gains tax imposed by the Director General shall be refunded to the Purchaser.</font>"
    ptext2  = ptext2 % RPGT
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    able    = [['(a) ', ptext_1], ['(b) ', ptext_2],['(c) ',ptext_3]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>.  <b>GOVERNMENT ACQUISITION</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11>The Vendor hereby covenant with the Purchaser that he/she/it has not received any notice from the Government or any proper authorities having power in that behalf to acquire the said Property or any part or parts thereof.</font>"
    ptext2  = "<font size=11>It is hereby agreed between the parties hereto that in the event of the Government or any proper Authorities having power on that behalf acquiring the said Property or any part or parts thereof for any purpose whatsoever after the date of this Agreement and before the Purchase Price has been paid to the Vendor, the Vendor shall immediately by writing notify the Purchaser upon receiving notice of such intended acquisition or declaration and the Purchaser shall forthwith be entitled by notice in writing to the Vendor, elect:-</font>"
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    able    = [['(a) ', ptext_1], ['(b) ', ptext_2]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext1  = "<font size =11>to rescind this Agreement whereupon the Vendor shall within Fourteen (14) working days from the date of receipt of the Purchaser’ notice refund to the Purchaser free of interest all monies already paid by the Purchaser to the Vendor pursuant to this Agreement and the Purchaser failing which the Vendor shall pay interest at the rate of %s per annum calculated on a daily basis on all monies remaining unrefunded to the Purchaser from the expiry of the said Fourteen (14) working days until the full refund is made to the Purchaser and thereafter this Agreement shall be terminated and shall be null and void and of no effect or force and neither party hereto shall have any further right against the other save and except for any antecedent breach of this Agreement; or</font>"
    ptext2  = "<font size =11>require the Vendor to serve notice upon such authority within Fourteen (14) working days from the date of receipt of the Purchaser’ election of the Purchaser’ interest in the said Property under the terms and conditions of this Agreement and thereafter the Purchaser shall be absolutely entitled to the whole of the benefit of any arrangement made or the compensation (if any) awarded by such acquiring authority in respect of such acquisition and the Vendor shall do all acts and things and execute and sign all documents to enable the Purchaser to procure such arrangement or compensation Provided Always That the Purchaser shall have paid the Purchase Price (less Deductions) in accordance with the terms herein. </font>"
    ptext1  = ptext1 % interest_rate
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    able    = [[' ', '(i)', ptext_1], [' ', '(ii)', ptext_2]]
    t       = Table(able, (2 * cm, 0.5 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (2, 2), 0.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 0.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11><seq>.  <b> RISK AGAINST FIRE AND OTHER HAPPENINGS</b></font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>The parties hereto agree that in the event that the said Property is destroyed by fire or other happenings beyond the control of the Vendor before vacant possession of the said Property is delivered to the Purchaser, the Purchaser shall have the option to treat this Agreement as terminated whereupon the Vendor shall refund to the Purchaser all the monies paid to the Vendor or on account of the Vendor pursuant to this Agreement without any interest thereon failing which the Vendor shall pay interest at the rate of %s per annum calculated on a daily basis on any part of the sums remaining unrefunded to the Purchaser from the date of demand until the full refund is made to the Purchaser whereupon this Agreement shall be terminated.</font>"
    ptext = ptext % interest_rate
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>  <b> APPORTIONMENT OF QUIT RENT, ASSESSMENT AND OTHER LAWFUL OUTGOINGS</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['13. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11>The quit rent, assessment, and other lawful outgoings payable in respect of the said Property to the relevant authorities shall be apportioned between the Vendor and the Purchaser as at the date of delivery of vacant possession to the Purchaser. The Vendor shall also indemnify the Purchaser in respect of any penalty imposed in respect of any late payment by the Vendor in respect of such quit rent, assessment and other lawful out goings.</font>"
    ptext2  = "<font size=11>The Purchaser hereby agree to pay all the lawful outgoings payable to the relevant authorities in respect of the said Property from the date vacant possession of the said Property is delivered to the Purchaser.</font>"
    ptext3  = "<font size=11>Upon completion of the sale and purchase herein and the delivery of vacant possession of the said Property to the Purchaser, the Purchaser shall take all necessary steps to notify the relevant authorities of the change of ownership of the said Property so that all future bills in respect of quit rents, assessment rates, sewerage and utility charges and all other lawful whatsoever in respect of the said Property will be directed to the Purchaser. The Purchaser shall indemnify and keep the Vendor indemnified in respect of all losses, damages, fines and penalties arising from the Purchaser’s breach of this Clause and/or from late payment or non-payment of all quit rent, assessment, water, electricity and indah water charges payable in respect of the said Property from the date vacant possession of the said Property is delivered to the Purchaser.</font>"
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    able    = [['(a) ', ptext_1], ['(b) ', ptext_2], ['(c) ', ptext_3]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    Story.append(PageBreak())
    ptext = "<font size=11><b>LODGEMENT OF PRIVATE CAVEAT</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['14. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11> At any time after the date hereof, the Purchaser shall be entitled at their own cost and expense to present and register a private caveat against the Property for the purpose of protecting the Purchaser’s interest in the Property and prohibiting any dealing by the Vendor in the Property prior to the completion or termination of this Agreement <b>PROVIDED FURTHER THAT</b> the Purchaser shall simultaneously execute a withdrawal of private caveat and deposit the same together with the requisite registration fees with the Purchaser’s Solicitors who are hereby authorized by the Purchaser to remove or cause to be removed the aforesaid private caveat upon lawful termination of this Agreement.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>  <b> COSTS AND EXPENSES</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['15. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>The Purchaser shall bear the costs for this Sale and Purchase Agreement. The costs for attending to the Memorandum of Transfer together with the stamp duties and registration fees thereof, inclusive of penalty, if any, thereof shall be borne and paid by the Purchaser.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>  <b> KNOWLEDGE OR ACQUIESCENCE</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['16. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>Knowledge or acquiescence of either party hereto of or in any breach of any of the conditions or covenants herein contained shall not operate as or be deemed to be a waiver of such conditions or covenants or any of them and notwithstanding such knowledge or acquiescence each party hereto shall be entitled to exercise their respective rights under this Agreement and to require strict performance by the other of the terms and conditions herein. </font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>  <b> SEVERABILITY</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['17. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>If any one or more of the provisions contained in this Agreement shall be invalid or unenforceable in any respect the legality and enforceability of the remaining provisions contained herein shall not in any way be affected or impaired.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>  <b> HEADINGS</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['18. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>The headings of each of the Clauses herein contained are inserted merely for convenience of reference and shall be ignored in the interpretation and construction of any of the provisions herein contained. </font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))

    ptext = "<font size=11>  <b> TIME OF THE ESSENCE</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['19. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>Time whenever mentioned shall be of the essence of this Agreement.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>  <b> SUCCESSORS BOUND</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['20. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>This Agreement shall be binding upon the successors-in-title legal representatives, administrators, nominees and permitted assigns of the parties hereto.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(PageBreak())
    ptext = "<font size=11>  <b> SERVICE OF NOTICE OR DEMAND</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['21. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>Any notice, request or demand requiring to be served by either party hereto to the other under the provisions of this Agreement shall be in writing and shall be deemed to be sufficiently served:-</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11>if it is given by the party or his solicitors by post under registered cover addressed to the other party to be served at his or its address hereinbefore mentioned or to his solicitors and in such a case it shall be deemed (whether actually delivered or not) to have been served at the time of posting of the notice; or </font>"
    ptext2  = "<font size=11>if it is given by the party or his or solicitors and despatched by hand to the party to be served or his solicitors; or</font>"
    ptext3  = "<font size=11>if given by facsimile it shall be deemed served to the other party or his solicitors when the transmitting machine registers the confirmation that the transmission has been successfully made showing the recipient’s facsimile number on the sender’s receipt of a confirmed log print-out for the transmission regarding the date time and transmission of all pages and shall be addressed to the parties or their solicitors or such address as any of the parties may designate from time to time.</font>"
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    able    = [['(i) ', ptext_1], ['(ii) ', ptext_2], ['(iii) ', ptext_3]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>  <b> NOTIFICATION OF CHANGE OF OWNERSHIP OF THE SAID PROPERTY</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['22. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>The Purchaser and the Vendor shall where necessary inform all relevant authorities of the change of ownership of the said Property after completion of the sale and purchase herein at their cost and expense. It is hereby agreed that it shall not be the responsibility of the Purchaser’s Solicitors to perform any of the foregoing matters.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    ptext = "<font size=11>  <b> INTERPRETATION</b></font>"
    ptext = Paragraph(ptext, styles['Justify'])
    able  = [['23. ', ptext]]
    t     = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    ptext   = "<font size=11>In this Agreement unless there is something in the subject or context inconsistent with such construction or unless it is otherwise expressly provided:-</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    ptext1  = "<font size=11>the expression “the Vendor” and “the Purchaser” shall include their respective successors personal representatives and assigns of the Vendor and the Purchaser and where two or more persons are included in any of the aforesaid expression this Agreement binds such persons jointly and severally;</font>"
    ptext2  = "<font size=11>words importing the masculine gender only include the feminine and neuter genders;</font>"
    ptext3  = "<font size=11>words importing the singular number only include the plural and vice versa;</font>"
    ptext4  = "<font size=11>words applicable to human beings include any body of persons corporate or unincorporate; </font>"
    ptext5  = "<font size=11>the phrase “working day” shall exclude Saturdays, Sundays, public holidays and state holidays in Selangor and/or Kuala Lumpur; and </font>"
    ptext6  = "<font size=11>	the word “month” shall mean the period of time which ends on the same date as it commenced in the previous month but if there is no numerically corresponding date in the following month, then the period shall end on the last day of the month PROVIDED ALWAYS that if the Completion Date falls on a non-working day, then the period shall end on the next working day. </font>"
    ptext_1 = Paragraph(ptext1, styles['Justify'])
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    ptext_4 = Paragraph(ptext4, styles['Justify'])
    ptext_5 = Paragraph(ptext5, styles['Justify'])
    ptext_6 = Paragraph(ptext6, styles['Justify'])
    able    = [['(a) ', ptext_1],['(b) ', ptext_2],['(c) ', ptext_3],['(d) ', ptext_4],['(e) ', ptext_5],['(f) ', ptext_6]]
    t       = Table(able, (1 * cm, 15 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (0, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
    ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    Story.append(PageBreak())
    ptext   = "<font size=11> (The rest of this page has been intentionally left blank)</font>"
    ptext_1 = Paragraph(ptext, styles['Justify'])
    able    = [[' ', ptext_1, ' ']]
    t       = Table(able, (5 * cm, 15 * cm, 1 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ('GRID', (0, 0), (2, 2), 0.50, colors.white, None, (2, 2, 1)),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 0.50, colors.white),
    ]))
    Story.append(t)
    Story.append(PageBreak())
    ptext = "<font size=11><b>IN WITNESS WHEREOF</b> the parties hereto have hereunto set their respective hands/seal the day and year first abovewritten.</font>"
    Story.append(Paragraph(ptext, styles['Justify']))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))

    ptext   = "<font size=11>   Signed by</font>"
    ptext   = Paragraph(ptext, styles['Justify'])
    ptext1  = "<font size=11>the above mentioned Purchaser</font>"
    ptext_1 = Paragraph(ptext1,styles['Normal'])
    ptext2  = "<font size=11>in the presence of : </font>"
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext3  = "<font size=11>Name: <b>%s</b></font>"
    ptext3  = ptext3 % owner
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    ptext4  = "<font size=11>NRIC No: <b>%s</b></font>"
    ptext4  = ptext4 % NRIC
    ptext_4 = Paragraph(ptext4, styles['Justify'])
    able    = [[ptext, ")"," "],[" ",")"," "],[ptext_1,")"," "],[ptext_2,")","....................................................."],[" "," ",ptext_3],[" "," ",ptext_4]]
    t       = Table(able, (6 * cm, 2 * cm,7 * cm))
    t.setStyle(TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
        ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    if company!="":
        ptext   = "<font size=11>   The Common Seal of the</font>"
        ptext   = Paragraph(ptext, styles['Justify'])
        ptext1  = "<font size=11>abovenamed Vendor (a Company)</font>"
        ptext_1 = Paragraph(ptext1, styles['Normal'])
        ptext2  = "<font size=11>is hereunto affixed </font>"
        ptext_2 = Paragraph(ptext2, styles['Justify'])
        ptext3  = "<font size=11>in the presence of :-</font>"
        ptext_3 = Paragraph(ptext3, styles['Justify'])
        able    = [[ptext, ")", " "], [ptext_1, ")", " "], [ptext_2, ")", " "],[ptext_3, ")", ""]]
        t       = Table(able, (6 * cm, 2 * cm, 7 * cm))
        t.setStyle(TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
        ]))
        Story.append(t)
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        Story.append(Spacer(1, 11))
        ptext   = "<font size=11>   Signed by</font>"
        ptext   = Paragraph(ptext, styles['Justify'])
        ptext1  = "<font size=11><b>%s</b></font>"
        ptext1  = ptext1 % company
        ptext_1 = Paragraph(ptext1, styles['Normal'])
        ptext2  = "<font size=11>the above mentioned Purchaser </font>"
        ptext_2 = Paragraph(ptext2, styles['Justify'])
        ptext3  = "<font size=11>in the presence of :-</font>"
        ptext_3 = Paragraph(ptext3, styles['Justify'])
        able    = [[ptext, ")", " "], [ptext_1, ")", " "], [ptext_2, ")", " "],['',')',''],[ptext_3, ")", ""]]
        t       = Table(able, (6 * cm, 2 * cm, 7 * cm))
        t.setStyle(TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
        ]))
        Story.append(t)

    ptext = "<font size=11>   Signed by</font>"
    ptext = Paragraph(ptext, styles['Justify'])
    ptext1 = "<font size=11>the above mentioned Vendor</font>"
    ptext_1 = Paragraph(ptext1, styles['Normal'])
    ptext2 = "<font size=11>in the presence of : </font>"
    ptext_2 = Paragraph(ptext2, styles['Justify'])
    ptext3 = "<font size=11>Name: <b>%s</b></font>"
    ptext3 = ptext3 % newOwner
    ptext_3 = Paragraph(ptext3, styles['Justify'])
    ptext4 = "<font size=11>NRIC No: <b>%s</b></font>"
    ptext4 = ptext4 % NRIC
    ptext_4 = Paragraph(ptext4, styles['Justify'])
    able = [[ptext, ")", " "], [" ", ")", " "], [ptext_1, ")", " "],
                [ptext_2, ")", "....................................................."], [" ", " ", ptext_3],
                [" ", " ", ptext_4]]
    t = Table(able, (6 * cm, 2 * cm, 7 * cm))
    t.setStyle(TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('GRID', (0, 0), (-1, -1), 1.50, colors.white, None, (2, 2, 1)),
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('BOX', (0, 0), (-1, -1), 1.50, colors.white),
        ]))
    Story.append(t)
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    Story.append(Spacer(1, 11))
    Story.append(PageBreak())
    Story.append(PageBreak())
    ptext = "<font size=11><u>Schedule 1</u></font>"
    Story.append(Paragraph(ptext, styles['title']))
    Story.append(Spacer(1, 11))

    ptext    = "<font size=11><b>Item</b></font>"
    ptext    = Paragraph(ptext, styles['Justify'])
    ptext11  = "<font size=11><b>Particulars</b></font>"
    ptext_11 = Paragraph(ptext11, styles['Justify'])
    ptext1   = "<font size=11><b>1A</b></font>"
    ptext_1  = Paragraph(ptext1, styles['Justify'])
    ptext2   = "<font size=11><b>1B</b></font>"
    ptext_2  = Paragraph(ptext2, styles['Justify'])
    ptext3   = "<font size=11><b>1C</b></font>"
    ptext_3  = Paragraph(ptext3, styles['Justify'])
    ptext4   = "<font size=11><b>1D</b></font>"
    ptext_4  = Paragraph(ptext4, styles['Justify'])
    ptext5   = "<font size=11>The Property is Charged or Assigned to</font>"
    ptext_5  = Paragraph(ptext5,styles['Justify'])
    ptext6   = "<font size=11>Chargee/Assignee: </font>"
    if charge_or_assign !='':
        ptext6 = ptext6 + '%s'
        ptext6 = ptext6 % charge_or_assign
    else:
        ptext6 = ptext6 + 'NIL'
    ptext_6    = Paragraph(ptext6,styles['Justify'])
    word =''

    word = word + '<br/><br/><font size=11><b>%s <br/>%s</b></font><br/>'
    word = word % (owner, NRIC)
    word = 'Name:'+word+'<br/>Address:<br/> '+'<br/><b> %s<br/></b>'
    word = word %(owner_address)
    ptext_10 = Paragraph(word,styles['Justify'])
    the_property_description ='<font size=11>Postal Address: <br/><br/><b>%s</b><br/><br/><br/>Description: <b>%s</b><br/><br/><br/>Held under Title (if individual title has been issued):<br/><br/><br/><b>%s</b><br/><br/>Built thereon Master Title (if individual title has not been issued):<br/><br/></font>'
    the_property_description = the_property_description %(sold_house_address,property_description,house_title)
    if master_title!='':
        the_property_description = the_property_description +'<b>%s</b>'
        the_property_description = the_property_description %master_title
    the_property_description     =  Paragraph(the_property_description,styles['Justify'])
    able = [[ptext, "", ptext_11 ], [ptext_1, "Date of Agreement", " "], [ptext_2, "Vendor", ptext_10], [ptext_3, 'Property', the_property_description],
            [ptext_4,ptext_5 , ptext_6]]
    t    = Table(able, (2.5* cm, 5 * cm, 7 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('INNERGRID', (0, 0), (-1, -1), 0.3, colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.black),
    ]))
    Story.append(t)
    Story.append(PageBreak())
    ptext = "<font size=11><u>Schedule 2</u></font>"
    Story.append(Paragraph(ptext, styles['title']))
    Story.append(Spacer(1, 11))
    ptext1     = "<font size=11><b>Item</b></font>"
    ptext_1    = Paragraph(ptext1,styles['Title'])
    ptext2     = "<font size=11><b>Particulars</b></font>"
    ptext_2    =  Paragraph(ptext2,styles['Title'])
    ptext3     = "<font size=11><b>2A</b></font>"
    ptext_3    = Paragraph(ptext3, styles['Title'])
    ptext4     = "<font size=11><b>2B</b></font>"
    ptext_4    = Paragraph(ptext4, styles['Title'])
    theword    = num2words(float(agreed_price))
    word_upper = theword.title()
    new_price  = "RM{:,.2f}".format(int(agreed_price))
    ptext5     = "<font size=10>%s<br/><br/> (Ringgit Malaysia: %s only)</font>"
    ptext5     = ptext5 % (new_price,word_upper)
    ptext_5    = Paragraph(ptext5, styles['Normal'])
    ptext6     = "<font size=10>Date: </font>"
    ptext_6    = Paragraph(ptext6, styles['Normal'])
    able       = [[ptext_1,'',ptext_2],[ptext_3,'Purchase Price',ptext_5],[ptext_4,'Completion Date',ptext_6]]
    t          = Table(able, (2.5 * cm, 5 * cm, 7 * cm))
    t.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('INNERGRID', (0, 0), (-1, -1), 0.3, colors.black),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('BOX', (0, 0), (-1, -1), 1.50, colors.black),
    ]))
    Story.append(t)


    doc.build(Story, canvasmaker=PageNumCanvas)
Example #24
0
        def build_parts(account, enddate, isdom=None, daterange=None):
            "build parts"
            parts = []
            sentry = 0
            for report in reports:
                column = report[0]
                exclude_kwargs = report[1]
                order_by = "-%s" % report[2]
                order = report[2]
                title = report[3]

                if isdom:
                    #dom
                    data = Message.objects.values(column).\
                    filter(Q(from_domain=account.address) | \
                    Q(to_domain=account.address)).\
                    exclude(**exclude_kwargs).annotate(
                        num_count=Count(column), total_size=Sum('size')
                    ).order_by(order_by)
                    if daterange:
                        data.filter(date__range=(daterange[0], daterange[1]))
                    elif enddate:
                        data.filter(date__gt=enddate)
                    data = data[:10]
                else:
                    #all users
                    data = Message.report.all(user, enddate, daterange).values(
                            column).exclude(**exclude_kwargs).annotate(
                            num_count=Count(column), total_size=Sum('size')
                            ).order_by(order_by)
                    data = data[:10]

                if data:
                    sentry += 1
                    pgraphs = build_chart(data, column, order, title)
                    parts.extend(pgraphs)
                    parts.append(Spacer(1, 70))
                    if (sentry % 2) == 0:
                        parts.append(PageBreak())
            parts.append(Paragraph(_('Message Totals'), styles['Heading1']))
            if isdom:
                #doms
                msg_totals = MessageTotals.objects.doms(account.address, enddate)
            else:
                #norm
                filters = []
                addrs = [
                    addr.address for addr in UserAddresses.objects.filter(
                        user=account
                    ).exclude(enabled__exact=0)]
                if enddate:
                    efilter = {
                                'filter': 3,
                                'field': 'date',
                                'value': str(enddate)
                               }
                    filters.append(efilter)
                msg_totals = MessageTotals.objects.all(
                                account, filters, addrs,
                                profile.account_type,
                                daterange)

            mail_total = []
            spam_total = []
            virus_total = []
            dates = []
            if include_daily:
                rows = [(
                Table([[draw_square(colors.white),
                Paragraph('Date', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch, ]),
                Table([[draw_square(colors.green),
                Paragraph('Mail totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch, ]),
                Table([[draw_square(colors.pink),
                Paragraph('Spam totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch, ]),
                Table([[draw_square(colors.red),
                Paragraph('Virus totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch, ]),
                )]
            for ind, msgt in enumerate(msg_totals):
                if ind % 10:
                    dates.append('')
                else:
                    dates.append(str(msgt.date))

                mail_total.append(int(msgt.mail_total))
                spam_total.append(int(msgt.spam_total))
                virus_total.append(int(msgt.virus_total))
                if include_daily:
                    rows.append((str(msgt.date), msgt.mail_total,
                    msgt.spam_total, msgt.virus_total))

            graph = BarChart()
            graph.chart.data = [
                    tuple(mail_total), tuple(spam_total),
                    tuple(virus_total)
                ]
            graph.chart.categoryAxis.categoryNames = dates
            graph_table = Table([[graph]], [7.4 * inch])
            parts.append(graph_table)
            if include_daily:
                rows.append(('Totals', sum(mail_total), sum(spam_total),
                sum(virus_total)))
                parts.append(Spacer(1, 20))
                graph_table = Table(rows, [1.85 * inch, 1.85 * inch,
                1.85 * inch, 1.85 * inch, ])
                graph_table.setStyle(TableStyle([
                ('FONTSIZE', (0, 0), (-1, -1), 8),
                ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                ('GRID', (0, 0), (-1, -1), 0.15, colors.black),
                ('FONT', (0, -1), (-1, -1), 'Helvetica-Bold'),
                #('BACKGROUND', (0, -1), (-1, -1), colors.green),
                ]))
                parts.append(graph_table)
            return parts
Example #25
0
def make_party_list_table(elements, styles, party_results):

    table_style = TableStyle([('FONT', (0, 0), (-1, -1), DEFAULT_FONT)])
    t = Table(party_results, style=table_style)
    elements.append(t)
Example #26
0
        [1177,'2017-08-04' ,18.29, u'Medellín',      82.30, u'Caldas'   ]]


t=Table(data,[1*inch,2*inch,1.5*inch,1.5*inch,1.5*inch,1.5*inch], len(data)*[0.4*inch])
pdf_rep1.setFillColorRGB(color_RGB1[0]/255., color_RGB1[1]/255., color_RGB1[2]/255.)
pdf_rep1.rect(565., 150., 1105., 390., fill = False, stroke = True)
pdf_rep1.rect(565., 515., 737., 50., fill = True, stroke = True)
pdf_rep1.setFillColorRGB(1,1,1)
pdf_rep1.setFont("Avenir", 24)
pdf_rep1.drawString(580., 530., 'Resumen eventos de la semana')

t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),\
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),\
                       ('ALIGN',(0,0),(-1,-1),'CENTER'),\
                       ('VALIGN',(0,0),(-1,-1),'MIDDLE'),\
                       ('FONTSIZE', (0, 0), (-1, 1), 18),\
                       ('BACKGROUND',(0,0),(-1,0),ColorInfo6),\
                       ('FONTSIZE', (0, 1), (-1, -1), 14),\
                       ('TEXTCOLOR',(0, 0),(-1,0),colors.white)\
                        ]))
t.wrapOn(pdf_rep1, 600, 890)
t.drawOn(pdf_rep1, 590., 350.)




sizes  = [2,2,0]

labels = ['Menor 15mm', 'Entre 15mm y 30mm','Entre 30mm y 45mm']
# labels = ['Menor 15mm', 'Entre 15mm y 30mm', 'Entre 30mm y 45mm']
def make_autopct(values):
Example #27
0
def _layout_extracted_fields(extracted_fields):
    elements = []

    if not extracted_fields:
        return elements

    def __children_have_data(field):
        for group in field.get('children', []):
            for child_field in group:
                if child_field.get('data'):
                    return True

        return False

    # information extracted from application
    for field in extracted_fields:
        if 'children' not in field:
            if 'data' in field and field['data']:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                elements.append(Paragraph(field['label'], styles['BoldLeft']))

                if field['help_text']:
                    elements.append(
                        Paragraph(field['help_text'], styles['ItalicLeft']))

                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

                if field['type'] in ['text', 'text_area']:
                    elements += _layout_paragraphs(field['data'])
                elif field['type'] in ['radiobuttons', 'select']:
                    elements.append(
                        Paragraph(
                            dict([i.values() for i in field['options']
                                  ]).get(field['data'], 'Not Specified'),
                            styles['Left']))
                else:
                    elements.append(Paragraph(field['data'], styles['Left']))

            elif field['type'] == 'label':
                if any([
                        option.get('data', 'off') == 'on'
                        for option in field['options']
                ]):
                    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                    elements.append(
                        Paragraph(field['label'], styles['BoldLeft']))

                    if field['help_text']:
                        elements.append(
                            Paragraph(field['help_text'],
                                      styles['ItalicLeft']))

                    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

                    elements.append(
                        Paragraph(
                            ', '.join([
                                option['label'] for option in field['options']
                                if option.get('data', 'off') == 'on'
                            ]), styles['Left']))
        else:
            if not __children_have_data(field):
                continue

            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(Paragraph(field['label'], styles['BoldLeft']))

            if field['help_text']:
                elements.append(
                    Paragraph(field['help_text'], styles['ItalicLeft']))

            table_data = []
            for index, group in enumerate(field['children']):
                if index == 0:
                    heading_row = []
                    for child_field in group:
                        heading_row.append(
                            Paragraph(child_field['label'],
                                      styles['BoldLeft']))
                    if heading_row:
                        table_data.append(heading_row)

                row = []
                for child_field in group:
                    if child_field['type'] in ['radiobuttons', 'select']:
                        row.append(
                            Paragraph(
                                dict([
                                    i.values() for i in child_field['options']
                                ]).get(child_field['data'], 'Not Specified'),
                                styles['Left']))
                    elif child_field['type'] == 'label':
                        if any([
                                option.get('data', 'off') == 'on'
                                for option in child_field['options']
                        ]):
                            row.append(
                                Paragraph(
                                    ', '.join([
                                        option['label']
                                        for option in child_field['options']
                                        if option.get('data', 'off') == 'on'
                                    ]), styles['Left']))
                        else:
                            row.append(
                                Paragraph('Not Specified', styles['Left']))
                    else:
                        row.append(
                            Paragraph(child_field['data'], styles['Left']))

                if row:
                    table_data.append(row)

            if table_data:
                elements.append(
                    Table(table_data,
                          style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')
                                            ])))

    return elements
Example #28
0
def _create_licence(licence_buffer, licence, application, site_url,
                    original_issue_date):
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160,
                             id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame],
                                       onPage=_create_licence_header)

    doc = BaseDocTemplate(licence_buffer,
                          pageTemplates=[every_page_template],
                          pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.licence = licence
    doc.site_url = site_url

    licence_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])

    elements = []

    elements.append(
        Paragraph(licence.licence_type.act, styles['InfoTitleLargeCenter']))
    elements.append(
        Paragraph(licence.licence_type.code.upper(),
                  styles['InfoTitleLargeCenter']))

    # cannot use licence get_title_with_variants because licence isn't saved yet so can't get variants
    if application.variants.exists():
        title = '{} ({})'.format(
            application.licence_type.name.encode('UTF-8'),
            ' / '.join(application.variants.all().values_list('name',
                                                              flat=True)))
    else:
        title = licence.licence_type.name.encode('UTF-8')

    elements.append(Paragraph(title, styles['InfoTitleVeryLargeCenter']))
    elements.append(
        Paragraph(licence.licence_type.statement,
                  styles['InfoTitleLargeLeft']))
    elements.append(
        Paragraph(licence.licence_type.authority,
                  styles['InfoTitleLargeRight']))

    # licence conditions
    if application.conditions.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Conditions', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        conditionList = ListFlowable([
            Paragraph(a.condition.text, styles['Left'])
            for a in application.applicationcondition_set.order_by('order')
        ],
                                     bulletFontName=BOLD_FONTNAME,
                                     bulletFontSize=MEDIUM_FONTSIZE)
        elements.append(conditionList)

    # purpose
    if licence.purpose:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Purpose', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements += _layout_paragraphs(licence.purpose)

    # locations
    if licence.locations:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Locations', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements += _layout_paragraphs(licence.locations)

    elements += _layout_extracted_fields(licence.extracted_fields)

    # additional information
    if licence.additional_information:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Additional Information',
                                  styles['BoldLeft']))
        elements += _layout_paragraphs(licence.additional_information)

    # delegation holds the dates, licencee and issuer details.
    delegation = []

    # dates and licensing officer
    dates_licensing_officer_table_style = TableStyle([
        ('VALIGN', (0, 0), (-2, -1), 'TOP'),
        ('VALIGN', (0, 0), (-1, -1), 'BOTTOM')
    ])

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    date_headings = [
        Paragraph('Date of Issue', styles['BoldLeft']),
        Paragraph('Valid From', styles['BoldLeft']),
        Paragraph('Date of Expiry', styles['BoldLeft'])
    ]
    date_values = [
        Paragraph(licence.issue_date.strftime(DATE_FORMAT), styles['Left']),
        Paragraph(licence.start_date.strftime(DATE_FORMAT), styles['Left']),
        Paragraph(licence.end_date.strftime(DATE_FORMAT), styles['Left'])
    ]

    if original_issue_date is not None:
        date_headings.insert(
            0, Paragraph('Original Date of Issue', styles['BoldLeft']))
        date_values.insert(
            0,
            Paragraph(original_issue_date.strftime(DATE_FORMAT),
                      styles['Left']))

    delegation.append(
        Table([[date_headings, date_values]],
              colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
              style=dates_licensing_officer_table_style))

    # licensee details
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    address = application.applicant_profile.postal_address
    address_paragraphs = [
        Paragraph(address.line1, styles['Left']),
        Paragraph(address.line2, styles['Left']),
        Paragraph(address.line3, styles['Left']),
        Paragraph(
            '%s %s %s' % (address.locality, address.state, address.postcode),
            styles['Left']),
        Paragraph(address.country.name, styles['Left'])
    ]
    delegation.append(
        Table([[[
            Paragraph('Licensee:', styles['BoldLeft']),
            Paragraph('Address', styles['BoldLeft'])
        ],
                [
                    Paragraph(
                        _format_name(application.applicant,
                                     include_first_name=True), styles['Left'])
                ] + address_paragraphs]],
              colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
              style=licence_table_style))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(
        Paragraph(
            'Issued by a Wildlife Licensing Officer of the Department of Parks and Wildlife '
            'under delegation from the Minister for Environment pursuant to section 133(1) '
            'of the Conservation and Land Management Act 1984.',
            styles['Left']))

    elements.append(KeepTogether(delegation))

    doc.build(elements)

    return licence_buffer
Example #29
0
    def make(request_info, vacancies):
        def add_page_number(canvas, doc):
            page_num = canvas.getPageNumber()
            text = "%s" % page_num
            canvas.drawRightString(11 * cm, 1 * cm, text)

        def add_spaces(num=1):
            for i in range(num):
                story.append(Paragraph("", style_h3))

        def key_or_none(dic, key, mes):
            return mes if key not in dic or dic[key] is None else str(dic[key])

        def currency_to_str(vacancy):
            if "salary" not in vacancy or vacancy["salary"] is None:
                return "Не указано"
            else:
                if len(vacancy["salary"]) > 2:
                    return "{} - {}".format(
                        key_or_none(vacancy["salary"], "from", "Не указано"),
                        key_or_none(vacancy["salary"], "to", "Не указано"))
                else:
                    return "Не известно"

        def pretty_text(text):
            text = html2text.html2text(text)

            replaces = (("\n", "<br />\n"), ("**", ""), ("*", "-"), ("\-",
                                                                     "-"))
            for source, target in replaces:
                text = text.replace(source, target)

            return text

        assert isinstance(request_info, dict)
        assert isinstance(vacancies, list)

        style_sheet = getSampleStyleSheet()

        style_h1 = style_sheet["Heading1"]
        style_h1.alignment = TA_CENTER
        style_h1.fontName = FONTNAME

        style_h2 = style_sheet["Heading2"]
        style_h2.alignment = TA_CENTER
        style_h2.fontName = FONTNAME

        style_h3 = style_sheet["Heading3"]
        style_h3.alignment = TA_CENTER
        style_h3.fontName = FONTNAME

        style_h4 = style_sheet["Heading4"]
        style_h4.alignment = TA_LEFT
        style_h4.fontName = FONTNAME

        style_table = style_sheet["Normal"]
        style_table.alignment = 1
        style_table.fontName = FONTNAME
        style_table.fontSize = 8

        style_body = style_sheet["BodyText"]
        style_body.fontName = FONTNAME
        style_body.alignment = TA_LEFT
        style_body.fontSize = 8
        style_body.spaceBefore = 10
        style_body.spaceAfter = 10

        filename = "Вакансии для {}.pdf".\
            format(request_info["email"].replace("<", "").replace(">", ""))

        doc = SimpleDocTemplate(filename,
                                pagesize=A4,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=50,
                                bottomMargin=50,
                                showBoundary=False,
                                allowSplitting=True)

        story = list()

        story.append(
            Paragraph("Кадровое агентство \"{}\"".format(utils.agency_name),
                      style_h1))
        add_spaces(2)
        story.append(
            Paragraph(
                "Дата отчета: {}".format(
                    datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")),
                style_h3))
        add_spaces(2)
        story.append(
            Paragraph(
                "Найдено вакансий: {}".format(
                    len(vacancies) if vacancies else 0), style_h3))
        add_spaces(2)

        story.append(Paragraph("Запрос:", style_h3))
        table = Table(
            [[
                Paragraph("Клиент", style_table),
                Paragraph(request_info["email"], style_table)
            ],
             [
                 Paragraph("Вакансии", style_table),
                 Paragraph(request_info["title"], style_table)
             ],
             [
                 Paragraph("Регион", style_table),
                 Paragraph(request_info["area"], style_table)
             ],
             [
                 Paragraph("Уровень зарплаты", style_table),
                 Paragraph(key_or_none(request_info, "salary", "Не задано"),
                           style_table)
             ],
             [
                 Paragraph("Опыт", style_table),
                 Paragraph(
                     key_or_none(request_info, "experience", "Не задано"),
                     style_table)
             ]],
            colWidths=[4 * cm, 6 * cm])
        table.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ]))
        story.append(table)

        for i, vacancy in enumerate(vacancies, start=1):
            story.append(PageBreak())
            story.append(
                Paragraph("Вакансия №{} из {}".format(i, len(vacancies)),
                          style_h3))

            story.append(Paragraph("Ключевая информация:", style_h4))

            table = Table(
                [[
                    Paragraph("Наименование вакансии", style_table),
                    Paragraph(vacancy["name"], style_table)
                ],
                 [
                     Paragraph("Компания", style_table),
                     Paragraph(vacancy["employer"]["name"], style_table)
                 ],
                 [
                     Paragraph("Город", style_table),
                     Paragraph(vacancy["area"]["name"], style_table)
                 ],
                 [
                     Paragraph("Уровень зарплаты", style_table),
                     Paragraph(currency_to_str(vacancy), style_table)
                 ],
                 [
                     Paragraph("Требуемый опыт работы", style_table),
                     Paragraph(
                         vacancy["experience"]["name"] if "experience"
                         in vacancy else str(request_info["experience"]),
                         style_table)
                 ]],
                colWidths=[5 * cm, 10 * cm])

            table.setStyle(
                TableStyle([
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]))

            story.append(table)

            story.append(Paragraph("Описание:", style_h4))
            story.append(
                Paragraph(
                    pretty_text(
                        vacancy.get("description", "Описание отсутствует")),
                    style_body))

        doc.build(story, onLaterPages=add_page_number)

        return filename
Example #30
0
def crearPdf_resumen(request, inventario, libros, issue, cd, resp):

    buffer = BytesIO()
    c = canvas.Canvas(buffer)
    # ----------------------- ENCABEZADO ---------------------
    # tamaño de la pagina
    w, h = A4
    c.setPageSize(A4)
    archivo_imagen = settings.MEDIA_ROOT + '/templates/inventario/img/logo.png'
    # Dibujamos una imagen (IMAGEN, X,Y, WIDTH, HEIGH)
    c.drawImage(archivo_imagen, 50, 780, 150, 50)
    # dibujamos una linea (X,Y, WIDTH, HEIGH)
    x = 50
    y = h - 100
    c.line(x, y, x + 500, y)
    # dibujamos otra linea (X,Y, WIDTH, HEIGH)
    x1 = 50
    y2 = h - 150
    c.line(x1, y2, x + 500, y2)
    # Para titulos asignamos una fuente y el tamaño = 20
    c.setFont('Helvetica', 20)
    # Dibujamos texto: (X,Y,Texto)
    c.drawString(220, 710, "Resumen de Inventario")
    # Para parrafos normales cambiamos el tamaño a 12
    c.setFont('Helvetica', 12)
    # ------------------------ FIN ENCABEZADO ------------------

    # Dibujamos texto: (X,Y,Texto)
    c.drawString(50, 650, "Nombre del responsable:")
    c.drawString(50, 630, "Biblioteca:")
    c.drawString(50, 610, "Fecha de inicio:")
    c.drawString(50, 590, "Fecha de termino:")
    c.drawString(50, 570, "Fecha de informe:")

    # ----------------- datos ------------------

    fecha_inicio = str(inventario.f_inicio)[0:10]
    fecha_termino = str(inventario.f_termino)[0:10]
    fecha_informe = str(inventario.f_informe)[0:10]
    c.setFont('Helvetica', 14)
    c.drawString(190, 650, "Alan brito")
    c.drawString(190, 630, "San Andres")
    c.drawString(190, 610, fecha_inicio)
    c.drawString(190, 590, fecha_termino)
    c.drawString(190, 570, fecha_informe)

    #----------------- tabla ------------------------
    styles = getSampleStyleSheet()
    styleN = styles["BodyText"]
    styleN.alignment = TA_LEFT
    styleBH = styles["Normal"]
    styleBH.alignment = TA_CENTER

    def coord(x, y, unit=1):
        x, y = x * unit, h - y * unit
        return x, y

    # Headers
    hConceptos = Paragraph('''<b>Conceptos</b>''', styleN)
    hN = Paragraph('''<b>#</b>''', styleBH)
    hISSUE = Paragraph('''<b>ISSUE</b>''', styleBH)
    hLIBROS = Paragraph('''<b>LIBROS</b>''', styleBH)
    hCD = Paragraph('''<b>CD</b>''', styleBH)
    hRESP = Paragraph('''<b>RESP</b>''', styleBH)
    hTOTAL = Paragraph('''<b>TOTAL</b>''', styleBH)
    # Texts

    # DATOS

    titulo1 = "Total de ítems Disponibles en el sistema"
    n1 = str(1)
    libros1 = str(libros.total_items)
    issue1 = str(issue.total_items)
    cd1 = str(cd.total_items)
    resp1 = str(resp.total_items)
    total1 = str(int(libros1) + int(issue1) + int(cd1) + int(resp1))
    # 1
    Conceptos1 = Paragraph(titulo1, styleN)
    N1 = Paragraph(n1, styleBH)
    ISSUE1 = Paragraph(libros1, styleBH)
    LIBROS1 = Paragraph(issue1, styleBH)
    CD1 = Paragraph(cd1, styleBH)
    RESP1 = Paragraph(resp1, styleBH)
    TOTAL1 = Paragraph(total1, styleBH)
    # DATOS

    titulo2 = "Total de ítems inventariados (Capturados en block de notas y pistola de mando) "
    n2 = str(2)
    libros2 = str(libros.total_items_inventariados)
    issue2 = str(issue.total_items_inventariados)
    cd2 = str(cd.total_items_inventariados)
    resp2 = str(resp.total_items_inventariados)
    total2 = str(int(libros2) + int(issue2) + int(cd2) + int(resp2))
    # 2
    Conceptos2 = Paragraph(titulo2, styleN)
    N2 = Paragraph(n2, styleBH)
    ISSUE2 = Paragraph(libros2, styleBH)
    LIBROS2 = Paragraph(issue2, styleBH)
    CD2 = Paragraph(cd2, styleBH)
    RESP2 = Paragraph(resp2, styleBH)
    TOTAL2 = Paragraph(total2, styleBH)

    # DATOS

    titulo3 = "Total de ítems en préstamo permanente"
    n3 = str(3)
    libros3 = str(libros.total_items_en_prestamos_permanente)
    issue3 = str(issue.total_items_en_prestamos_permanente)
    cd3 = str(cd.total_items_en_prestamos_permanente)
    resp3 = str(resp.total_items_en_prestamos_permanente)
    total3 = str(int(libros3) + int(issue3) + int(cd3) + int(resp3))
    # 3
    Conceptos3 = Paragraph(titulo3, styleN)
    N3 = Paragraph(n3, styleBH)
    ISSUE3 = Paragraph(libros3, styleBH)
    LIBROS3 = Paragraph(issue3, styleBH)
    CD3 = Paragraph(cd3, styleBH)
    RESP3 = Paragraph(resp3, styleBH)
    TOTAL3 = Paragraph(total3, styleBH)

    # DATOS

    titulo4 = "Total de ítems en moroso alumnos"
    n4 = str(4)
    libros4 = str(libros.total_items_en_morosos_alumnos)
    issue4 = str(issue.total_items_en_morosos_alumnos)
    cd4 = str(cd.total_items_en_morosos_alumnos)
    resp4 = str(resp.total_items_en_morosos_alumnos)
    total4 = str(int(libros4) + int(issue4) + int(cd4) + int(resp4))
    # 4
    Conceptos4 = Paragraph(titulo4, styleN)
    N4 = Paragraph(n4, styleBH)
    ISSUE4 = Paragraph(libros4, styleBH)
    LIBROS4 = Paragraph(issue4, styleBH)
    CD4 = Paragraph(cd4, styleBH)
    RESP4 = Paragraph(resp4, styleBH)
    TOTAL4 = Paragraph(total4, styleBH)
    # DATOS

    titulo5 = "Total de ítems morosos académico"
    n5 = str(5)
    libros5 = str(libros.total_items_morosos_academicos)
    issue5 = str(issue.total_items_morosos_academicos)
    cd5 = str(cd.total_items_morosos_academicos)
    resp5 = str(resp.total_items_morosos_academicos)
    total5 = str(int(libros5) + int(issue5) + int(cd5) + int(resp5))
    # 5
    Conceptos5 = Paragraph(titulo5, styleN)
    N5 = Paragraph(n5, styleBH)
    ISSUE5 = Paragraph(libros5, styleBH)
    LIBROS5 = Paragraph(issue5, styleBH)
    CD5 = Paragraph(cd5, styleBH)
    RESP5 = Paragraph(resp5, styleBH)
    TOTAL5 = Paragraph(total5, styleBH)
    # DATOS

    titulo6 = " 	Total ítems morosos funcionarios"
    n6 = str(6)
    libros6 = str(libros.total_items_morosos_funcionarios)
    issue6 = str(issue.total_items_morosos_funcionarios)
    cd6 = str(cd.total_items_morosos_funcionarios)
    resp6 = str(resp.total_items_morosos_funcionarios)
    total6 = str(int(libros6) + int(issue6) + int(cd6) + int(resp6))
    # 6
    Conceptos6 = Paragraph(titulo6, styleN)
    N6 = Paragraph(n6, styleBH)
    ISSUE6 = Paragraph(libros6, styleBH)
    LIBROS6 = Paragraph(issue6, styleBH)
    CD6 = Paragraph(cd6, styleBH)
    RESP6 = Paragraph(resp6, styleBH)
    TOTAL6 = Paragraph(total6, styleBH)
    # DATOS

    titulo7 = "Total ítem morosos postgrado"
    n7 = str(7)
    libros7 = str(libros.total_items_morosos_postgrado)
    issue7 = str(issue.total_items_morosos_postgrado)
    cd7 = str(cd.total_items_morosos_postgrado)
    resp7 = str(resp.total_items_morosos_postgrado)
    total7 = str(int(libros7) + int(issue7) + int(cd7) + int(resp7))
    # 7
    Conceptos7 = Paragraph(titulo7, styleN)
    N7 = Paragraph(n7, styleBH)
    ISSUE7 = Paragraph(libros7, styleBH)
    LIBROS7 = Paragraph(issue7, styleBH)
    CD7 = Paragraph(cd7, styleBH)
    RESP7 = Paragraph(resp7, styleBH)
    TOTAL7 = Paragraph(total7, styleBH)
    # DATOS

    titulo8 = "Total ítems morosos PIB"
    n8 = str(8)
    libros8 = str(libros.total_items_morosos_pib)
    issue8 = str(issue.total_items_morosos_pib)
    cd8 = str(cd.total_items_morosos_pib)
    resp8 = str(resp.total_items_morosos_pib)
    total8 = str(int(libros8) + int(issue8) + int(cd8) + int(resp8))
    # 8
    Conceptos8 = Paragraph(titulo8, styleN)
    N8 = Paragraph(n8, styleBH)
    ISSUE8 = Paragraph(libros8, styleBH)
    LIBROS8 = Paragraph(issue8, styleBH)
    CD8 = Paragraph(cd8, styleBH)
    RESP8 = Paragraph(resp8, styleBH)
    TOTAL8 = Paragraph(total8, styleBH)
    # DATOS

    titulo9 = "Total de ítems extraviados"
    n9 = str(9)
    libros9 = str(libros.total_items_extraviados)
    issue9 = str(issue.total_items_extraviados)
    cd9 = str(cd.total_items_extraviados)
    resp9 = str(resp.total_items_extraviados)
    total9 = str(int(libros9) + int(issue9) + int(cd9) + int(resp9))
    # 9
    Conceptos9 = Paragraph(titulo9, styleN)
    N9 = Paragraph(n9, styleBH)
    ISSUE9 = Paragraph(libros9, styleBH)
    LIBROS9 = Paragraph(issue9, styleBH)
    CD9 = Paragraph(cd9, styleBH)
    RESP9 = Paragraph(resp9, styleBH)
    TOTAL9 = Paragraph(total9, styleBH)
    # DATOS

    titulo10 = "Total ítems perdidos"
    n10 = str(10)
    libros10 = str(libros.total_items_perdidos)
    issue10 = str(issue.total_items_extraviados)
    cd10 = str(cd.total_items_extraviados)
    resp10 = str(resp.total_items_extraviados)
    total10 = str(int(libros10) + int(issue10) + int(cd10) + int(resp10))
    # 10
    Conceptos10 = Paragraph(titulo10, styleN)
    N10 = Paragraph(n10, styleBH)
    ISSUE10 = Paragraph(libros10, styleBH)
    LIBROS10 = Paragraph(issue3, styleBH)
    CD10 = Paragraph(cd10, styleBH)
    RESP10 = Paragraph(resp10, styleBH)
    TOTAL10 = Paragraph(total10, styleBH)
    # DATOS

    titulo11 = "Total ítems inutilizados (Quemado, manchado, mutilado)"
    n11 = str(11)
    libros11 = str(libros.total_items_inutilizados)
    issue11 = str(issue.total_items_inutilizados)
    cd11 = str(cd.total_items_inutilizados)
    resp11 = str(resp.total_items_inutilizados)
    total11 = str(int(libros11) + int(issue11) + int(cd11) + int(resp11))
    # 11
    Conceptos11 = Paragraph(titulo11, styleN)
    N11 = Paragraph(n11, styleBH)
    ISSUE11 = Paragraph(libros11, styleBH)
    LIBROS11 = Paragraph(issue11, styleBH)
    CD11 = Paragraph(cd11, styleBH)
    RESP11 = Paragraph(resp11, styleBH)
    TOTAL11 = Paragraph(total11, styleBH)
    # DATOS

    titulo12 = "Total de ítems deteriorados para empastar (puede ser recuperable)"
    n12 = str(12)
    libros12 = str(libros.total_items_deteriorados_para_empastar)
    issue12 = str(issue.total_items_deteriorados_para_empastar)
    cd12 = str(cd.total_items_deteriorados_para_empastar)
    resp12 = str(resp.total_items_deteriorados_para_empastar)
    total12 = str(int(libros12) + int(issue12) + int(cd12) + int(resp12))
    # 12
    Conceptos12 = Paragraph(titulo12, styleN)
    N12 = Paragraph(n12, styleBH)
    ISSUE12 = Paragraph(libros12, styleBH)
    LIBROS12 = Paragraph(issue12, styleBH)
    CD12 = Paragraph(cd12, styleBH)
    RESP12 = Paragraph(resp12, styleBH)
    TOTAL12 = Paragraph(total12, styleBH)
    # DATOS

    titulo13 = "Total ítems en transito"
    n13 = str(13)
    libros13 = str(libros.total_items_transito)
    issue13 = str(issue.total_items_transito)
    cd13 = str(cd.total_items_transito)
    resp13 = str(resp.total_items_transito)
    total13 = str(int(libros13) + int(issue13) + int(cd13) + int(resp13))
    # 13
    Conceptos13 = Paragraph(titulo13, styleN)
    N13 = Paragraph(n13, styleBH)
    ISSUE13 = Paragraph(libros13, styleBH)
    LIBROS13 = Paragraph(issue13, styleBH)
    CD13 = Paragraph(cd13, styleBH)
    RESP13 = Paragraph(resp13, styleBH)
    TOTAL13 = Paragraph(total13, styleBH)
    # DATOS

    titulo14 = "Total ítems con problemas en catalogación"
    n14 = str(14)
    libros14 = str(libros.total_items_problemas_de_catalogacion)
    issue14 = str(issue.total_items_problemas_de_catalogacion)
    cd14 = str(cd.total_items_problemas_de_catalogacion)
    resp14 = str(resp.total_items_problemas_de_catalogacion)
    total14 = str(int(libros14) + int(issue14) + int(cd14) + int(resp14))
    # 14
    Conceptos14 = Paragraph(titulo14, styleN)
    N14 = Paragraph(n14, styleBH)
    ISSUE14 = Paragraph(libros14, styleBH)
    LIBROS14 = Paragraph(issue14, styleBH)
    CD14 = Paragraph(cd14, styleBH)
    RESP14 = Paragraph(resp14, styleBH)
    TOTAL14 = Paragraph(total14, styleBH)
    # DATOS

    titulo15 = "Total de ítems faltantes"
    n15 = str(15)
    libros15 = str(libros.total_items_faltantes)
    issue15 = str(issue.total_items_faltantes)
    cd15 = str(cd.total_items_faltantes)
    resp15 = str(resp.total_items_faltantes)
    total15 = str(int(libros15) + int(issue15) + int(cd15) + int(resp15))
    # 15
    Conceptos15 = Paragraph(titulo15, styleN)
    N15 = Paragraph(n15, styleBH)
    ISSUE15 = Paragraph(libros15, styleBH)
    LIBROS15 = Paragraph(issue15, styleBH)
    CD15 = Paragraph(cd15, styleBH)
    RESP15 = Paragraph(resp15, styleBH)
    TOTAL15 = Paragraph(total15, styleBH)

    data = [[hN, hConceptos, hISSUE, hLIBROS, hCD, hRESP, hTOTAL],
            [N1, Conceptos1, ISSUE1, LIBROS1, CD1, RESP1, TOTAL1],
            [N2, Conceptos2, ISSUE2, LIBROS2, CD2, RESP2, TOTAL2],
            [N3, Conceptos3, ISSUE3, LIBROS3, CD3, RESP3, TOTAL3],
            [N4, Conceptos4, ISSUE4, LIBROS4, CD4, RESP4, TOTAL4],
            [N5, Conceptos5, ISSUE5, LIBROS5, CD5, RESP5, TOTAL5],
            [N6, Conceptos6, ISSUE6, LIBROS6, CD6, RESP6, TOTAL6],
            [N7, Conceptos7, ISSUE7, LIBROS7, CD7, RESP7, TOTAL7],
            [N8, Conceptos8, ISSUE8, LIBROS8, CD8, RESP8, TOTAL8],
            [N9, Conceptos9, ISSUE9, LIBROS9, CD9, RESP9, TOTAL9],
            [N10, Conceptos10, ISSUE10, LIBROS10, CD10, RESP10, TOTAL10],
            [N11, Conceptos11, ISSUE11, LIBROS11, CD11, RESP11, TOTAL11],
            [N12, Conceptos12, ISSUE12, LIBROS12, CD12, RESP12, TOTAL12],
            [N13, Conceptos13, ISSUE13, LIBROS13, CD13, RESP13, TOTAL13],
            [N14, Conceptos14, ISSUE14, LIBROS14, CD14, RESP14, TOTAL14],
            [N15, Conceptos15, ISSUE15, LIBROS15, CD15, RESP15, TOTAL15]]

    table = Table(
        data,
        colWidths=[1.0 * cm, 8.7 * cm, 1.5 * cm, 1.9 * cm, 1.4 * cm, 1.7 * cm])

    table.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))

    table.wrapOn(c, w, h)
    table.drawOn(c, *coord(1.5, 22.6, cm))
    # Guardar
    c.showPage()
    c.save()
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
    def makeStyles(self):
        styles = TableStyle([('GRID', (0, 0), (-1, -1), 0.0, colors.black),
                             ('VALIGN', (0, 0), (-1, -1), 'TOP')])  #finale

        return styles
Example #32
0
def create_report(request):
	response = HttpResponse(content_type='application/pdf')
	response['Content-Disposition'] = 'filename=MSAP.pdf'
	buffer = BytesIO()
	c = canvas.Canvas(buffer, pagesize=A4)
	#cabecera
	c.setLineWidth(.3)
	c.setFont('Helvetica',22)
	c.drawString(30,750,'MSAP')
	c.setFont('Helvetica',12)
	c.drawString(30,735,'Reporte del Proceso')
	c.setFont('Helvetica-Bold',12)
	print(datetime.now())
	date = str(datetime.now().date())
	c.drawString(480,750,date)
	c.line(460,747,560,747)
	#cuerpo
	proces = Process.objects.all()
	notas =[]
	i = 0
	for p in proces:
		i = i + 1
		number = round((float(p.status_process)),2)
		data={'#':i,'name':p.name,'total':number}
		notas.append(data)
	"""	
	notas = [{'#':'1','name':'Henry Aymara Apaza','total':'19.5'},
	         {'#':'1','name':'DBB','total':'20'}]
	"""
	styles = getSampleStyleSheet()
	styleBH = styles["Normal"]
	styleBH.aligment = TA_CENTER
	styleBH.fontSize = 10

	numero = Paragraph('''No.''', styleBH)
	alumno = Paragraph('''Fases''',styleBH)
	total = Paragraph('''Avance(%)''',styleBH)
	data = [[numero, total]]

	styles = getSampleStyleSheet()
	styleN = styles["BodyText"]
	styleN.aligment = TA_CENTER
	styleN.fontSize = 7

	width, height = A4
	high = 650
	for nota in notas:
		this_student = [nota['#'],nota['name'],nota["total"]]
		data.append(this_student)
		high = high - 10

	table = Table(data, colWidths=[19 * mm,95 * mm,19 * mm,19 * mm,19 * mm,19 * mm])
	table.setStyle(TableStyle([
		('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
		('BOX', (0,0),(-1,-1), 0.25, colors.black),
	]))
	table.wrapOn(c,width, height)
	table.drawOn(c,30,high)
	c.showPage()
	c.save()
	pdf = buffer.getvalue()
	buffer.close()
	response.write(pdf)
	return response
Example #33
0
def export_stock_report(request):
    try:
        if request.method == 'POST':
            start_date = request.POST['from_date']
            end_date = request.POST['to_date']
            filter_args = {}
            smonth, sday, syear = start_date.split('/')
            emonth, eday, eyear = end_date.split('/')
            start_date = date(int(syear), int(smonth), int(sday))
            end_date = date(int(eyear), int(emonth), int(eday))
            filter_args['created_date__range'] = (datetime.combine(
                start_date, time.min), datetime.combine(end_date, time.max))
            daterange = 'From ' + start_date.strftime(
                '%b %d, %Y') + ' to ' + end_date.strftime('%b %d, %Y')
            dataset = Stock.objects.filter(**filter_args)
            if not dataset.exists():
                messages.error(request, 'No Data Found')
                return redirect('report:stock_report')

            if 'xls_export' in request.POST:
                response = HttpResponse(content_type='application/ms-excel')
                response[
                    'Content-Disposition'] = 'attachment; filename="Stock Report.xls"'
                wb = xlwt.Workbook(encoding='utf-8', style_compression=2)
                ws = wb.add_sheet('stock_report')
                row_num = 4

                font_style = xlwt.XFStyle()
                common = "font:name Calibri, bold on, height 200;  align:wrap yes, horiz center, vert center ;"
                common1 = "align: wrap yes, horiz right, vert center ;"

                columns = [
                    'SL', 'Name', 'Brand', 'Size', 'Category', 'Price',
                    'Quantity', 'Expiry Date', 'Supplier'
                ]

                ws.write_merge(0, 1, 0, 5, 'Stock Report', xlwt.easyxf(common))
                ws.write_merge(2, 3, 0, 5, daterange, xlwt.easyxf(common))
                for col in range(len(columns)):
                    ws.write(row_num, col, columns[col], font_style)
                row_num += 1
                for count, data in enumerate((dataset)):
                    ws.write(row_num, 0, count + 1, font_style)
                    ws.write(row_num, 1, data.product.name, font_style)
                    ws.write(row_num, 2, data.product.brand, font_style)
                    ws.write(row_num, 3, data.product.size, font_style)
                    ws.write(row_num, 4, data.product.category.name,
                             font_style)
                    ws.write(row_num, 5, str(data.product.price), font_style)
                    ws.write(row_num, 6, str(data.quantity), font_style)
                    ws.write(row_num, 7, str(data.expiry_date), font_style)
                    ws.write(row_num, 8, data.supplier.name,
                             xlwt.easyxf(common1))
                    row_num += 1

                wb.save(response)
                return response

            elif 'pdf_export' in request.POST:
                styles = getSampleStyleSheet()
                doc = SimpleDocTemplate(
                    "assets/pdf_files/Stock Report.pdf",
                    pagesize=reportlab.lib.pagesizes.landscape(letter))
                parastyles = ParagraphStyle(
                    'header',
                    parent=styles['Normal'],
                    fontName='Helvetica-Bold',
                    fontSize=8,
                    alignment=TA_CENTER,
                    textColor=colors.black,
                )
                story = []
                elements = []
                columns = []
                columns.insert(0, [
                    Paragraph('S/L', parastyles),
                    Paragraph('Name', parastyles),
                    Paragraph('Brand', parastyles),
                    Paragraph('Size', parastyles),
                    Paragraph('Category', parastyles),
                    Paragraph('Price', parastyles),
                    Paragraph('Quantity', parastyles),
                    Paragraph('Expiry Date', parastyles),
                    Paragraph('Supplier', parastyles)
                ])

                texstyles = ParagraphStyle(
                    'text',
                    parent=styles['Normal'],
                    fontSize=8,
                    alignment=TA_CENTER,
                    textColor=colors.black,
                )
                j = 1

                for count, data in enumerate((dataset)):
                    columns.insert(j, [
                        Paragraph(str(j), texstyles),
                        Paragraph(str(data.product.name), texstyles),
                        Paragraph(str(data.product.brand), texstyles),
                        Paragraph(str(data.product.size), texstyles),
                        Paragraph(str(data.product.category), texstyles),
                        Paragraph(str(data.product.price), texstyles),
                        Paragraph(str(data.quantity), texstyles),
                        Paragraph(str(data.expiry_date), texstyles),
                        Paragraph(str(data.supplier.name), texstyles)
                    ])
                    j = j + 1
                t = Table(columns, repeatRows=1, splitByRow=1)
                t.setStyle(
                    TableStyle([('FONTSIZE', (0, 0), (-1, -1), 1),
                                ('INNERGRID', (0, 0), (-1, -1), 0.25,
                                 colors.gray),
                                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                ('VALIGN', (0, 0), (-1, -1), 'TOP')]))

                dateofpdf = (datetime.now()).strftime("%d/%m/%Y")
                story.append(Paragraph("Stock Report", parastyles))
                story.append(Spacer(1, 0.2 * inch))
                story.append(Paragraph(daterange, parastyles))
                story.append(Spacer(1, 0.2 * inch))
                story.append(
                    Paragraph("Printed Date: " + dateofpdf, styles['Normal']))
                story.append(Spacer(1, 0.2 * inch))
                story.append(Spacer(1, 0.2 * inch))
                elements.append(t)
                story.append(t)
                doc.build(story,
                          onFirstPage=myFirstPage,
                          onLaterPages=myLaterPages)
                fs = FileSystemStorage()
                with fs.open("pdf_files/Stock Report.pdf") as pdf:
                    response = HttpResponse(pdf,
                                            content_type='application/pdf')
                    filename = "Stock Report.pdf"
                    response[
                        'Content-Disposition'] = 'attachment; filename="{}"'.format(
                            filename)
                    return response
                return response
    except Exception as ex:
        messages.error(request, str(ex))
        mylog.exception('export_stock_report', exc_info=True)
        return redirect('report:stock_report')
Example #34
0
def build_stv_doc(title,
                  name,
                  institution_name,
                  voting_start,
                  voting_end,
                  extended_until,
                  data,
                  language,
                  filename="election_results.pdf",
                  new_page=True):
    with translation.override(language[0]):
        pageinfo = _("Zeus Elections - Poll Results")
        title = _('Results')
        DATE_FMT = "%d/%m/%Y %H:%M"
        if isinstance(voting_start, datetime.datetime):
            voting_start = _('Start: %(date)s') % {
                'date': voting_start.strftime(DATE_FMT)
            }

        if isinstance(voting_end, datetime.datetime):
            voting_end = _('End: %(date)s') % {
                'date': voting_end.strftime(DATE_FMT)
            }

        if extended_until and isinstance(extended_until, datetime.datetime):
            extended_until = _('Extension: %(date)s') % {
                'date': extended_until.strftime(DATE_FMT)
            }
        else:
            extended_until = ""

        if not isinstance(data, list):
            data = [(name, data)]

        # reset pdfdoc timestamp in order to force a fresh one to be used in
        # pdf document metadata.
        pdfdoc._NOWT = None

        elements = []

        doc = SimpleDocTemplate(filename, pagesize=A4)

        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(name='Zeus',
                           fontName=DEFAULT_FONT,
                           fontSize=12,
                           leading=16,
                           alignment=TA_JUSTIFY))
        styles.add(
            ParagraphStyle(name='ZeusBold',
                           fontName=DEFAULT_FONT,
                           fontSize=12,
                           leading=16,
                           alignment=TA_JUSTIFY))

        styles.add(
            ParagraphStyle(name='ZeusSubHeading',
                           fontName=DEFAULT_FONT,
                           fontSize=14,
                           alignment=TA_JUSTIFY,
                           spaceAfter=16))

        styles.add(
            ParagraphStyle(name='ZeusHeading',
                           fontName=DEFAULT_FONT,
                           fontSize=16,
                           alignment=TA_CENTER,
                           spaceAfter=16))
        intro_contents = [voting_start, voting_end, extended_until]

        make_heading(elements, styles, [title, name, institution_name])
        make_intro(elements, styles, intro_contents)
        make_election_voters(elements, styles, data, stv=True)

        for poll_name, poll_results, questions, poll_voters in data:
            poll_intro_contents = [poll_name]

            #total_votes, blank_votes, parties_results, candidates_results = \
            #    load_results(poll_results)
            if new_page:
                elements.append(PageBreak())
            elements.append(Spacer(1, 12))
            elements.append(Spacer(1, 12))
            elements.append(Spacer(1, 12))
            make_subheading(elements, styles, poll_intro_contents)
            elements.append(Spacer(1, 12))
            make_intro(elements, styles, intro_contents)
            make_poll_voters(elements, styles, poll_voters)
            elements.append(Spacer(1, 12))
            #make dict with indexing as key and name as value
            counter = 0
            indexed_cands = {}
            for item in questions[0]['answers']:
                indexed_cands[str(counter)] = item
                counter += 1
            elected = [[_('Elected')]]
            json_data = poll_results[0]
            for item in json_data:
                elected.append([indexed_cands[item[0]]])
            t = Table(elected)
            my_table_style = TableStyle([
                ('FONT', (0, 0), (-1, -1), DEFAULT_FONT),
                ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ])
            t.setStyle(my_table_style)
            elements.append(t)

            actions_desc = {
                'elect': _('Elect'),
                'eliminate': _('Eliminated'),
                'quota': _('Eliminated due to quota restriction')
            }

            table_header = [_('Candidate'), _('Votes'), _('Draw'), _('Action')]

            stv = STVParser(poll_results[2])
            rounds = list(stv.rounds())

            for num, round in rounds:
                round_name = _('Round ')
                round_name += str(num)
                elements.append(Paragraph(round_name, styles['Zeus']))
                round_table = []
                temp_table = []
                temp_table.append(table_header)
                for name, cand in round['candidates'].items():
                    actions = [x[0] for x in cand['actions']]
                    draw = _("NO")
                    if 'random' in actions:
                        draw = _("YES")
                    action = None
                    if len(actions):
                        action = actions_desc.get(actions[-1])
                    votes = cand['votes']
                    cand_name = indexed_cands[str(name)]
                    cand_name = cand_name.split(':')[0]
                    row = [cand_name, votes, draw, action]
                    temp_table.append(row)
                round_table = Table(temp_table)
                round_table.setStyle(my_table_style)
                elements.append(round_table)
                elements.append(Spacer(1, 12))

        doc.build(elements,
                  onFirstPage=make_first_page_hf,
                  onLaterPages=make_later_pages_hf(pageinfo))
Example #35
0
 def __init__(self, name, cmds=None, parent=None, **kw):
     self.name = name
     TableStyle.__init__(self, cmds, parent, **kw)
Example #36
0
    def gen_stat(self):
        """
        Генерирует элементы для статистике в отчете. \n
        Данные таблицы с краткой статистикой:
        - Общее пройденное расстояние(мили).
        - Среднее расстояние между заправками(мили).
        - Средняя цена галлона(центы).
        - Среднее количество галлонов.
        - Средняя цена одной заправки(доллары).
        - Общая цена всех заправок(доллары).
        - Средний пробег на одном галлоне(мили).
        - Средняя цена одной мили(доллары).
        - Средний расход топлива(галлоны).

        Основная статистика:
        - Самая часто посещаемая вами заправка.
        - Самая выгодная заправка и информация о ней.
        - Количество долларов, которые можно было сэкономить,
          если заправляться только на самой выгодной заправке.

        Returns
        -------
        list
            Элементы краткой статистики
        """

        elements = []

        # Данные по статистике
        elements.append(Paragraph("Statistics", self.s_header_1))
        elements.append(Spacer(0, 5))

        table_data = self.table_data_to_list(
            self.db.select("v_trans",
                           """
                           MAX(odometer) - MIN(odometer),
                           AVG(mbs),
                           AVG(price),
                           AVG(amount),
                           AVG(cost),
                           SUM(cost),
                           AVG(mpg),
                           AVG(mile_price),
                           SUM(amount) / (MAX(odometer) - MIN(odometer)) * 60
                           """,
                           condition=self.condition))

        row_name = [
            "TOTAL \n DISTANCE", "AVERAGE \n MILIAGE \n BEETWEEN",
            "AVERAGE \n GALLON \n PRICE", "AVERAGE \n GALLONS",
            "AVERAGE \n COST", "TOTAL \n COST", "AVERAGE \n MPG",
            "AVERAGE \n MILE \n PRICE", "AVERAGE \n FUEL \n CONSUPTION"
        ]
        table_data.insert(0, row_name)
        # for i in range(row_name - 1):
        #     table_data[i].insert(0, row_name[i])

        # Создаем таблицу
        self.logger.debug("Creating short statistics table")
        table = Table(table_data, repeatRows=True)
        table_style = [("BACKGROUND", (0, 0), (-1, 0), colors.lightblue),
                       ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                       ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                       ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
                       ('ALIGN', (0, 0), (-1, -1), "CENTER")]
        table.setStyle(TableStyle(table_style))
        self.logger.info("Short statistics table was created")
        elements.append(table)

        # Информация о самой часто посещаемой заправке
        self.logger.debug("Generating info about the most visited gas station")
        elements.append(
            Paragraph("The most visited gas station", self.s_header_2))
        table_data = self.table_data_to_list(
            self.db.select("v_trans v",
                           """
                           name,
                           price,
                           mpg,
                           mile_price,
                           (SELECT COUNT(vv.name) FROM v_trans vv WHERE vv.name = v.name AND """
                           + self.condition + ") as names_count",
                           condition=self.condition,
                           order_by="names_count DESC",
                           limit="1"))

        table_data.insert(0, [
            "GAS \n STATION", "GALLON \n PRICE", "MPG", "MILE \n PRICE",
            "VISITS"
        ])

        table = Table(table_data, repeatRows=True)
        table_style = [("BACKGROUND", (0, 0), (-1, 0), colors.lightblue),
                       ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                       ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                       ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
                       ('ALIGN', (0, 0), (-1, -1), "CENTER")]
        table.setStyle(TableStyle(table_style))
        self.logger.info("Generated info about the most visited gas station")
        elements.append(table)

        # Информация о самой выгодной заправке
        self.logger.debug(
            "Generating info about the most profitable gas station")
        elements.append(
            Paragraph("The most profitable gas station", self.s_header_2))
        table_data = self.table_data_to_list(
            self.db.select(
                "v_trans",
                """
                           name,
                           price,
                           mpg,
                           mile_price,
                           COUNT(name)
                           """,
                self.condition +
                "AND price = (SELECT MIN(price) FROM v_trans WHERE " +
                self.condition + ")",
                limit="1"))

        table_data.insert(0, [
            "GAS \n STATION", "GALLON \n PRICE", "MPG", "MILE \n PRICE",
            "VISITS"
        ])

        table = Table(table_data, repeatRows=True)
        table_style = [("BACKGROUND", (0, 0), (-1, 0), colors.lightblue),
                       ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                       ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                       ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
                       ('ALIGN', (0, 0), (-1, -1), "CENTER")]
        table.setStyle(TableStyle(table_style))
        self.logger.info(
            "Generated info about the most profitable gas station was generated"
        )
        elements.append(table)
        elements.append(Spacer(0, 15))

        # Информация о том, сколько можно было съэкономить,
        # если бы человек заправлялся только на самой выгодной
        # заправке.
        # Общая цена заправок равна сумме цен заправок.
        # Общая цена заправок, если все заправки были бы
        # самыми выгодными равна:
        # цена одного галлона умноженная на общую сумму
        # всех купленных галлонов, затем разделить 100,
        # чтобы получить цену в галлонах.
        table_data = self.table_data_to_list(
            self.db.select("v_trans",
                           """
                           SUM(cost),
                           (SELECT price
                            FROM v_trans
                            WHERE price = (SELECT MIN(price) FROM v_trans WHERE """
                           + self.condition + ")) * SUM(amount) / 100",
                           condition=self.condition))

        elements.append(
            Paragraph(
                "Total spent on gas stations: " + str(table_data[0][0]) + "$.",
                self.s_text))
        elements.append(
            Paragraph(
                "Refueling at the best gas station," +
                " the total price would be: " + str(table_data[0][1]) + "$.",
                self.s_text))
        elements.append(
            Paragraph(
                "Could have saved: " +
                str(round(table_data[0][0] - table_data[0][1], 2)) + "$.",
                self.s_text))

        return elements
def export_pdf(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=programa.pdf'
    doc = SimpleDocTemplate(
        response,
        pagesize=letter,
        rightMargin=72,
        leftMargin=72,
        topMargin=50,
        bottomMargin=18,
    )
    Story = []
    # im = Image(settings.STATIC_ROOT+'/images/logoUS.png', 1 * inch, 1 * inch)
    # Story.append(im)
    # Story.append(Spacer(2, 24))
    estilos = getSampleStyleSheet()
    estilos.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    resultado = []
    bd = sqlite3.connect("programa.db")
    cursor = bd.cursor()
    sql_lunes = "select dia, fecha, hora_inicio, hora_fin, programa.titulo, charlas.titulo, evento, ponentes, resumen from programa left outer join charlas on charlas.sessioncode = programa.sessioncode where dia= 'Monday' order by  hora_fin asc;"
    sql_martes = "select dia, fecha, hora_inicio, hora_fin, programa.titulo, charlas.titulo, evento, ponentes, resumen from programa left outer join charlas on charlas.sessioncode = programa.sessioncode where dia= 'Tuesday' order by  hora_fin asc;"
    sql_miercoles = "select dia, fecha, hora_inicio, hora_fin, programa.titulo, charlas.titulo, evento, ponentes, resumen from programa left outer join charlas on charlas.sessioncode = programa.sessioncode where dia= 'Wednesday' order by  hora_fin asc;"
    sql_jueves = "select dia, fecha, hora_inicio, hora_fin, programa.titulo, charlas.titulo, evento, ponentes, session_name from programa left outer join charlas on charlas.sessioncode = programa.sessioncode where dia= 'Thursday' order by  hora_fin asc;"
    sql_viernes = "select dia, fecha, hora_inicio, hora_fin, programa.titulo, charlas.titulo, evento, ponentes, session_name from programa left outer join charlas on charlas.sessioncode = programa.sessioncode where dia= 'Friday' order by  hora_fin asc;"
    lunes = cursor.execute(sql_lunes)
    resultado.extend(lunes)
    martes = cursor.execute(sql_martes)
    resultado.extend(martes)
    miercoles = cursor.execute(sql_miercoles)
    resultado.extend(miercoles)
    jueves = cursor.execute(sql_jueves)
    resultado.extend(jueves)
    viernes = cursor.execute(sql_viernes)
    resultado.extend(viernes)
    bd.close()

    head = estilos["Heading4"]
    head.alignment = TA_CENTER
    Story.append(Paragraph('PROGRAMA DEL EVENTO', head))
    Story.append(Spacer(2, 24))


    primera_columna = ('Fecha', 'Hora Inicio', 'Hora Fin', 'Acciones', 'Titulo')

    datos = []
    a = ""
    for i in resultado:
        if i[5] is not None:
            a = i[5][:19]+"..."
        datos.append((i[0]+' '+i[1], i[2], i[3], i[4], a))

    detalle = Table([primera_columna] + datos, colWidths=[100, 60, 60, 100, 120])

    detalle.setStyle(TableStyle([
        ('GRID', (0, 0), (4, -1), 1, colors.black),
        ('ALIGN', (0, 0), (0, 0), 'CENTER'),
        ('FONTSIZE', (0, 0), (0, 0), 10, 'CENTER'),
    ]))
    Story.append(detalle)
    doc.build(Story)
    return response
Example #38
0
def evenement_est(response, lettre_commande):
    # Our container for 'Flowable' objects
    elements = []

    # Main TableFontsize
    petitePolice = 10
    basePolice = 12
    grandePolice = 14

    fontsize_style = ("FONTSIZE", (0, 0), (-1, -1), basePolice)

    rootPath = "/var/www/vhosts/backupmix.com/httpdocs/greta/administration/pdf/img/"
    # Empty checkbox
    empty_checkbox = Image(rootPath + "checkbox_empty.jpg", width=18, height=18)

    # Checked checkbox
    checked_checkbox = Image(rootPath + "checkbox_checked.jpg", width=18, height=18)

    checks_box = (empty_checkbox, checked_checkbox)

    # A basic document for us to write to 'rl_hello_platypus.pdf'
    # doc = SimpleDocTemplate("fiche_evenemment.pdf", rightMargin=10, leftMargin=10, topMargin=0, bottomMargin=5)
    doc = SimpleDocTemplate(response, rightMargin=10, leftMargin=10, topMargin=0, bottomMargin=5)

    # Image en-tête
    evenementEst_Image = Image(rootPath + "evenement_est.jpg", width=573, height=159)
    evenementEst_Image.spaceAfter = 30
    elements.append(evenementEst_Image)

    # Create two 'Paragraph' Flowables and add them to our 'elements'
    # elements.append(Paragraph("The Platypus", styles['Heading1']))
    elements.append(Paragraph("<u>Type de prestation</u>", styles.getSampleStyleSheet()["Heading2"]))

    # Tableau type de prestations
    typePresta_data = [
        [
            empty_checkbox,
            "BCA",
            checked_checkbox,
            "CIBLE",
            empty_checkbox,
            "OP CREA",
            empty_checkbox,
            "ECCP",
            empty_checkbox,
            "MOB",
            empty_checkbox,
            "STR",
            empty_checkbox,
            "EPCE",
        ]
    ]
    colonnesWidths = (20, 55, 20, 65, 20, 80, 20, 55, 20, 55, 20, 50, 20, 50)
    typePresta_style = TableStyle(
        [
            fontsize_style,
            ("VALIGN", (1, 0), (1, 0), "MIDDLE"),
            ("VALIGN", (3, 0), (3, 0), "MIDDLE"),
            ("VALIGN", (5, 0), (5, 0), "MIDDLE"),
            ("VALIGN", (7, 0), (7, 0), "MIDDLE"),
            ("VALIGN", (9, 0), (9, 0), "MIDDLE"),
            ("VALIGN", (11, 0), (11, 0), "MIDDLE"),
            ("VALIGN", (13, 0), (13, 0), "MIDDLE"),
        ]
    )
    typePresta_style.spaceAfter = 10
    typePresta_table = Table(data=typePresta_data, colWidths=colonnesWidths, style=typePresta_style)
    elements.append(typePresta_table)

    location_style = styles.getSampleStyleSheet()["Normal"]
    location_style.spaceAfter = 10
    location_style.alignment = enums.TA_LEFT

    elements.append(
        Paragraph(
            u"<font size='12'><b>Nom du prestataire: </b>%s</font>" % (lettre_commande.site.prestataire.nom,),
            location_style,
        )
    )
    elements.append(
        Paragraph(
            u"<font size='12'><b>Lieu de réalisation: </b>%s</font>" % (lettre_commande.site.nom,), location_style
        )
    )
    elements.append(Paragraph(u"<font size='12'><b>Agence d'inscription: </b>%s</font>", location_style))

    tableData = [
        [
            u"Nom-Prénom du DE:",
            lettre_commande.nom + " " + lettre_commande.prenom,
            "",
            "",
            u"N° Identifiant:",
            lettre_commande.polemploi_id,
        ],
        [
            "Date du premier RDV:",
            lettre_commande.ouverture_rdv.dateheure.date().strftime("%d/%m/%Y"),
            "",
            "",
            "Heure du RDV:",
            lettre_commande.ouverture_rdv.dateheure.time().strftime("%H:%M"),
        ],
    ]
    tableStyle = TableStyle(
        [
            fontsize_style,
            # ('ALIGN', (0,0), (5,0), 'RIGHT'),
            ("FONT", (0, 0), (0, 1), "Times-Bold"),
            ("FONT", (4, 0), (4, 1), "Times-Bold"),
            ("ALIGN", (0, 0), (-1, -1), "LEFT"),
        ]
    )
    table = Table(tableData, style=tableStyle)
    table.hAlign = 0
    # table.leftPadding = 0
    table.spaceAfter = 20
    elements.append(table)

    # Escpace
    # space1 = Spacer(width=450, height=20)
    # elements.append(space1)

    # Barre Horizontale
    barreHorizontale = Image(rootPath + "barre_horizontale.jpg", width=520, height=6)
    barreHorizontale.spaceAfter = 20
    elements.append(barreHorizontale)

    # Tableaux Premier RDV

    # DEMARRAGE DE PRESTATION

    demarragePresta_data = [
        [
            eval(get_image_ouverture_rdv(lettre_commande.ouverture_rdv, ouvertureRdv.PRESENT_C)),
            "A DEMARRE LA PRESTATION",
        ]
    ]
    demarragePresta_style = TableStyle(
        [("FONTSIZE", (1, 0), (1, 0), grandePolice), ("LEADING", (1, 0), (1, 0), 3), ("VALIGN", (1, 0), (1, 0), "TOP")]
    )
    demarragePresta = Table(demarragePresta_data, style=demarragePresta_style)
    demarragePresta.hAlign = 0
    demarragePresta.spaceAfter = 10
    elements.append(demarragePresta)

    # REFUS PRESTATION
    refusPresta_data = [
        [
            eval(get_image_ouverture_rdv(lettre_commande.ouverture_rdv, ouvertureRdv.PRESENT_NC)),
            "N'A PAS ADHERE A LA PRESTATION",
        ],
        [None, "Indiquer le motif: " + get_comments_ouverture_rdv(lettre_commande.ouverture_rdv)],
    ]
    refusPresta_style = TableStyle(
        [
            ("FONTSIZE", (1, 0), (1, 0), grandePolice),
            ("VALIGN", (1, 0), (1, 0), "TOP"),
            ("FONTSIZE", (1, 1), (1, 1), petitePolice),
        ]
    )
    refusPresta = Table(refusPresta_data, style=refusPresta_style)
    refusPresta.hAlign = 0
    refusPresta.spaceAfter = 10
    elements.append(refusPresta)

    # ABSENT
    absentPresta_data = [
        [eval(get_image_ouverture_rdv(lettre_commande.ouverture_rdv, ouvertureRdv.ABSENT)), "NE S'EST PAS PRESENTE"]
    ]
    absentPresta_style = TableStyle([("FONTSIZE", (1, 0), (1, 0), grandePolice), ("VALIGN", (1, 0), (1, 0), "TOP")])
    absentPresta = Table(absentPresta_data, style=absentPresta_style)
    absentPresta.hAlign = 0
    absentPresta.spaceAfter = 10
    elements.append(absentPresta)

    # REPORT
    reportPresta_data = [
        [
            eval(get_image_ouverture_rdv(lettre_commande.ouverture_rdv, ouvertureRdv.REPORT)),
            "A DEMANDE AU PRESTATAIRE UN REPORT DU PREMIER RDV",
        ],
        [None, "(8 jours maxi)"],
    ]
    reportPresta_style = TableStyle(
        [
            ("FONTSIZE", (1, 0), (1, 0), grandePolice),
            ("FONTSIZE", (1, 1), (1, 1), basePolice),
            ("VALIGN", (1, 0), (1, 0), "TOP"),
        ]
    )
    reportPresta = Table(reportPresta_data, style=reportPresta_style)
    reportPresta.hAlign = 0
    reportPresta.spaceAfter = 10
    elements.append(reportPresta)

    newDateTime_data = [
        [
            None,
            "Date du nouveau RDV: " + get_newdate_ouverture_rdv(lettre_commande.ouverture_rdv),
            "Heure du nouveau RDV: " + get_newtime_ouverture_rdv(lettre_commande.ouverture_rdv),
        ]
    ]
    newDateTime_style = TableStyle([("FONTSIZE", (0, 0), (-1, -1), basePolice)])
    newDateTime = Table(newDateTime_data, style=newDateTime_style)
    newDateTime.hAlign = 0
    newDateTime.spaceAfter = 20
    elements.append(newDateTime)

    # Barre Horizontale
    elements.append(barreHorizontale)

    # ABANDON PRESTATION
    abandonPresta_data = [
        [empty_checkbox, "A ABANDONNE EN COURS DE PRESTATION A LA DATE DU:"],
        [None, "Indiquer le motif:"],
    ]
    abandonPresta_style = TableStyle(
        [
            ("FONTSIZE", (1, 0), (1, 0), grandePolice),
            ("VALIGN", (1, 0), (1, 0), "TOP"),
            ("FONTSIZE", (1, 1), (1, 1), basePolice),
        ]
    )
    abandonPresta = Table(abandonPresta_data, style=abandonPresta_style)
    abandonPresta.hAlign = 0
    abandonPresta.spaceAfter = 20
    elements.append(abandonPresta)

    # Barre Horizontale
    elements.append(barreHorizontale)

    # DISCLAIMER
    disclaimer_style = styles.getSampleStyleSheet()["Normal"]
    disclaimer_style.textColor = colors.grey
    disclaimer_style.fontSize = grandePolice
    disclaimer_style.alignment = enums.TA_CENTER
    disclaimer = Paragraph(
        "<strong>LES EVENEMENTS DOIVENT ETRE SIGNALES A LA PLATEFORME DES QUE POSSIBLE ET AU PLUS TARD DANS LES 48 HEURES -  01 49 44 42 86<strong>",
        disclaimer_style,
    )
    elements.append(disclaimer)

    # Write the document to disk
    doc.build(elements)
Example #39
0
    def gen_main_info(self):
        """
        Генерирует элементы для основоного отчета,
        в котором будет данные о заправках. \n
        Не формирует статистистическую информацию! \n
        Данные:
        - Дата заправки;
        - Название заправки;
        - Расстояние пройденное до этой заправки(мили);
        - Цена одного галлона(центы);
        - Расстояние, пройденное после предыдущей заправки(мили);
        - Количество галлонов;
        - Общая стоимость заправки(доллары);
        - Расстояние пройденно на одном галлоне(мили);
        - Цена одной мили(доллары);
        - Цена одного дня(доллары);

        Returns
        -------
        list:
            Список элементов основного отчета
        """

        elements = []

        # Получаем данные из базы данных
        # Условия получения информации из вьюшки для цены дня:
        # Если дата текущей заправки равна дате предыдущей заправки,
        # то прибавляем ее цену к сумме.
        # Если даты разные, то сохраняем сумму в предыдущую заправку, затем
        # сумму приравниваем к цене текущей запраки.
        table_data = self.table_data_to_list(
            self.db.select("v_trans vv",
                           """dtime,
                           name,
                           odometer,
                           mbs,
                           price,
                           amount,
                           cost,
                           mpg,
                           mile_price,
                           CASE next_dtime = dtime
                              WHEN FALSE
                                THEN (
                                      SELECT SUM(v.cost) 
                                      FROM v_trans v 
                                      WHERE v.dtime = vv.dtime AND
                           """ + self.condition + """
                                      GROUP BY v.dtime
                                     )
                           END
                            """,
                           condition=self.condition,
                           order_by="dtime"))

        table_data.insert(0, [
            "DATE", "GAS \n STATION", "ODOMETER", "MILIAGE \n BEETWEEN",
            "GALLON \n PRICE", "GALLONS", "COST", "MPG", "MILE \n PRICE",
            "DAY \n PRICE"
        ])

        # После получения данных из вьюшки нужно создать список,
        # в котором будут хранится строки,
        # которые нужно объединить объединить в таблице.
        # Элемент списка будет выглядить вот так: [s_cell, e_cell]
        merge_rows = []
        merging = False
        # В списке, который мы получили от базы данны, проверяем:
        self.logger.debug("Creating merging rows list for document's table")
        for i in range(1, len(table_data)):
            # Если ячейка цены дня пустая и флажок объединения не активен:
            if table_data[i][9] is None and merging is False:
                # Записываем текущую строку, как начальную для объединения и
                # активируем флажок объединения.
                merge_rows.append([
                    i,
                ])
                merging = True
            # Если ячейка цены дня не пустая и флажок объединения активен,
            elif table_data[i][9] is not None and merging is True:
                # то указываем текущую ячейку, как конечную для объединения и
                # выключаем флажок объединения.
                table_data[merge_rows[len(merge_rows) -
                                      1][0]][9] = table_data[i][9]
                merge_rows[len(merge_rows) - 1].append(i)
                merging = False
        self.logger.debug("Merging rows is " + str(merge_rows))
        self.logger.info("Merging rows list was created")

        # Создаем таблицу
        self.logger.debug("Creating document's main table")
        table = Table(table_data, repeatRows=True)
        table_style = [("BACKGROUND", (0, 0), (-1, 0), colors.lightblue),
                       ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                       ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                       ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
                       ('ALIGN', (0, 0), (-1, 0), "CENTER"),
                       ('ALIGN', (2, 1), (-1, -1), "RIGHT")]
        # Обединяем строки в таблице
        for row in merge_rows:
            table_style.append(("SPAN", (9, row[0]), (9, row[1])))

        table.setStyle(TableStyle(table_style))
        self.logger.info("Document's main table was created")
        elements.append(table)
        elements.append(Spacer(0, 20))

        return elements
Example #40
0
    def _render_month(self, month):
        '''Render one page with a month.'''
        
        table_data = self._calendar.monthdayscalendar(self.year, month)
        table_data = [ [ day or None for day in week ] for week in table_data ]

        table = Table(table_data,
            colWidths=(self.cell_width,) * 7,
            rowHeights=(self.cell_height,) * len(table_data)
        )

        style = TableStyle()
        for padding in ("TOP", "RIGHT", "BOTTOM", "LEFT"):
            style.add(padding + "PADDING", (0, 0), (-1, -1), self.cell_padding)
        for position in ("BEFORE", "AFTER", "ABOVE", "BELOW"):
            style.add("LINE" + position, (0, 0), (-1, -1), self.cell_spacing / 2, colors.white)

        font_name = font_loader.get_font_name(self.cell_font_name, self.cell_font_variant)
        style.add("FONT", (0, 0), (-1, -1), font_name, self.cell_font_size)
        style.add("ALIGN", (0, 0), (-1, -1), "RIGHT")
        style.add("VALIGN", (0, 0), (-1, -1), "MIDDLE")
        style.add("BACKGROUND", (0, 0), (-1, -1), self.week_bgcolor)
        style.add("TEXTCOLOR", (0, 0), (-1, -1), self.week_color)

        self._style_holidays_and_special_days(month, style)

        table.setStyle(style)
        table_width, table_height = table.wrapOn(self.canvas, 7*self.cell_width, 6*self.cell_height)
        table.drawOn(self.canvas, self.margins[3], self.margins[2])
        
        # Render title
        title_position = (self.margins[3], self.margins[2] + table_height + self.title_margin)
        self.set_font(self.title_font_name, self.title_font_size, variant=self.title_font_variant)
        self.canvas.drawString(title_position[0], title_position[1], self.locale.month_title(self.year, month))

        # Render picture
        self._render_picture(month, self.content_height - self.title_font_size - 2 * self.title_margin - table_height)
        self.canvas.showPage()
Example #41
0
    def get_story(self, doc, form_data):
        from reportlab.platypus import Paragraph, Spacer, TableStyle, Table
        from reportlab.lib.units import mm

        headlinestyle = self.get_style()
        headlinestyle.fontSize = 15
        headlinestyle.fontName = 'OpenSansBd'
        tz = pytz.timezone(self.event.settings.timezone)

        tax_rates = set(a for a in OrderFee.objects.filter(
            order__event=self.event).values_list(
                'tax_rate', flat=True).distinct().order_by())
        tax_rates |= set(a for a in OrderPosition.objects.filter(
            order__event=self.event).filter(
                order__status__in=self.form_data['status']).values_list(
                    'tax_rate', flat=True).distinct().order_by())
        tax_rates = sorted(tax_rates)

        # Cols: Order ID | Order date | Status | Payment Date | Total | {gross tax} for t in taxes
        colwidths = [a * doc.width for a in [0.12, 0.1, 0.10, 0.12, 0.08]]
        if tax_rates:
            colwidths += [0.48 / (len(tax_rates) * 2) * doc.width
                          ] * (len(tax_rates) * 2)

        tstyledata = [
            # Alignment
            ('ALIGN', (0, 0), (3, 0), 'LEFT'),  # Headlines
            ('ALIGN', (4, 0), (-1, 0), 'CENTER'),  # Headlines
            ('ALIGN', (4, 1), (-1, -1), 'RIGHT'),  # Money
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),

            # Fonts
            ('FONTNAME', (0, 0), (-1, 0), 'OpenSansBd'),  # Headlines
            ('FONTNAME', (0, -1), (-1, -1), 'OpenSansBd'),  # Sums
        ]
        for i, rate in enumerate(tax_rates):
            tstyledata.append(('SPAN', (5 + 2 * i, 0), (6 + 2 * i, 0)))

        story = [
            Paragraph(
                _('Orders by tax rate ({currency})').format(
                    currency=self.event.currency), headlinestyle),
            Spacer(1, 5 * mm)
        ]
        tdata = [
            [
                _('Order code'),
                _('Order date'),
                _('Status'),
                _('Payment date'),
                _('Order total'),
            ] + sum(([str(t) + ' %', ''] for t in tax_rates), []),
            ['', '', '', '', ''] + sum(
                ([_('Gross'), _('Tax')] for t in tax_rates), []),
        ]

        op_date = OrderPayment.objects.filter(
            order=OuterRef('order'),
            state__in=(OrderPayment.PAYMENT_STATE_CONFIRMED,
                       OrderPayment.PAYMENT_STATE_REFUNDED),
            payment_date__isnull=False).values('order').annotate(
                m=Max('payment_date')).values('m').order_by()
        qs = OrderPosition.objects.filter(
            order__status__in=self.form_data['status'],
            order__event=self.event,
        ).annotate(payment_date=Subquery(
            op_date, output_field=models.DateTimeField())).values(
                'order__code', 'order__datetime', 'payment_date',
                'order__total', 'tax_rate', 'order__status',
                'order__id').annotate(
                    prices=Sum('price'), tax_values=Sum('tax_value')).order_by(
                        'order__datetime' if self.form_data['sort']
                        == 'datetime' else 'payment_date', 'order__datetime',
                        'order__code')
        fee_sum_cache = {
            (o['order__id'], o['tax_rate']): o
            for o in OrderFee.objects.values('tax_rate', 'order__id').order_by(
            ).annotate(taxsum=Sum('tax_value'), grosssum=Sum('value'))
        }

        last_order_code = None
        tax_sums = defaultdict(Decimal)
        price_sums = defaultdict(Decimal)
        status_labels = dict(Order.STATUS_CHOICE)
        for op in qs:
            if op['order__code'] != last_order_code:
                tdata.append([
                    op['order__code'],
                    date_format(op['order__datetime'].astimezone(tz),
                                "SHORT_DATE_FORMAT"),
                    status_labels[op['order__status']],
                    date_format(op['payment_date'], "SHORT_DATE_FORMAT")
                    if op['payment_date'] else '',
                    localize(
                        round_decimal(op['order__total'], self.event.currency))
                ] + sum((['', ''] for t in tax_rates), []), )
                last_order_code = op['order__code']
                for i, rate in enumerate(tax_rates):
                    odata = fee_sum_cache.get((op['order__id'], rate))
                    if odata:
                        tdata[-1][5 + 2 * i] = str(odata['grosssum'] or 0)
                        tdata[-1][6 + 2 * i] = str(odata['taxsum'] or 0)
                        tax_sums[rate] += odata['taxsum'] or 0
                        price_sums[rate] += odata['grosssum'] or 0

                i = tax_rates.index(op['tax_rate'])
                tdata[-1][5 + 2 * i] = localize(
                    round_decimal(
                        Decimal(tdata[-1][5 + 2 * i] or '0') + op['prices'],
                        self.event.currency))
                tdata[-1][6 + 2 * i] = localize(
                    round_decimal(
                        Decimal(tdata[-1][6 + 2 * i] or '0') +
                        op['tax_values'], self.event.currency))
                tax_sums[op['tax_rate']] += op['tax_values']
                price_sums[op['tax_rate']] += op['prices']

        tdata.append([_('Total'), '', '', '', ''] + sum(([
            localize(
                round_decimal(
                    price_sums.get(t) or Decimal('0.00'),
                    self.event.currency)),
            localize(
                round_decimal(
                    tax_sums.get(t) or Decimal('0.00'), self.event.currency))
        ] for t in tax_rates), []), )

        table = Table(tdata, colWidths=colwidths, repeatRows=2)
        table.setStyle(TableStyle(tstyledata))
        story.append(table)
        return story
Example #42
0
    def drawTable(self, group=None, monocell=None, reiter = None, tabpro=None):
        """ Drawing a table """
        matrix = []
        lst = []
        matrix2 = []
        vector = []
        # Total of element's table
        n_cells = int(tabpro['n_cells'])
        columns = int(tabpro['columns'])
        rows = int(tabpro['rows'])
        celle = tabpro["cells"]
        widths = [float(x.get("WIDTH")) for x in celle]
        heights = [float(x.get("HEIGHT")) for x in celle]
        xpos = [float(x.get("XPOS")) for x in celle]
        ypos = [float(x.get("YPOS")) for x in celle]
        contColumns = 0
        ch = ''
        col = 0
        cycle = False
        vector = []
        alignment= None
        itexts = [x.findall("ITEXT") for x in celle]
        paras = [x.findall("para") for x in celle]
        trail = [x.findall("trail") for x in celle]
        stile = TableStyle([])
        stile.add('VALIGN',(0,0),(-1,-1),'TOP')
        if monocell==True:
            cells = 1
            columns=1
            rows = 1
        #print "CEEEEEEEEEEEEEELS", cells
        for v in range(0,n_cells):
            if v == 0:
                contRows = 0
                contColumns = 0
            elif columns==1:
                contColumns = -1
                contRows= int(v/columns)
            else:
                contRows= int(v/columns)
                contColumns = ((v)%columns)
#            print "VVVVVVVVVVVVV E CELLE", "celle", celle,"V:",v, "LEN DI CELLE",len(celle), "NCELLS", n_cells, group
            try:
                background = self.backgroundFunc(celle[v])# Finding background
            except Exception as e:
                Environment.pg2log.info("ERRORE NEL GRUPPO TABELLA"+ group + "ERRORE:" + str(e.args))
            hexBorderColor = self.hexBorderColorFunc(celle[v].get('PCOLOR2'))
            stile.add('ROWBACKGROUNDS', (contColumns,contRows),
                                (contColumns,contRows),
                                (background, background))
            cellpict = celle[v].get('PFILE')
            cellIMGHeight = celle[v].get('HEIGHT')
            cellIMGWidth = celle[v].get('WIDTH')
            bordoriga = False
            if (celle[v].get('BottomLine') == "1" and celle[v].get('TopLine') == "1" and\
                        celle[v].get('LeftLine') =="1" and celle[v].get('RightLine') == "1"):
                stile.add('BOX', (contColumns,contRows),
                                (contColumns,contRows),
                                float(celle[v].get('PWIDTH')),
                                hexBorderColor)
                bordoriga = True
            else:
                if celle[v].get('BottomLine') == "1":
                    stile.add('LINEBELOW', (contColumns,contRows),
                                (contColumns,contRows),
                                float(celle[v].get('PWIDTH')),
                                hexBorderColor)
                    bordoriga = True
                if celle[v].get('TopLine') == "1":
                    stile.add('LINEABOVE', (contColumns,contRows),
                                (contColumns,contRows),
                                float(celle[v].get('PWIDTH')),
                                hexBorderColor)
                    bordoriga = True
                if celle[v].get('LeftLine') == "1":
                    stile.add('LINEBEFORE', (contColumns,contRows),
                                (contColumns,contRows),
                                float(celle[v].get('PWIDTH')),
                                hexBorderColor)
                    bordoriga = True
                if celle[v].get('RightLine') == "1":
                    stile.add('LINEAFTER', (contColumns,contRows),
                                (contColumns,contRows),
                                float(celle[v].get('PWIDTH')),
                                hexBorderColor)
                    bordoriga = True
            if not bordoriga and str(celle[v].get('PCOLOR2')) != "None":
                stile.add('BOX', (contColumns,contRows),
                                (contColumns,contRows),
                                float(celle[v].get('PWIDTH')),
                                hexBorderColor)
            if not monocell:
                ch = self.chFunc(itexts[v])[0]
                itext = self.chFunc(itexts[v])[1]
            else:
                try:
                    itext = itexts[0]
                    ch = itexts[0].get('CH')
                except:
                    itext = None
                    ch = ""

            actualPageObject = tabpro # Borders

            pdfAlignment = self.alignmentFunc(paras,v, monocell, trail=trail, reiter=reiter) #alignment
            stile.add('ALIGN', (contColumns,contRows),
                                (contColumns,contRows),
                                pdfAlignment)
            if itext != None:

                fontSize = self.fontSizeFunc(itext,v=v, trail=trail)# Font size
                stile.add('FONTSIZE', (contColumns,contRows),
                                    (contColumns,contRows),
                                    fontSize)

                fontName = self.fontNameFunc(itext,trail=trail) #  Font name
                stile.add('FONT', (contColumns,contRows),
                                    (contColumns,contRows),
                                    fontName)

                foreground = self.foregroundFunc(itext) #foreground
                stile.add('TEXTCOLOR', (contColumns,contRows),
                                    (contColumns,contRows),
                                    foreground)
                if "bcview" in ch:
                    alignment="LEFT"
                    vector.append(Sla2pdfUtils.createbarcode(ch))
                else:
                    vector.append(Sla2pdfUtils.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize))
            elif cellpict:
                (imgPath, imgFile) = os.path.split(cellpict)
                path = Environment.imagesDir + imgFile
                widthIMG = (float(cellIMGHeight)-2)*100/(float(cellIMGWidth)-2)
                img = Image(path,width=widthIMG,height=float(cellIMGHeight)-2)
                vector.append(img)
            else:
                vector.append('')
            if monocell==True:
                cycle= True
            elif ((v+1)%columns) == 0:
                contRows = 0
                cycle= True
            if cycle == True:
                matrix.append(vector)
                vector = []
                cycle = False
        table=Table(matrix,style=stile,  colWidths=widths[:columns], rowHeights=heights[:rows])
        lst.append(table)
        # Effective table size
        sumRows = Sla2pdfUtils.sumRowsFunc(heights,rows)
        sumColumns = Sla2pdfUtils.sumColumnsFunc(widths,columns)
        f = Frame(x1=(xpos[0] - self.pageProperties[self.pdfPage][9]),
                    y1=(self.pageProperties[self.pdfPage][7] - ypos[0] - sumRows + self.pageProperties[self.pdfPage][10] - 12),
                    width=sumColumns,
                    height=(sumRows+12),
                    showBoundary=0)
        sumRows = sumColumns = 0
        f.addFromList(lst, self.canvas)
        reiter = False
Example #43
0
        def drawTable():
            """ Drawing a table """
            matrix = []
            vector = []

            # Total of element's table
            actualGroup = self.group
            cells = int(self.tablesProperties[actualGroup]['cells'])
            columns = int(self.tablesProperties[actualGroup]['columns'])
            rows = int(self.tablesProperties[actualGroup]['rows'])

            # Finding cell size
            cont = 0
            widths = []
            heights = []
            innerIterator = self.iterator
            xpos = float(self.pageObjects[innerIterator].get('XPOS'))
            ypos = float(self.pageObjects[innerIterator].get('YPOS'))
            while actualGroup == self.group and innerIterator < len(self.pageObjects):
                cont += 1
                actualGroup = self.pageObjects[innerIterator].get('GROUPS')
                if actualGroup == self.group:
                    width = float(self.pageObjects[innerIterator].get('WIDTH'))
                    widths.append(width)
                    if cont == columns:
                        height = float(self.pageObjects[innerIterator].get('HEIGHT'))
                        heights.append(height)
                        cont = 0
                    innerIterator += 1

            # General table style (always the same!!!)
            stile = TableStyle([])
            stile.add('VALIGN',(0,0),(-1,-1),'TOP')

            # Applying stile, font and color for every cell
            contColumns = -1
            contRows = 0
            ch = ''
            cont = 0
            vector = []
            actualGroup = self.group
            innerIterator = self.iterator
            alignment = " "

            while actualGroup == self.group and innerIterator < len(self.pageObjects):
                actualGroup = self.pageObjects[innerIterator].get('GROUPS')
                actualPage = int(self.pageObjects[innerIterator].get('OwnPage'))

                if actualPage != self.pdfPage:
                    innerIterator += 1
                    continue

                if actualGroup == self.group:
                    # Conversion between index - row/column
                    contColumns += 1
                    if contColumns == columns:
                        contColumns = 0
                        contRows += 1

                    # Finding background
                    cellBackground = self.pageObjects[innerIterator].get('PCOLOR')
                    if cellBackground in self.colorList:
                        try:
                            hexColor = self.colorList[cellBackground]
                            background = colors.HexColor(str(hexColor))
                        except:
                            background = colors.HexColor('#ffffff')
                    else:
                        background = colors.HexColor('#ffffff')
                    stile.add('ROWBACKGROUNDS', (contColumns,contRows), (contColumns,contRows), (background, background))
                    itexts = self.pageObjects[innerIterator].findall('ITEXT')
                    put = False
                    if self.version:
                        paras = self.pageObjects[innerIterator].findall('para')
                    if len(itexts)>=1:
                            if len(itexts)>1:
                                for itext in itexts:
                                    chtmp = itext.get('CH')
                                    ch = ch +" "+ chtmp
                                itext = itexts[0]

                            else:
                                itext = itexts[0]
                                ch = itext.get('CH')
                            if self.version:
                                #try:
                                alignment = paras[0].get('ALIGN')
                                #except:
                                    #alignment = "0"
                            else:
                                alignment = itext.get('CAB')
                            if alignment == None:
                                alignment = self.defaultAlignment
                            if alignment == '0':
                                alignment = 'LEFT'
                            elif alignment == '1':
                                alignment = 'CENTER'
                            elif alignment == '2':
                                alignment = 'RIGHT'
                            else:
                                alignment = "LEFT"
                            stile.add('ALIGN', (contColumns,contRows), (contColumns,contRows), alignment)

                            # Font name
                            if self.version:
                                fontName = getPdfFontName(str(itext.get('FONT')))
                            else:
                                fontName = getPdfFontName(str(itext.get('CFONT')))
                            stile.add('FONT', (contColumns,contRows), (contColumns,contRows), fontName)

                            # Font size
                            if self.version:
                                try:
                                    print "TEEEEE", itext.get('FONTSIZE')
                                    fontSize = float(itext.get('FONTSIZE'))
                                except:
                                    fontSize = float(10)
                            else:
                                fontSize = float(itext.get('CSIZE'))

                            stile.add('FONTSIZE', (contColumns,contRows), (contColumns,contRows), fontSize)

                            # Hex color
                            textColor = itext.get('FCOLOR')
                            if textColor in self.colorList:
                                try:
                                    hexColor = self.colorList[textColor]
                                    foreground = colors.HexColor(str(hexColor))
                                except:
                                    foreground = colors.HexColor('#000000')
                            else:
                                foreground = colors.HexColor('#000000')
                            stile.add('TEXTCOLOR', (contColumns,contRows), (contColumns,contRows), foreground)

                            # Borders
                            actualPageObject = self.pageObjects[innerIterator]
                            bottomLine = int(actualPageObject.get('BottomLine'))
                            topLine = int(actualPageObject.get('TopLine'))
                            leftLine = int(actualPageObject.get('LeftLine'))
                            rightLine = int(actualPageObject.get('RightLine'))
                            lineWidth = float(actualPageObject.get('PWIDTH'))

                            borderColor = actualPageObject.get('PCOLOR2')
                            if borderColor in self.colorList:
                                try:
                                    hexBorderColor = self.colorList[borderColor]
                                except:
                                    hexBorderColor = '#000000'
                            else:
                                hexBorderColor = '#000000'

                            if (bottomLine == 1 and topLine == 1 and leftLine == 1 and rightLine == 1):
                                stile.add('BOX', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor)
                            else:
                                if bottomLine == 1:
                                    stile.add('LINEBELOW', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor)
                                elif topLine == 1:
                                    stile.add('LINEABOVE', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor)
                                if leftLine == 1:
                                    stile.add('LINEBEFORE', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor)
                                if rightLine == 1:
                                    stile.add('LINEAFTER', (contColumns,contRows), (contColumns,contRows), lineWidth, hexBorderColor)

                            vector.append(self.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize))
                            put = True
                    if put == False:
                        vector.append('')
                    cont += 1
                    if cont == columns:
                        #print "VECTORRRR ", vector
                        matrix.append(vector)
                        vector = []
                        cont = 0
                    test = None
                    innerIterator += 1

            # Creating and filling table
            #print "matrix", matrix
            table=Table(matrix, style=stile, colWidths=widths[:columns], rowHeights=heights[:rows])

            # Adding cell to the frame and save it
            lst = []
            lst.append(table)

            # Effective table size
            sumRows = 0
            sumColumns = 0
            for i in range(0, rows):
                sumRows += heights[i]
            for i in range(0, columns):
                sumColumns += widths[i]

            f = Frame(x1=(xpos - self.pageProperties[self.pdfPage][9]),
                      y1=(self.pageProperties[self.pdfPage][7] - ypos - sumRows + self.pageProperties[self.pdfPage][10] - 12),
                      width=sumColumns,
                      height=(sumRows+12),
                      showBoundary=0)
            f.addFromList(lst, self.canvas)
            self.canvas.saveState()

            self.iterator += cells - 1
def generate_report(report, the_file, report_data):


    cloud = WordCloud(width=235, height=145, background_color='white', max_font_size=20, margin=0,
                      color_func=my_color_func, prefer_horizontal=1.0, relative_scaling=0.4)
    cloud.generate_from_frequencies(report_data['wordcloud_data'])

    sentiment_and_cloud = Drawing(width=530, height=180)
    sentiment_and_cloud.add(MyChartFrame(x=0,y=0,width=260,height=180,title='Sentiment'))
    sentiment_and_cloud.add(MyChartFrame(x=270,y=0,width=260,height=180,title='Trending Words'))
    if report_data.get('sentiment_bench_data', None):
        MySentimentComparoChart(drawing=sentiment_and_cloud, title=report.query, data=report_data['sentiment_data'], bench_data=report_data['sentiment_bench_data'])
    else:
        MySentimentChart(drawing=sentiment_and_cloud, data=report_data['sentiment_data'])
    draw_wordcloud(sentiment_and_cloud, cloud, x=285, y=13)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='LatoNormal', parent=styles['Normal'], fontName='Lato'))
    styles.add(ParagraphStyle(name='LatoTitle', parent=styles['Normal'], fontName='Lato-Bold', fontSize=16))

    tbl_style = TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black),
                            ('BOX', (0,0), (-1,-1), 0.25, black),
                            ('FACE', (0, 0), (-1, 0), 'Lato-Bold'),
                            ('ALIGN', (1,1), (-1,-1), 'LEFT')])

    languages_and_publications = Drawing(width=530, height=180)
    languages_and_publications.add(MyChartFrame(x=0,y=0,width=260,height=180,title='Languages'))
    languages_and_publications.add(MyChartFrame(x=270,y=0,width=260,height=180,title='Publications'))
    if report_data.get('sentiment_bench_data', None):
        MyHBarChart(drawing=languages_and_publications, title=report.query, data=report_data['languages_data'])
    else:
        MyPieChart(drawing=languages_and_publications, data=report_data['languages_data'])
    MyHBarChart(drawing=languages_and_publications, data=report_data['publication_data'], x=390, width=130)

    rep_drivers = Drawing(width=530, height=125)
    rep_drivers.add(MyChartFrame(x=0,y=0,width=530,height=125,title='Brand Pillars'))
    MyVBarChart(drawing=rep_drivers, title=report.title, data=report_data['reputation_data'])

    media_types_and_sites = Drawing(width=528, height=180)
    media_types_and_sites.add(MyChartFrame(x=0,y=0,width=259,height=180,title='Media Types'))
    media_types_and_sites.add(MyChartFrame(x=269,y=0,width=259,height=180,title='Top Sites'))
    MyPieChart(drawing=media_types_and_sites, data=report_data['media_type_data'])
    #MyHBarChart(drawing=media_types_and_sites, data=media_type_data)
    MyHBarChart(drawing=media_types_and_sites, data=report_data['sites_data'], x=405, width=115)

    articles = [
        [Paragraph(item or '', styles['LatoNormal']) for item in article]
        for article in report_data['articles']
    ]

    elements = [
        Paragraph('Media Scan: %s' % report.title, styles['LatoTitle']),
        Spacer(width=1, height=20),
        MyVolumeChart(data=report_data['volume_chart_data'], legend_data=report_data['volume_legend_data']),
        Spacer(width=1, height=10),
        sentiment_and_cloud,
        Spacer(width=1, height=10),
        rep_drivers,
        Spacer(width=1, height=10),
        languages_and_publications,
        media_types_and_sites,
        Spacer(width=1, height=10),
        Table(data=[('Date', 'Publication', 'Title')] + articles, style=tbl_style,
              colWidths=(2.5*cm, 4.5*cm, '*'), vAlign='LEFT'),
    ]

    def add_header(canvas, doc):
        canvas.saveState()
        canvas.drawImage('feed_harvesting/static/reportly.png', 20, A4[1]-35, width=85, height=21, mask='auto')
        canvas.setFont('Lato', 10)
        canvas.drawRightString(A4[0]-20, A4[1]-25, "www.reportly.nl")
        canvas.drawRightString(A4[0]-20, A4[1]-35, "*****@*****.**")
        canvas.line(x1=20, y1=A4[1]-45, x2=A4[0]-20, y2=A4[1]-45)
        canvas.line(x1=20, y1=45, x2=A4[0]-20, y2=45)
        canvas.restoreState()

    doc = SimpleDocTemplate(the_file, pagesize=A4, initialFontName='Lato',
                            topMargin=2*cm, bottomMargin=2*cm, leftMargin=1*cm, rightMargin=1*cm)
    doc.build(elements, onFirstPage=add_header, onLaterPages=add_header)

    the_file.seek(0)
Example #45
0
    def get_story(self, doc, form_data):
        from reportlab.platypus import Paragraph, Spacer, TableStyle, Table
        from reportlab.lib.units import mm

        if form_data.get('date_from'):
            form_data['date_from'] = parse(form_data['date_from'])
        if form_data.get('date_until'):
            form_data['date_until'] = parse(form_data['date_until'])

        headlinestyle = self.get_style()
        headlinestyle.fontSize = 15
        headlinestyle.fontName = 'OpenSansBd'
        colwidths = [
            a * doc.width for a in (.33, 0.05, .075, 0.05, .075, 0.05, .075,
                                    0.05, .075, 0.05, .075)
        ]
        tstyledata = [
            ('SPAN', (1, 0), (2, 0)),
            ('SPAN', (3, 0), (4, 0)),
            ('SPAN', (5, 0), (-1, 0)),
            ('SPAN', (5, 1), (6, 1)),
            ('SPAN', (7, 1), (8, 1)),
            ('SPAN', (9, 1), (10, 1)),
            ('ALIGN', (0, 0), (-1, 1), 'CENTER'),
            ('ALIGN', (1, 2), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('FONTNAME', (0, 0), (-1, 1), 'OpenSansBd'),
            ('FONTNAME', (0, -1), (-1, -1), 'OpenSansBd'),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('LINEBEFORE', (1, 0), (1, -1), 1, colors.lightgrey),
            ('LINEBEFORE', (3, 0), (3, -1), 1, colors.lightgrey),
            ('LINEBEFORE', (5, 0), (5, -1), 1, colors.lightgrey),
            ('LINEBEFORE', (7, 1), (7, -1), 1, colors.lightgrey),
            ('LINEBEFORE', (9, 1), (9, -1), 1, colors.lightgrey),
        ]

        story = [
            Paragraph(_('Orders by product'), headlinestyle),
            Spacer(1, 5 * mm)
        ]
        if form_data.get('date_axis'):
            story += [
                Paragraph(
                    _('{axis} between {start} and {end}').format(
                        axis=dict(
                            OverviewFilterForm(
                                event=self.event).fields['date_axis'].choices)[
                                    form_data.get('date_axis')],
                        start=date_format(form_data.get('date_from'),
                                          'SHORT_DATE_FORMAT')
                        if form_data.get('date_from') else '–',
                        end=date_format(form_data.get('date_until'),
                                        'SHORT_DATE_FORMAT')
                        if form_data.get('date_until') else '–',
                    ), self.get_style()),
                Spacer(1, 5 * mm)
            ]

        if form_data.get('subevent'):
            try:
                subevent = self.event.subevents.get(
                    pk=self.form_data.get('subevent'))
            except SubEvent.DoesNotExist:
                subevent = self.form_data.get('subevent')
            story.append(
                Paragraph(
                    pgettext('subevent', 'Date: {}').format(subevent),
                    self.get_style()))
            story.append(Spacer(1, 5 * mm))
        tdata = [
            [
                _('Product'),
                _('Canceled'), '',
                _('Expired'), '',
                _('Purchased'), '', '', '', '', ''
            ],
            [
                '', '', '', '', '',
                _('Pending'), '',
                _('Paid'), '',
                _('Total'), ''
            ],
            [
                '',
                _('#'),
                self.event.currency,
                _('#'),
                self.event.currency,
                _('#'),
                self.event.currency,
                _('#'),
                self.event.currency,
                _('#'),
                self.event.currency,
            ],
        ]

        items_by_category, total = order_overview(
            self.event,
            subevent=form_data.get('subevent'),
            date_filter=form_data.get('date_axis'),
            date_from=form_data.get('date_from'),
            date_until=form_data.get('date_until'),
        )
        places = settings.CURRENCY_PLACES.get(self.event.currency, 2)
        states = (
            ('canceled', Order.STATUS_CANCELED),
            ('expired', Order.STATUS_EXPIRED),
            ('pending', Order.STATUS_PENDING),
            ('paid', Order.STATUS_PAID),
            ('total', None),
        )

        for tup in items_by_category:
            if tup[0]:
                tstyledata.append(('FONTNAME', (0, len(tdata)),
                                   (-1, len(tdata)), 'OpenSansBd'))
                tdata.append([
                    tup[0].name,
                ])
                for l, s in states:
                    tdata[-1].append(str(tup[0].num[l][0]))
                    tdata[-1].append(floatformat(tup[0].num[l][1], places))
            for item in tup[1]:
                tdata.append([str(item)])
                for l, s in states:
                    tdata[-1].append(str(item.num[l][0]))
                    tdata[-1].append(floatformat(item.num[l][1], places))
                if item.has_variations:
                    for var in item.all_variations:
                        tdata.append([
                            "          " + str(var),
                        ])
                        for l, s in states:
                            tdata[-1].append(str(var.num[l][0]))
                            tdata[-1].append(floatformat(
                                var.num[l][1], places))

        tdata.append([
            _("Total"),
        ])
        for l, s in states:
            tdata[-1].append(str(total['num'][l][0]))
            tdata[-1].append(floatformat(total['num'][l][1], places))

        table = Table(tdata, colWidths=colwidths, repeatRows=3)
        table.setStyle(TableStyle(tstyledata))
        story.append(table)
        return story
Example #46
0
def export_supplier_report(request):
    try:
        if request.method == 'POST':
            dataset = Supplier.objects.all()
            if not dataset.exists():
                messages.error(request, 'No Data Found')
                return redirect('report:supplier_report')

            if 'xls_export' in request.POST:
                response = HttpResponse(content_type='application/ms-excel')
                response[
                    'Content-Disposition'] = 'attachment; filename="Supplier Report.xls"'
                wb = xlwt.Workbook(encoding='utf-8', style_compression=2)
                ws = wb.add_sheet('supplier_report')
                row_num = 3

                font_style = xlwt.XFStyle()
                common = "font:name Calibri, bold on, height 200;  align:wrap yes, horiz center, vert center ;"
                common1 = "align: wrap yes, horiz right, vert center ;"

                columns = ['SL', 'Name', 'E-mail', 'Phone', 'Address']

                ws.write_merge(0, 1, 0, 5, 'Supplier Report',
                               xlwt.easyxf(common))
                for col in range(len(columns)):
                    ws.write(row_num, col, columns[col], font_style)
                row_num += 1
                for count, data in enumerate((dataset)):
                    ws.write(row_num, 0, count + 1, font_style)
                    ws.write(row_num, 1, data.name, font_style)
                    ws.write(row_num, 2, data.email, font_style)
                    ws.write(row_num, 3, data.phone, font_style)
                    ws.write(row_num, 4, data.address, xlwt.easyxf(common1))
                    row_num += 1

                wb.save(response)
                return response

            elif 'pdf_export' in request.POST:
                styles = getSampleStyleSheet()
                doc = SimpleDocTemplate(
                    "assets/pdf_files/Supplier Report.pdf",
                    pagesize=reportlab.lib.pagesizes.letter)
                parastyles = ParagraphStyle(
                    'header',
                    parent=styles['Normal'],
                    fontName='Helvetica-Bold',
                    fontSize=8,
                    alignment=TA_CENTER,
                    textColor=colors.black,
                )
                story = []
                elements = []
                columns = []
                columns.insert(0, [
                    Paragraph('S/L', parastyles),
                    Paragraph('Name', parastyles),
                    Paragraph('Email', parastyles),
                    Paragraph('Phone', parastyles),
                    Paragraph('Address', parastyles)
                ])

                texstyles = ParagraphStyle(
                    'text',
                    parent=styles['Normal'],
                    fontSize=8,
                    alignment=TA_CENTER,
                    textColor=colors.black,
                )
                j = 1

                for count, data in enumerate((dataset)):
                    columns.insert(j, [
                        Paragraph(str(j), texstyles),
                        Paragraph(str(data.name), texstyles),
                        Paragraph(str(data.email), texstyles),
                        Paragraph(str(data.phone), texstyles),
                        Paragraph(str(data.address), texstyles)
                    ])
                    j = j + 1

                t = Table(columns, repeatRows=1, splitByRow=1)
                t.setStyle(
                    TableStyle([('FONTSIZE', (0, 0), (-1, -1), 1),
                                ('INNERGRID', (0, 0), (-1, -1), 0.25,
                                 colors.gray),
                                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                ('VALIGN', (0, 0), (-1, -1), 'TOP')]))

                dateofpdf = (datetime.now()).strftime("%d/%m/%Y")
                story.append(Paragraph("Supplier Report", parastyles))
                story.append(Spacer(1, 0.2 * inch))
                story.append(
                    Paragraph("Printed Date: " + dateofpdf, styles['Normal']))
                story.append(Spacer(1, 0.2 * inch))
                story.append(Spacer(1, 0.2 * inch))
                elements.append(t)
                story.append(t)
                doc.build(story,
                          onFirstPage=myFirstPage,
                          onLaterPages=myLaterPages)
                fs = FileSystemStorage()
                with fs.open("pdf_files/Supplier Report.pdf") as pdf:
                    response = HttpResponse(pdf,
                                            content_type='application/pdf')
                    filename = "Supplier Report.pdf"
                    response[
                        'Content-Disposition'] = 'attachment; filename="{}"'.format(
                            filename)
                    return response
                return response
    except Exception as ex:
        messages.error(request, str(ex))
        mylog.exception('export_supplier_report', exc_info=True)
        return redirect('report:supplier_report')
Example #47
0
  def Set_Bills(self, Bill_List):
    self.Insert_First_Page_Header(Bill_List)
    Normal_Style=ParagraphStyle('normal')

    Right_Para_Style=ParagraphStyle(
      'right-col-style',
      parent=ParagraphStyle('normal'),
      alignment=TA_CENTER,
      fontSize=self.Right_Side_Font_Size,
      leading=self.Right_Side_Font_Size,
      spaceBefore=0,
      spaceAfter=0,
      textColor=colors.white,
      fontName='Helvetica-Bold')


    Number_And_Title_Para_Style=Normal_Style=ParagraphStyle('num-title-style',
      parent=Normal_Style, alignment=TA_LEFT,leftIndent=6, \
      textColor=colors.white,
      fontName='Helvetica-Bold',fontSize=12, leading=16, spaceBefore=0,
            spaceAfter=0)

    Committee_And_Recommend_Para_Style=ParagraphStyle('commit-recommend-style',
      parent=Normal_Style, alignment=TA_LEFT,leftIndent=6, \
      textColor=colors.white,
      fontName='Helvetica-Bold', fontSize=11, leading=15)

    Liberty_Type_And_Summary_Para_Style=ParagraphStyle('liberty-type-style',
      parent=Normal_Style, alignment=TA_LEFT,leftIndent=6, \
      textColor=colors.black,
      fontName='Helvetica-Bold', fontSize=11, leading=15)

    #
    # Convert the bill data into table format
    RL_Bill_Table=[]
    RL_Bill_Table_Style=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)
      ])

    #
    # Each time through this loop, we add all of the rows to the RL_Bill_Table
    Base_Row=0
    for Bill in Bill_List:
        URL_Text="<a href=http://www.nhliberty.org/bills/view/2016/" + \
          bill.Brief_Bill_Number(Bill.Number, Separator='') + ">"

        #
        # There may be specal cases where we have an entry that does not
        # have a bill number in which case we want to avoid dropping
        # in our normal text with a comma and just go blank
        #
        if len(Bill.Number.strip()) > 0:
          Number_And_Title_Para=Paragraph(URL_Text + Bill.Number + '</a>, ' +
            utils.Normalize_Text(Bill.Title), Number_And_Title_Para_Style)
        else:
          Number_And_Title_Para=Paragraph(utils.Normalize_Text(Bill.Title),\
                                          Number_And_Title_Para_Style)

        Number_Only_Para = Paragraph(bill.Brief_Bill_Number(Bill.Number), \
        Right_Para_Style)
        RL_Bill_Table.append([Number_And_Title_Para, Number_Only_Para])

        Committee_And_Recommendation_Para=Paragraph(Bill.Committee + ': ' +
          Bill.Committee_Recommendation, Committee_And_Recommend_Para_Style)
        RL_Bill_Table.append([Committee_And_Recommendation_Para, ''])

        Liberty_Type_And_Summary_Para=Paragraph(Bill.Liberty_Type.upper()\
           + ': ' + utils.Normalize_Text(Bill.NHLA_Summary), \
           Liberty_Type_And_Summary_Para_Style)
        NHLA_Recommend_Para=Paragraph(Bill.NHLA_Recommendation, \
                                      Right_Para_Style)
        RL_Bill_Table.append([Liberty_Type_And_Summary_Para, \
                             NHLA_Recommend_Para])

        RL_Bill_Table.append([utils.To_Bullet_List(Bill.GS_Blurb), ''])

        RL_Bill_Table_Style.add('BACKGROUND',(0,Base_Row), (0,Base_Row),\
           colors.black)
        RL_Bill_Table_Style.add('BACKGROUND',(0,Base_Row+1), (0,Base_Row+1),\
           ["HORIZONTAL", colors.HexColor(0x606060), colors.black])
        RL_Bill_Table_Style.add('BACKGROUND',(0,Base_Row+2), (0,Base_Row+3),\
           colors.transparent)
        RL_Bill_Table_Style.add('VALIGN',(0,Base_Row),(0,Base_Row+3),"TOP")
        RL_Bill_Table_Style.add('VALIGN',(1, Base_Row), (1, Base_Row), "TOP")
        RL_Bill_Table_Style.add('VALIGN',(1, Base_Row+2), (1, Base_Row+3),\
           "MIDDLE")
        RL_Bill_Table_Style.add('SPAN', (1,Base_Row), (1,Base_Row+1))
        RL_Bill_Table_Style.add('SPAN', (1,Base_Row+2), (1,Base_Row+3))
        RL_Bill_Table_Style.add('BACKGROUND', (1,Base_Row), (1,Base_Row+1), \
          colors.black)
        RL_Bill_Table_Style.add('BACKGROUND', (1,Base_Row+2), (1,Base_Row+3),\
          ["VERTICAL", colors.black, colors.HexColor(0x606060)])
        RL_Bill_Table_Style.add('TOPPADDING',(1,Base_Row+2), (1,Base_Row+3),7)
        RL_Bill_Table_Style.add('BOTTOMPADDING',(1,Base_Row+2),\
           (1,Base_Row+3),7)
        RL_Bill_Table_Style.add('BOTTOMPADDING',(0,Base_Row+3),\
           (0,Base_Row+3),3)
        RL_Bill_Table_Style.add('NOSPLIT', (0,Base_Row),(1,Base_Row+3))
        Base_Row=Base_Row+4

    #
    # Reportlab does not take kindly to inserting a table with no rows so
    # if we've ended up with a zero length table, don't insert it
    #
    if len(RL_Bill_Table) > 0:
      t=BetterTable(RL_Bill_Table, [7.06*inch, 1.44*inch])
      t.setStyle(RL_Bill_Table_Style)
      self.doc.elements.append(t)
Example #48
0
    def handle(self, *args, **options):
        if len(args) != 0:
            raise CommandError(_("Command doesn't accept any arguments"))

        by_domain = options.get('by_domain')
        domain_name = options.get('domain_name')
        copy_admin = options.get('copy_admin')
        period = options.get('period')
        include_daily = options.get('include_daily')
        startdate =  options.get('startdate')
        end_date =  options.get('enddate')
        enddate = None

        if startdate and end_date:
            if not checkdate(startdate) or not checkdate(end_date):
                raise CommandError(_("The startdate, enddate specified is invalid"))
            daterange = (startdate, end_date)
        else:
            daterange = None

        period_re = re.compile(r"(?P<num>(\d+))\s+(?P<period>(day|week|month))(?:s)?")
        if period:
            match = period_re.match(period)
            if not match:
                raise CommandError(_("The period you specified is invalid"))
            num = match.group('num')
            ptype = match.group('period')
            if not ptype.endswith('s'):
                ptype = ptype + 's'
            delta = datetime.timedelta(**{ptype: int(num)})
            enddate = datetime.date.today() - delta

        table_style = TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Helvetica'),
            ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('GRID', (0, 0), (-1, -1), 0.15, colors.black),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('ALIGN', (4, 1), (-1, -1), 'CENTER'),
            ('ALIGN', (0, 0), (0, -1), 'CENTER'),
            ('VALIGN', (4, 1), (-1, -1), 'MIDDLE'),
            ('SPAN', (4, 1), (-1, -1)),
        ])

        styles = getSampleStyleSheet()

        reports = [
            [
                'from_address', {'from_address__exact': ""}, 'num_count',
                'Top senders by quantity'],
            [
                'from_address', {'from_address__exact': ""}, 'total_size',
                'Top senders by volume'],
            [
                'from_domain', {'from_domain__exact': ""}, 'num_count',
                'Top sender domains by quantity'],
            [
                'from_domain', {'from_domain__exact': ""}, 'total_size',
                'Top sender domains by volume'],
            [
                'to_address', {'to_address__exact': ""}, 'num_count',
                'Top recipients by quantity'],
            [
                'to_address', {'to_address__exact': ""}, 'total_size',
                'Top recipients by volume'],
            [
                'to_domain', {'to_domain__exact': "",
                'to_domain__isnull': False}, 'num_count',
                'Top recipient domains by quantity'],
            [
                'to_domain', {'to_domain__exact': "",
                'to_domain__isnull': False}, 'total_size',
                'Top recipient domains by volume'],
        ]

        emails = []
        admin_addrs = []
        if copy_admin:
            mails = User.objects.values('email').filter(is_superuser=True)
            admin_addrs = [mail['email'] for mail in mails]

        from_email = getattr(settings, 'DEFAULT_FROM_EMAIL',
            'postmaster@localhost')
        url = getattr(settings, 'QUARANTINE_REPORT_HOSTURL', '')
        logo_dir = getattr(settings, 'MEDIA_ROOT', '')
        img = Image(logo_dir + '/imgs/css/logo.jpg')

        def build_chart(data, column, order, title):
            "build chart"
            headings = [('', _('Address'), _('Count'), _('Volume'), '')]
            rows = [[draw_square(PIE_CHART_COLORS[index]),
            tds_trunc(row[column], 45), row['num_count'],
            filesizeformat(row['total_size']), '']
            for index, row in enumerate(data)]

            if len(rows) != 10:
                missing = 10 - len(rows)
                add_rows = [
                    ('', '', '', '', '') for ind in range(missing)
                    ]
                rows.extend(add_rows)

            headings.extend(rows)
            dat = [row[order] for row in data]
            total = sum(dat)
            labels = [
                    ("%.1f%%" % ((1.0 * row[order] / total) * 100))
                    for row in data
                ]

            pie = PieChart()
            pie.chart.labels = labels
            pie.chart.data = dat
            headings[1][4] = pie

            table_with_style = Table(headings, [0.2 * inch,
                2.8 * inch, 0.5 * inch, 0.7 * inch, 3.2 * inch])
            table_with_style.setStyle(table_style)

            paragraph = Paragraph(title, styles['Heading1'])

            return [paragraph, table_with_style]

        def build_parts(account, enddate, isdom=None, daterange=None):
            "build parts"
            parts = []
            sentry = 0
            for report in reports:
                column = report[0]
                exclude_kwargs = report[1]
                order_by = "-%s" % report[2]
                order = report[2]
                title = report[3]

                if isdom:
                    #dom
                    data = Message.objects.values(column).\
                    filter(Q(from_domain=account.address) | \
                    Q(to_domain=account.address)).\
                    exclude(**exclude_kwargs).annotate(
                        num_count=Count(column), total_size=Sum('size')
                    ).order_by(order_by)
                    if daterange:
                        data.filter(date__range=(daterange[0], daterange[1]))
                    elif enddate:
                        data.filter(date__gt=enddate)
                    data = data[:10]
                else:
                    #all users
                    data = Message.report.all(user, enddate, daterange).values(
                            column).exclude(**exclude_kwargs).annotate(
                            num_count=Count(column), total_size=Sum('size')
                            ).order_by(order_by)
                    data = data[:10]

                if data:
                    sentry += 1
                    pgraphs = build_chart(data, column, order, title)
                    parts.extend(pgraphs)
                    parts.append(Spacer(1, 70))
                    if (sentry % 2) == 0:
                        parts.append(PageBreak())
            parts.append(Paragraph(_('Message Totals'), styles['Heading1']))
            if isdom:
                #doms
                msg_totals = MessageTotals.objects.doms(account.address, enddate)
            else:
                #norm
                filters = []
                addrs = [
                    addr.address for addr in UserAddresses.objects.filter(
                        user=account
                    ).exclude(enabled__exact=0)]
                if enddate:
                    efilter = {
                                'filter': 3,
                                'field': 'date',
                                'value': str(enddate)
                               }
                    filters.append(efilter)
                msg_totals = MessageTotals.objects.all(
                                account, filters, addrs,
                                profile.account_type,
                                daterange)

            mail_total = []
            spam_total = []
            virus_total = []
            dates = []
            if include_daily:
                rows = [(
                Table([[draw_square(colors.white),
                Paragraph('Date', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch, ]),
                Table([[draw_square(colors.green),
                Paragraph('Mail totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch, ]),
                Table([[draw_square(colors.pink),
                Paragraph('Spam totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch, ]),
                Table([[draw_square(colors.red),
                Paragraph('Virus totals', styles["Heading6"])]],
                [0.35 * inch, 1.50 * inch, ]),
                )]
            for ind, msgt in enumerate(msg_totals):
                if ind % 10:
                    dates.append('')
                else:
                    dates.append(str(msgt.date))

                mail_total.append(int(msgt.mail_total))
                spam_total.append(int(msgt.spam_total))
                virus_total.append(int(msgt.virus_total))
                if include_daily:
                    rows.append((str(msgt.date), msgt.mail_total,
                    msgt.spam_total, msgt.virus_total))

            graph = BarChart()
            graph.chart.data = [
                    tuple(mail_total), tuple(spam_total),
                    tuple(virus_total)
                ]
            graph.chart.categoryAxis.categoryNames = dates
            graph_table = Table([[graph]], [7.4 * inch])
            parts.append(graph_table)
            if include_daily:
                rows.append(('Totals', sum(mail_total), sum(spam_total),
                sum(virus_total)))
                parts.append(Spacer(1, 20))
                graph_table = Table(rows, [1.85 * inch, 1.85 * inch,
                1.85 * inch, 1.85 * inch, ])
                graph_table.setStyle(TableStyle([
                ('FONTSIZE', (0, 0), (-1, -1), 8),
                ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                ('GRID', (0, 0), (-1, -1), 0.15, colors.black),
                ('FONT', (0, -1), (-1, -1), 'Helvetica-Bold'),
                #('BACKGROUND', (0, -1), (-1, -1), colors.green),
                ]))
                parts.append(graph_table)
            return parts

        def build_pdf(charts):
            "Build a PDF"
            pdf = StringIO()
            doc = SimpleDocTemplate(pdf, topMargin=50, bottomMargin=18)
            logo = [(img, _('Baruwa mail report'))]
            logo_table = Table(logo, [2.0 * inch, 5.4 * inch])
            logo_table.setStyle(TableStyle([
            ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
            ('ALIGN', (0, 0), (-1, 0), 'LEFT'),
            ('ALIGN', (1, 0), (-1, 0), 'RIGHT'),
            ('FONTSIZE', (1, 0), (-1, 0), 10),
            ('LINEBELOW', (0, 0), (-1, -1), 0.15, colors.black),
            ]))
            parts = [logo_table]
            parts.append(Spacer(1, 20))
            parts.extend(charts)
            try:
                doc.build(parts)
            except IndexError:
                pass
            return pdf

        def gen_email(pdf, user, owner):
            "generate and return email"
            text_content = render_to_string('reports/pdf_report.txt',
                {'user': user, 'url': url})
            subject = _('Baruwa usage report for: %(user)s') % {
                        'user': owner}
            if email_re.match(user.username):
                toaddr = user.username
            if email_re.match(user.email):
                toaddr = user.email

            if admin_addrs:
                msg = EmailMessage(subject, text_content, from_email, [toaddr], admin_addrs)
            else:
                msg = EmailMessage(subject, text_content, from_email, [toaddr])
            msg.attach('baruwa.pdf', pdf.getvalue(), "application/pdf")
            print _("* Queue %(user)s's report to: %(addr)s") % {
                'user': owner, 'addr': toaddr}
            pdf.close()
            return msg

        print _("=================== Processing reports ======================")
        if by_domain:
            #do domain query
            #print "camacamlilone"
            domains = UserAddresses.objects.filter(Q(enabled=1), Q(address_type=1))
            if domain_name != 'all':
                domains = domains.filter(address=domain_name)
                if not domains:
                    print _("========== domain name %(dom)s does not exist ==========") % {
                    'dom': domain_name
                    }
            for domain in domains:
                if email_re.match(domain.user.email):
                    parts = build_parts(domain, enddate, True, daterange)
                    if parts:
                        pdf = build_pdf(parts)
                        email = gen_email(pdf, domain.user, domain.address)
                        emails.append(email)
        else:
            #do normal query
            profiles = UserProfile.objects.filter(send_report=1)
            for profile in profiles:
                try:
                    user = profile.user
                    if email_re.match(user.email) or email_re.match(user.username):
                        parts = build_parts(user, enddate, False, daterange)
                        if parts:
                            pdf = build_pdf(parts)
                            email = gen_email(pdf, user, user.username)
                            emails.append(email)
                except User.DoesNotExist:
                    pass

        if emails:
            try:
                conn = SMTPConnection()
                conn.send_messages(emails)
                print _("====== sending %(num)s messages =======") % {
                        'num': str(len(emails))}
            except Exception, exception:
                print _("Sending failed ERROR: %(error)s") % {'error': str(exception)}
Example #49
0
def createDoc(rows, rptType):
    flightroute = dbMgr(config.flightRoute)
    doc = SimpleDocTemplate(rptType + baseReport,
                            rightMargin=margin,
                            leftMargin=margin,
                            topMargin=margin,
                            bottomMargin=margin,
                            pagesize=landscape(letter))

    # container for the 'Flowable' objects
    elements = []

    elements.append(Paragraph(rptType + " Flights seen on:" + "  " + rptDate, styleHeading))
    # elements.append(PageBreak)

    # Set Column Headers
    even_rows = []
    poi = []
    chk = []
    colWidths = [.75 * inch] + [.8 * inch] + [1 * inch] + [2.2 * inch] + [1.45 * inch] + [.65 * inch] + [
        .65 * inch] + [.65 * inch] + [.65 * inch] + [.65 * inch] + [.65 * inch]
    rowHeights = [.16 * inch] * ((len(rows) * 2) + 2)
    index = 0
    data = [["Start Time", "Mode S", "Call Sign", "Country", "Manufacturer", "First Sqwk", "First Alt", "First GS",
             "First VR", "First Track", "#MsgRcvd"],
            ['End Time', 'Registration', 'Route', 'Owner', 'Type', 'Last Sqwk', "Last Alt", "Last GS", "Last VR",
             "Last Track"]]

    for row in rows:
        # Change "N" to "United States"
        if row[4] == 'N':
            country = 'United States'
        else:
            country = row[4]

        # Check for missing start_time
        try:
            start_time = str(row[53][11:])
        except TypeError:
            start_time = 'UNKNOWN'

        # Check for missing end_time
        try:
            end_time = str(row[54][11:])
        except TypeError:
            end_time = 'UNKNOWN'

        try:
            mode_s = str(row[3])
        except TypeError:
            mode_s = "UNKNOWN"

        try:
            registration = str(row[6]).strip()
        except TypeError:
            registration = '------'

        try:
            manufacturer = str(row[12]).strip()
        except TypeError:
            manufacturer = '------'

        try:
            mfr_type = str(row[14]).strip()
        except TypeError:
            mfr_type = '------'

        try:
            owner = str(row[21]).strip()
        except TypeError:
            owner = '-----'

        if str(row[81]).strip() == '':
            firstSquawk = '----'
        else:
            firstSquawk = str(row[81])

        if str(row[82]).strip() == '':
            lastSquawk = '----'
        else:
            lastSquawk = str(row[82])

        if str(row[75]).strip() == '':
            firstAlt = '------'
        else:
            firstAlt = str(row[75])

        if str(row[76]).strip() == '':
            lastAlt = '------'
        else:
            lastAlt = str(row[76])

        if str(row[55]).strip() == 'None':
            callsign = '------'
            route = '------'
        else:
            callsign = str(row[55]).strip()
            route = flightroute.query("select route from FlightRoute where FlightRoute.flight like '" + callsign + "'").fetchall()
            if len(route) > 0:
                route = str(route[0][0])
            else:
                route = '------'
        try:
            firstGS = str(int(float(row[73])))
        except TypeError:
            firstGS = '------'

        try:
            lastGS = str(int(float(row[74])))
        except TypeError:
            lastGS = '------'

        msg_rcvd = calcMsgCount(row)

        try:
            firstVR = str(int(float(row[77])))
        except TypeError:
            firstVR = "------"

        try:
            lastVR = str(int(float(row[78])))
        except TypeError:
            lastVR = "------"

        try:
            firstTrk = str(int(float(row[79])))
        except TypeError:
            firstTrk = '----'

        try:
            lastTrk = str(int(float(row[80])))
        except TypeError:
            lastTrk = '----'

        data.append(
            [start_time, mode_s, callsign, country, manufacturer, firstSquawk, firstAlt, firstGS, firstVR, firstTrk,
             msg_rcvd])
        data.append([end_time, registration, route, owner, mfr_type, lastSquawk, lastAlt, lastGS, lastVR, lastTrk])

        index += 1

        if index % 2 == 0:
            even_rows.append(index)

        if row[28] == 1:
            poi.append(index)

        if str(row[6]).strip() == 'None':
            chk.append(index)

    # Reminder: (column, row) starting at 0
    # (0,0) is upper left, (-1,-1) is lower right (row,0),(row,-1) is entire row

    # t = Table(data, colWidths=colWidths, rowHeights=rowHeights, repeatRows=2)
    t = Table(data, colWidths=colWidths, rowHeights=rowHeights, repeatRows=2, hAlign='LEFT')
    t.hAlign = 'LEFT'
    t.vAlign = 'CENTER'

    # Define default table attributes 
    tblStyle = TableStyle([])
    tblStyle.add('FONTSIZE', (0, 0), (-1, -1), page_font_size)
    tblStyle.add('TEXTFONT', (0, 0), (-1, -1), page_font)
    tblStyle.add('TEXTCOLOR', (0, 0), (-1, -1), colors.black)
    tblStyle.add('TOPPADDING', (0, 0), (-1, -1), 6)
    tblStyle.add('BOTTOMPADDING', (0, 0), (-1, -1), 0)
    tblStyle.add('BOX', (0, 0), (-1, 1), .25, colors.black)
    tblStyle.add('BOX', (0, 0), (-1, -1), 2, colors.black)
    tblStyle.add('INNERGRID', (0, 0), (-1, 1), 0.15, colors.gray)
    tblStyle.add('BACKGROUND', (0, 0), (-1, 1), colors.lightblue)
    tblStyle.add('BACKGROUND', (0, 2), (-1, -1), colors.white)

    for row in even_rows:
        row1 = (row) * 2
        row2 = row1 + 1
        tblStyle.add('BACKGROUND', (0, row1), (-1, row2), colors.lightgreen)

    if rptType == 'all':
        for row in poi:
            row1 = row * 2
            row2 = row1 + 1
            tblStyle.add('BACKGROUND', (0, row1), (-1, row1), colors.red)
            tblStyle.add('BACKGROUND', (0, row2), (-1, row2), colors.red)
            tblStyle.add('TEXTCOLOR', (0, row1), (-1, row1), colors.white)
            tblStyle.add('TEXTCOLOR', (0, row2), (-1, row2), colors.white)

        for row in chk:
            row1 = row * 2
            row2 = row1 + 1
            tblStyle.add('BACKGROUND', (0, row1), (-1, row1), colors.yellow)
            tblStyle.add('BACKGROUND', (0, row2), (-1, row2), colors.yellow)
            tblStyle.add('TEXTCOLOR', (0, row1), (-1, row1), colors.black)
            tblStyle.add('TEXTCOLOR', (0, row2), (-1, row2), colors.black)

    t.setStyle(tblStyle)
    elements.append(t)

    # write the document to disk
    doc.build(elements)
Example #50
0
def generate_roster_pdf(sched_act_ids, include_instructions):
    r"""Generates a PDF roster for one or more.

    :class:`EighthScheduledActivity`\s.

    Args
        sched_act_ids
            The list of IDs of the scheduled activities to show in the PDF.
        include_instructions
            Whether instructions should be printed at the bottom of the
            roster(s).

    Returns a BytesIO object for the PDF.

    """

    pdf_buffer = BytesIO()
    h_margin = 1 * inch
    v_margin = 0.5 * inch
    doc = SimpleDocTemplate(pdf_buffer,
                            pagesize=letter,
                            rightMargin=h_margin,
                            leftMargin=h_margin,
                            topMargin=v_margin,
                            bottomMargin=v_margin)

    elements = []

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name="Center", alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name="BlockLetter",
                       fontSize=60,
                       leading=72,
                       alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name="BlockLetterSmall",
                       fontSize=30,
                       leading=72,
                       alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name="BlockLetterSmallest",
                       fontSize=20,
                       leading=72,
                       alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name="ActivityAttribute",
                       fontSize=15,
                       leading=18,
                       alignment=TA_RIGHT))

    for i, said in enumerate(sched_act_ids):
        sact = EighthScheduledActivity.objects.get(id=said)

        sponsor_names = sact.get_true_sponsors().values_list(
            "first_name", "last_name")
        sponsors_str = "; ".join(l + ", " + f for f, l in sponsor_names)

        room_names = sact.get_true_rooms().values_list("name", flat=True)
        if len(room_names) == 1:
            rooms_str = "Room " + room_names[0]
        else:
            rooms_str = "Rooms: " + ", ".join(r for r in room_names)

        block_letter = sact.block.block_letter

        if len(block_letter) < 4:
            block_letter_width = 1 * inch
            block_letter_width += (0.5 * inch) * (len(block_letter) - 1)
            block_letter_style = "BlockLetter"
        elif len(block_letter) < 7:
            block_letter_width = 0.4 * inch
            block_letter_width += (0.3 * inch) * (len(block_letter) - 1)
            block_letter_style = "BlockLetterSmall"
        else:
            block_letter_width = 0.3 * inch
            block_letter_width += (0.2 * inch) * (len(block_letter) - 1)
            block_letter_style = "BlockLetterSmallest"

        header_data = [[
            Paragraph(
                "<b>Activity ID: {}<br />Scheduled ID: {}</b>".format(
                    sact.activity.id, sact.id), styles["Normal"]),
            Paragraph(
                "{}<br/>{}<br/>{}".format(
                    sponsors_str, rooms_str,
                    sact.block.date.strftime("%A, %B %-d, %Y")),
                styles["ActivityAttribute"]),
            Paragraph(block_letter, styles[block_letter_style])
        ]]
        header_style = TableStyle([("VALIGN", (0, 0), (0, 0), "TOP"),
                                   ("VALIGN", (1, 0), (2, 0), "MIDDLE"),
                                   ("TOPPADDING", (0, 0), (0, 0), 15),
                                   ("RIGHTPADDING", (1, 0), (1, 0), 0)])

        elements.append(
            Table(header_data,
                  style=header_style,
                  colWidths=[2 * inch, None, block_letter_width]))
        elements.append(Spacer(0, 10))
        elements.append(Paragraph(sact.full_title, styles["Title"]))

        num_members = sact.members.count()
        num_members_label = "{} Student{}".format(
            num_members, "s" if num_members != 1 else "")
        elements.append(Paragraph(num_members_label, styles["Center"]))
        elements.append(Spacer(0, 5))

        attendance_data = [[
            Paragraph("Present", styles["Heading5"]),
            Paragraph("Student Name (ID)", styles["Heading5"]),
            Paragraph("Grade", styles["Heading5"])
        ]]

        members = []
        for member in sact.members.all():
            members.append(
                (member.last_name + ", " + member.first_name,
                 (member.student_id if member.student_id else "User {}".format(
                     member.id)), int(member.grade) if member.grade else "?"))
        members = sorted(members)

        for member_name, member_id, member_grade in members:
            row = ["", "{} ({})".format(member_name, member_id), member_grade]
            attendance_data.append(row)

        # Line commands are like this:
        # op, start, stop, weight, colour, cap, dashes, join, linecount, linespacing
        attendance_style = TableStyle([
            ("LINEABOVE", (0, 1), (2, 1), 1, colors.black, None, None, None,
             2),
            ("LINEBELOW", (0, 1), (0, len(attendance_data)), 1, colors.black),
            ("TOPPADDING", (0, 1), (-1, -1), 6),
            ("BOTTOMPADDING", (0, 1), (-1, -1), 0),
            ("BOTTOMPADDING", (0, 0), (-1, 0), 5),
        ])

        elements.append(
            Table(attendance_data,
                  style=attendance_style,
                  colWidths=[1.3 * inch, None, 0.8 * inch]))
        elements.append(Spacer(0, 15))
        instructions = """
        <b>Highlight or circle</b> the names of students who are <b>absent</b>, and put an <b>"X"</b> next to those <b>present</b>.<br />
        If a student arrives and their name is not on the roster, please send them to the <b>8th Period Office</b>.<br />
        If a student leaves your activity early, please make a note. <b>Do not make any additions to the roster.</b><br />
        Before leaving for the day, return the roster and any passes to 8th Period coordinator, Catherine Forrester's mailbox in the
        <b>main office</b>. For questions, please call extension 5046 or 5078. Thank you!<br />"""

        elements.append(Paragraph(instructions, styles["Normal"]))

        if i != len(sched_act_ids) - 1:
            elements.append(PageBreak())

    def first_page(canvas, _):
        canvas.setTitle("Eighth Activity Roster")
        canvas.setAuthor("Generated by Ion")

    doc.build(elements, onFirstPage=first_page)
    return pdf_buffer
Example #51
0
def build_unigov_doc(title,
                     name,
                     institution_name,
                     voting_start,
                     voting_end,
                     extended_until,
                     results,
                     language,
                     filename="election_results.pdf",
                     new_page=True,
                     score=False,
                     parties=False):
    with translation.override(language[0]):
        pageinfo = _("Zeus Elections - Poll Results")
        title = _('Results')
        DATE_FMT = "%d/%m/%Y %H:%M"
        if isinstance(voting_start, datetime.datetime):
            voting_start = _('Start: %(date)s') % {
                'date': voting_start.strftime(DATE_FMT)
            }

        if isinstance(voting_end, datetime.datetime):
            voting_end = _('End: %(date)s') % {
                'date': voting_end.strftime(DATE_FMT)
            }

        if extended_until and isinstance(extended_until, datetime.datetime):
            extended_until = _('Extension: %(date)s') % {
                'date': extended_until.strftime(DATE_FMT)
            }
        else:
            extended_until = ""

        # reset pdfdoc timestamp in order to force a fresh one to be used in
        # pdf document metadata.
        pdfdoc._NOWT = None

        elements = []

        doc = SimpleDocTemplate(filename, pagesize=A4)

        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(name='Zeus',
                           fontName=DEFAULT_FONT,
                           fontSize=12,
                           leading=16,
                           alignment=TA_JUSTIFY))

        styles.add(
            ParagraphStyle(name='ZeusBold',
                           fontName=DEFAULT_FONT,
                           fontSize=12,
                           leading=16,
                           alignment=TA_JUSTIFY))

        styles.add(
            ParagraphStyle(name='ZeusSubHeading',
                           fontName=DEFAULT_FONT,
                           fontSize=14,
                           alignment=TA_JUSTIFY,
                           spaceAfter=16))

        styles.add(
            ParagraphStyle(name='ZeusHeading',
                           fontName=DEFAULT_FONT,
                           fontSize=16,
                           alignment=TA_CENTER,
                           spaceAfter=16))
        intro_contents = [voting_start, voting_end, extended_until]

        make_heading(elements, styles, [title, name, institution_name])
        make_intro(elements, styles, intro_contents)

        group_a = results['group_a']
        group_b = results['group_b']
        totals = results['totals']

        elements.append(Spacer(1, 12))
        elements.append(Spacer(1, 12))
        elements.append(Spacer(1, 12))

        groups_table = []
        for g in [group_a, group_b]:
            group_elements = []
            make_subheading(group_elements, styles, [g['name']])
            _total_voters = g['voters']
            _excluded_voters = g['excluded']
            group_elements.append(
                Paragraph(escape(_("Voters") + ": " + str(_total_voters)),
                          styles['Zeus']))
            group_elements.append(
                Paragraph(escape(_('Total votes: %d') % g['voted']),
                          styles['Zeus']))
            group_elements.append(
                Paragraph(escape(_('Blank: %d') % g['blank']), styles['Zeus']))
            if _excluded_voters > 0:
                group_elements.append(
                    Paragraph(
                        escape(
                            _("Excluded voters") + ": " +
                            str(_excluded_voters)), styles['Zeus']))
            group_elements.append(Spacer(1, 12))
            group_elements.append(Spacer(1, 12))
            group_elements.append(Spacer(1, 12))
            group_elements.append(Spacer(1, 12))
            group_elements.append(Spacer(1, 12))
            groups_table.append(group_elements)

        t = Table(list(zip(*groups_table)))
        table_style = TableStyle([('FONT', (0, 0), (-1, -1), DEFAULT_FONT)])
        t.setStyle(table_style)
        elements.append(t)

        questions = OrderedDict()
        for q in list(results['totals']['counts'].keys()):
            total_counts = totals['counts'][q]
            total_counts_rounded = totals['counts_rounded'][q]
            group_a_counts = group_a['counts'][q]
            group_b_counts = group_b['counts'][q]
            questions[q] = {}
            for candidate in list(totals['counts'][q].keys()):
                questions[q][candidate] = {
                    'total': total_counts[candidate],
                    'total_rounded': int(total_counts_rounded[candidate]),
                    'group_a': group_a_counts[candidate],
                    'group_b': group_b_counts[candidate],
                }

        elements.append(PageBreak())
        for question, candidates in questions.items():
            make_heading(elements, styles, [question])
            elements.append(Spacer(1, 12))
            elements.append(Spacer(1, 12))
            elements.append(Spacer(1, 12))

            group_a_name = group_a['name'].split(
                " ", 1)[1] if " " in group_a['name'] else group_a['name']
            group_b_name = group_b['name'].split(
                " ", 1)[1] if " " in group_b['name'] else group_b['name']

            candidates_table = [[
                Paragraph(escape(_("Candidate")), styles['ZeusBold']),
                Paragraph(escape(_("Total")), styles['ZeusBold']),
                Paragraph(escape(group_a_name), styles['ZeusBold']),
                Paragraph(escape(group_b_name), styles['ZeusBold'])
            ]]
            table_data = []
            for candidate, counts in candidates.items():
                table_data.append([
                    Paragraph(escape(candidate), styles['Zeus']),
                    counts['total_rounded'],
                    counts['group_a'],
                    counts['group_b'],
                ])
            candidates_table += sorted(table_data, key=lambda x: -x[1])

            from reportlab.lib.units import inch

            t = Table(candidates_table,
                      colWidths=[4 * inch] + [1.2 * inch] * 3)
            table_style = TableStyle([
                ('FONT', (0, 0), (-1, -1), DEFAULT_FONT),
                ('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
            ])
            table_style = TableStyle([
                ('FONT', (0, 0), (-1, -1), DEFAULT_FONT),
                ('ALIGN', (1, 1), (-2, -2), 'LEFT'),
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ])
            t.setStyle(table_style)
            elements.append(t)
            elements.append(PageBreak())

        doc.build(elements,
                  onFirstPage=make_first_page_hf,
                  onLaterPages=make_later_pages_hf(pageinfo))
Example #52
0
def csv_to_db(csv_path):
    conn = psycopg2.connect("host=localhost dbname=postgres user=postgres")
    cur = conn.cursor()
    cur.execute("""DELETE FROM users;""")
    cur.execute("""
    CREATE TABLE IF NOT EXISTS  users(
        name text,
        surname text,
        company text,
        title text,
        dateofbirth text,
        photo text
    )
    """)

    with open(csv_path, 'r') as csv_file:
        cur.copy_from(csv_file, 'users', sep=',')
        cur.execute("""
            SELECT * FROM users ORDER BY company ASC, title ASC;
            """)

    rows = cur.fetchall()

    doc = SimpleDocTemplate("list_of_people.pdf", pagesize=A4, rightMargin=30, leftMargin=20, topMargin=30,
                            bottomMargin=18)
    pdf_elements = []
    s = getSampleStyleSheet()
    s = s["BodyText"]

    data_rows = [('NAME', 'SURNAME', 'COMPANY', 'TITLE', 'DOB', 'PHOTO'), ]
    for row in rows:
        img = urllib.urlretrieve(row[5], "pic of {} {}.jpg".format(row[0], row[1]))
        watermark = str(row[0])
        edit_image("pic of {} {}.jpg".format(row[0], row[1]), watermark)
        I = Image("pic of {} {}.jpg".format(row[0], row[1]))
        data_rows.append((row[0], row[1], Paragraph(row[2], s), Paragraph(row[3], s), row[4], I),)

    main_table_from_db = LongTable(data_rows, 5 * [1 * inch], len(data_rows) * [1 * inch], repeatRows=1,
                                   splitByRow=1)
    main_table_from_db.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    ]))

    cur.execute("""SELECT company, COUNT(company) FROM users GROUP BY company""")
    table_of_people = cur.fetchall()
    people_in_company = []
    for row in table_of_people:
        people_in_company.append((Paragraph(row[0], s), row[1]),)

    people_in_company = [('COMPANY', Paragraph('NUMBER OF EMPLOYEES', s)), ] + people_in_company

    table_for_employees_amount = Table(people_in_company, 5 * [1 * inch], len(people_in_company) * [0.4 * inch])
    table_for_employees_amount.setStyle(TableStyle([
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    ]))

    pdf_elements.append(main_table_from_db)
    pdf_elements.append(Spacer(1, 30))
    pdf_elements.append(table_for_employees_amount)
    doc.build(pdf_elements)

    conn.commit()
Example #53
0
 def __init__(self, name, cmds=None, parent=None, **kw):
     self.name = name
     TableStyle.__init__(self, cmds, parent, **kw)
Example #54
0
def equivs_and_emission_equivs(equivs_data, emissions_data, Elements):
    '''
    Creates a table with 2 columns, each with their own embedded table
    The embedded tables contain 2 vertically-stacked tables, one for the header
    and the other one for the actual data in order to have better alignment

    The first row of the 2nd vertically-stacked table is smaller than the rest in
    order to remove the extra space and make these tables look cohesive with the
    energy usage readings and energy mix tables

    Setup:
    * Table(data[array of arrays, one for each row], [column widths], [row heights])
    * Spacer(width, height)


    '''
    s = Spacer(9*inch, .2*inch)
    Elements.append(s)

    no_rows = 1
    no_cols = 1
    col_size = 4.5

    equivs_header_data = [["Assumed Carbon Equivalencies"]]

    # Table(data)
    equivs_header_table = Table(equivs_header_data, [3*inch], [.25*inch])
    equivs_header_table.setStyle(TableStyle([('FONT',(0,0),(0,-1),"Times-Bold"),
                                             ('FONTSIZE', (0,0), (-1,-1), 13)]))


    equivs_data_table = Table(equivs_data, [1*inch, 2*inch], [0.17*inch, 0.25*inch, 0.25*inch, 0.25*inch],hAlign="LEFT")
    equivs_data_table.setStyle(TableStyle([('FONT', (0,0), (-1,-1), "Times-Roman"),
                                         ('FONTSIZE', (0,0), (-1,-1), 12),
                                         ('ALIGN', (0,0), (0,-1), "RIGHT"),
                                         ('VALIGN', (-1,-1), (-1,-1), "TOP")]))

    t1_data = [[equivs_header_table],[equivs_data_table]]

    t1 = Table(t1_data, [3*inch])

    emission_equiv_para = Paragraph('<font face="times" size=13><strong>CO<sub rise = -10 size = 8>2</sub>' +
    '  Emissions Equivalents</strong></font>', style = styles["Normal"])
    emissions_header_data = [[emission_equiv_para]]
    emissions_header_table = Table(emissions_header_data, [3*inch], [.25*inch])
    emissions_header_table.setStyle(TableStyle([('FONT',(0,0),(0,-1),"Times-Bold"),
                                             ('FONTSIZE', (0,0), (-1,-1), 13)]))


    emissions_data_table = Table(emissions_data, [2.1*inch, 1.5*inch], [0.17*inch, 0.25*inch, 0.25*inch],hAlign="LEFT")
    emissions_data_table.setStyle(TableStyle([('FONT', (0,0), (-1,-1), "Times-Roman"),
                                         ('FONTSIZE', (0,0), (-1,-1), 12),
                                         ('ALIGN', (0,0), (0,-1), "RIGHT"),
                                         ('VALIGN', (-1,-1), (-1,-1), "TOP")]))

    t2_data = [[emissions_header_table],[emissions_data_table]]

    t2 = Table(t2_data, [3*inch])


    table_data = [(t1, t2)]
    t = Table(table_data, [4.25*inch, 3*inch], hAlign='CENTER')
    t.setStyle(TableStyle([('VALIGN', (-1,-1), (-1,-1), "TOP")]))
    Elements.append(t)
Example #55
0
    def drawTable(self, group=None, monocell=None, reiter = None):
        """ Drawing a table """
        matrix = []
        lst = []
        matrix2 = []
        vector = []
        # Total of element's table
        cells = int(self.tablesPropertie['cells'])
        columns = int(self.tablesPropertie['columns'])
        rows = int(self.tablesPropertie['rows'])
        widths = self.tablesPropertie['widths']
        heights = self.tablesPropertie['heights']
        xpos = self.tablesPropertie['xpos']
        ypos = self.tablesPropertie['ypos']
#        print "DATI", cells, columns, rows, group, heights, widths
        contColumns = 0
        ch = ''
        col = 0
        cycle = False
        vector = []
        alignment= None
        itexts = self.tablesPropertie['itextsobj']
        paras = self.tablesPropertie['parasobj']
        stile = TableStyle([])
        stile.add('VALIGN',(0,0),(-1,-1),'TOP')
        tblprop = self.tablesPropertie['cellProperties']
        if monocell==True:
            cells = 1
            columns=1
            rows = 1
        for v in xrange(0,cells):
            if v == 0:
                contRows = 0
                contColumns = 0
            elif columns==1:
                contColumns = -1
                contRows= int(v/columns)
            else:
                contRows= int(v/columns)
                contColumns = ((v)%columns)
            background = self.backgroundFunc(tblprop[v])# Finding background
            hexBorderColor = self.hexBorderColorFunc(tblprop[v]['borderColor'])
            stile.add('ROWBACKGROUNDS', (contColumns,contRows),
                                (contColumns,contRows),
                                (background, background))
            cellpr = tblprop[v]
            cellpict = cellpr['cellPicture']
            cellIMGHeight = cellpr['cellHeight']
            cellIMGWidth = cellpr['cellWidth']
            if (cellpr['bottomLine'] == 1 and cellpr['topLine'] == 1 and\
                        cellpr['leftLine'] == 1 and cellpr['rightLine'] == 1):
                stile.add('BOX', (contColumns,contRows),
                                (contColumns,contRows),
                                cellpr['lineWidth'],
                                hexBorderColor)
            else:
                if cellpr['bottomLine'] == 1:
                    stile.add('LINEBELOW', (contColumns,contRows),
                                (contColumns,contRows),
                                cellpr['lineWidth'],
                                hexBorderColor)
                elif cellpr['topLine'] == 1:
                    stile.add('LINEABOVE', (contColumns,contRows),
                                (contColumns,contRows),
                                cellpr['lineWidth'],
                                hexBorderColor)
                if cellpr['leftLine'] == 1:
                    stile.add('LINEBEFORE', (contColumns,contRows),
                                (contColumns,contRows),
                                cellpr['lineWidth'],
                                hexBorderColor)
                if cellpr['rightLine'] == 1:
                    stile.add('LINEAFTER', (contColumns,contRows),
                                (contColumns,contRows),
                                cellpr['lineWidth'],
                                hexBorderColor)

            if not monocell:
                ch = self.chFunc(itexts[v])[0]
                itext = self.chFunc(itexts[v])[1]
            else:
                try:
                    itext = itexts[0]
                    ch = itexts[0].get('CH')
                except:
                    itext = None
                    ch = ""
            # self.chFunc(itexts[0])[1]
            actualPageObject = self.tablesPropertie# Borders
            uff = self.tablesPropertie['iterproper']
            if uff != [] and v > columns:
                pdfAlignment = self.alignmentFunc(self.tablesPropertie['iterproper'][contColumns],v, reiter=True)
            else:
                pdfAlignment = self.alignmentFunc(paras, v, monocell) #alignment
            stile.add('ALIGN', (contColumns,contRows),
                                (contColumns,contRows),
                                pdfAlignment)
            if itext != None:
                fontName = self.fontNameFunc(itext) #  Font name
                stile.add('FONT', (contColumns,contRows),
                                    (contColumns,contRows),
                                    fontName)

                fontSize = self.fontSizeFunc(itext)# Font size
                stile.add('FONTSIZE', (contColumns,contRows),
                                    (contColumns,contRows),
                                    fontSize)

                foreground = self.foregroundFunc(itext) #foreground
                stile.add('TEXTCOLOR', (contColumns,contRows),
                                    (contColumns,contRows),
                                    foreground)
                if "bcview" in ch:
                    alignment="LEFT"
                    vector.append(Sla2pdfUtils.createbarcode(ch))
                else:
                    vector.append(Sla2pdfUtils.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize))
            elif cellpict:
                (imgPath, imgFile) = os.path.split(cellpict)
                path = Environment.imagesDir + imgFile
                widthIMG = (float(cellIMGHeight)-2)*100/(float(cellIMGWidth)-2)
                img = Image(path,width=widthIMG,height=float(cellIMGHeight)-2)
                vector.append(img)
            else:
                vector.append('')
            if monocell==True:
                cycle= True
            elif ((v+1)%columns) == 0:
                contRows = 0
                cycle= True
            if cycle == True:
                matrix.append(vector)
                vector = []
                cycle = False
#        if columns > 1 and not reiter:
#            #wid = []
#            hei = []
#            for h in range(0,len(heights),rows):
#                hei.append(heights[h])
#            heights = hei
        table=Table(matrix,style=stile,  colWidths=widths[:columns], rowHeights=heights[:rows])

        lst.append(table)
        # Effective table size
        sumRows = Sla2pdfUtils.sumRowsFunc(heights,rows)
        sumColumns = Sla2pdfUtils.sumColumnsFunc(widths,columns)
        f = Frame(x1=(xpos[0] - self.pageProperties[self.pdfPage][9]),
                    y1=(self.pageProperties[self.pdfPage][7] - ypos[0] - sumRows + self.pageProperties[self.pdfPage][10] - 12),
                    width=sumColumns,
                    height=(sumRows+12),
                    showBoundary=0)
        sumRows = sumColumns = 0
        f.addFromList(lst, self.canvas)
        reiter = False
Example #56
0
from reportlab.platypus import Table
from reportlab.lib import colors
from reportlab.pdfgen import canvas
from reportlab.platypus import TableStyle

style = TableStyle([
    ('BACKGROUND', (0, 0), (3, 0), colors.blue),
    ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
    ('FONTNAME', (0, 0), (-1, 0), 'Courier-Bold'),
    ('FONTSIZE', (0, 0), (-1, 0), 14),
    ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
    ('BACKGROUND', (0, 1), (-1, -1), colors.white),
])

ts = TableStyle([
    ('BOX', (0, 0), (-1, -1), 2, colors.black),
    ('LINEBEFORE', (2, 1), (2, -1), 2, colors.red),
    ('LINEABOVE', (0, 2), (-1, 2), 2, colors.green),
    ('GRID', (0, 0), (-1, -1), 2, colors.black),
])


def drawMyRuler(pdf):
    pdf.drawString(100, 810, 'x100')
    pdf.drawString(200, 810, 'x200')
    pdf.drawString(300, 810, 'x300')
    pdf.drawString(400, 810, 'x400')
    pdf.drawString(500, 810, 'x500')

    pdf.drawString(10, 100, 'y100')
Example #57
0
def create_print_table(table_data):
    """Formats report data into table"""

    num_columns = len(RECEIVEDDATA.keys())
    if num_columns != 1 and num_columns != 2:
        arcpy.AddError("Only one or two columns are supported")
        return None

    data_list = []
    table_keys = []
    for key in RECEIVEDDATA.keys():
        TEMPDICT = {key : ATTRIBUTEDATA.find(key)}
        TABLEKEYSINDEX.update(TEMPDICT)
    SORTEDTABLESINDEX = sorted((value, key) for (key, value)
                                   in TABLEKEYSINDEX.items())
    for index in SORTEDTABLESINDEX:
        table_keys.append(index[1])

    header_list = []
    rows_count = []

    header_style = ParagraphStyle("headerStyle", alignment=TA_CENTER,
                              spaceAfter=4, borderPadding=(10, 10, 10),
                              leftIndent=10, fontName='VeraBd', fontSize=7.5,
                              wordWrap='CJK')

    key_style = ParagraphStyle(name='keyStyle', alignment=TA_LEFT,
                                        spaceAfter=4, fontName='Vera',
                                        fontSize=7.5,
                                        wordWrap='CJK')

    val_style = ParagraphStyle(name='valStyle', alignment=TA_RIGHT,
                                        spaceAfter=4, fontName='Vera',
                                        fontSize=7.5,
                                        wordWrap='CJK')

    for header in table_keys:
        header_list += [Paragraph(header, header_style), "", ""]
        rows_count.append(len(table_data[header]))
    header_list.pop()
    data_list.append(header_list)

    rows_number = max(rows_count)

    column_header_color = Color(0.8666666666666667, 0.8745098039215686,
                                0.8745098039215686, 1)
    if num_columns == 1:
        table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                ('ALIGN', (0, 0), (1, 0), 'CENTER'),
                                ('ALIGN', (0, 0), (-1, 0), 'LEFT'),
                                ('BACKGROUND', (0, 0), (1, 0),
                                 column_header_color),
                                ('SPAN', (0, 0), (1, 0)),
                                ])
    else:
        table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                ('ALIGN', (0, 0), (1, 0), 'CENTER'),
                                ('ALIGN', (0, 0), (-1, 0), 'LEFT'),
                                ('BACKGROUND', (0, 0), (1, 0),
                                 column_header_color),
                                ('BACKGROUND', (3, 0), (4, 0),
                                 column_header_color),
                                ('SPAN', (0, 0), (1, 0)),
                                ('SPAN', (3, 0), (4, 0)),
                                ])

    row_color = Color(0.9529411764705882, 0.9529411764705882,
                      0.9529411764705882, 1)

    for i in xrange(rows_number):
        if i % 2 != 0:
            table_style.add('BACKGROUND', (0, (i+1)), (1, (i+1)),
                            row_color)
            if num_columns == 2:
                table_style.add('BACKGROUND', (3, (i+1)), (4, (i+1)),
                            row_color)
        values_list = []
        for header in table_keys:
            try:
                row_value = table_data[header][i]
                key =  Paragraph(row_value.split(":")[0], key_style)
                val = Paragraph(row_value.split(":")[1], val_style)

                values_list += [key, val,""]
            except IndexError:
                values_list += ["", "",""]

        values_list.pop()
        data_list.append(values_list)

    if num_columns == 1:
        data_table = Table(data_list, colWidths=(145, 100), style=table_style)
    else:
        data_table = Table(data_list, colWidths=(145, 100, 10, 145, 100), style=table_style)
    return data_table
Example #58
0
    def Imprimer(self):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.styles import ParagraphStyle

        hauteur_page = A4[1]
        largeur_page = A4[0]

        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("depot_prestations", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc,
                                pagesize=(largeur_page, hauteur_page),
                                topMargin=30,
                                bottomMargin=30,
                                leftMargin=40,
                                rightMargin=40)
        story = []

        # Création du titre du document
        dataTableau = []
        largeursColonnes = ((largeur_page - 175, 100))
        dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
        dataTableau.append((_(u"Détail des prestations d'un dépôt"),
                            _(u"%s\nEdité le %s") %
                            (UTILS_Organisateur.GetNom(), dateDuJour)))
        style = TableStyle([
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (0, 0), 'LEFT'),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
            ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
            ('FONT', (1, 0), (1, 0), "Helvetica", 6),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 10))

        # Intro
        styleA = ParagraphStyle(name="A",
                                fontName="Helvetica",
                                fontSize=6,
                                spaceAfter=20)
        story.append(Paragraph(self.GetLabelParametres(), styleA))

        # Tableau
        dataTableau = []
        largeursColonnes = []
        for x in range(0, len(self.dictImpression["entete"]) - 1):
            largeursColonnes.append(45 * 2)
        largeursColonnes.insert(0, largeur_page - 75 - sum(largeursColonnes))

        # Entetes labels
        dataTableau.append(self.dictImpression["entete"])

        # Contenu du tableau
        listeRubriques = ("contenu", "total")
        for rubrique in listeRubriques:
            listeLignes = self.dictImpression[rubrique]

            for ligne in listeLignes:
                dataTableau.append(ligne)

        positionLigneTotal = len(self.dictImpression["contenu"]) + 1
        listeStyles = [
            ('VALIGN', (0, 0), (-1, -1),
             'MIDDLE'),  # Centre verticalement toutes les cases
            ('FONT', (0, 0), (-1, -1), "Helvetica",
             7),  # Donne la police de caract. + taille de police 
            ('GRID', (0, 0), (-1, -1), 0.25,
             colors.black),  # Crée la bordure noire pour tout le tableau
            ('ALIGN', (0, 0), (-1, -1), 'CENTRE'),  # Centre les cases
            ('BACKGROUND', (0, 0), (-1, 0),
             (0.6, 0.6, 0.6)),  # Donne la couleur de fond du label
            ('BACKGROUND', (0, positionLigneTotal), (-1, positionLigneTotal),
             (0.6, 0.6, 0.6)),  # Donne la couleur de fond du label
        ]

        # Formatage des lignes "Activités"
        for indexColoration in self.dictImpression["coloration"]:
            listeStyles.append(
                ('FONT', (0, indexColoration + 1), (-1, indexColoration + 1),
                 "Helvetica-Bold", 7))
            listeStyles.append(('BACKGROUND', (0, indexColoration + 1),
                                (-1, indexColoration + 1), (0.8, 0.8, 0.8)))

        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)
        story.append(Spacer(0, 20))

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
                       )
             )

# A Spacer flowable is fairly obvious. It is used to ensure that an empty space
# of a given size is left in the frame. This spacer leaves a 25mm gap before
# this next paragraph.
story.append(Spacer(1, 15*mm))

# Prepare the table data as a list of lists, including a header row.
datafile = csv.reader(open("02_02_kiwipycon_wifi_details.csv"))
table_data = list(datafile)

# Prepare the TableStyle.
myTableStyle = TableStyle([('LINEABOVE', (0,0), (-1,0), 2, colors.green),
                           ('LINEBELOW', (0,0), (-1,0), 2, colors.green),
                           ('LINEBELOW', (0,1), (-1,-1), 0.25, colors.black),
                           ('LINEBELOW', (0,-1), (-1,-1), 2, colors.green),
                           ('ALIGN', (1,1), (-1,-1), 'RIGHT')]
                          )

# add some conditional formatting to the table style
for i, data in enumerate(table_data):
    if not i:
        continue  # skip header row
    for col in range(1,3):
        mb = int(data[col]) # megabytes uploaded or downloaded
        # color each cell from white at 0MB to a maximum of full red at 1000MB
        myTableStyle.add('BACKGROUND', (col, i), (col, i),
                         lerp(colors.white, colors.red, 0, 1000, min(mb, 1000)))

# The table flowables. A couple of points to note:
#  - repeatRows=1 means that 1 row (the header) will repeat at the top of each
Example #60
0
    
    
    # use the follow statement to break the loop when conduct test
    # break

stockdb.commit()  


cur.execute("SELECT * FROM test_%s ORDER BY meanIn3wHistorical DESC LIMIT 100" % td_str)
top100=cur.fetchall()
    
doc = SimpleDocTemplate("D:\\zero\\analysis_report\\test_report_%s.pdf" %td_str, pagesize=letter)
    
heads=[('stcode', 'meanInLastYear', 'stdInLastYear', 'meanIn3wHistorical', 'stdIn3wHistorical', 'meanIn3wActual', 'stdIn3wActual')]
top100=heads+top100

elements=[]

t=Table(top100, repeatRows=1)
t.setStyle(TableStyle([('GRID', (0,0), (-1,-1), 1, colors.black), ('BACKGROUND', (0,0), (6,0), colors.lightblue), ('TEXTCOLOR', (6,1), (-1,-1), colors.red), ('TEXTCOLOR', (4,1), (-3,-1), colors.red), ('TEXTCOLOR', (2,1), (-5,-1), colors.red)]))
elements.append(t)

doc.build(elements)
 

# close the cursor
cur.close()

# close the database connection
stockdb.close()