def build_index_US(self, records, sito):
		styleSheet = getSampleStyleSheet()
		styNormal = styleSheet['Normal']
		styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink)
		styH1 = styleSheet['Heading3']
		data = self.datestrfdate()
		lst = []
		lst.append(Paragraph("<b>ELENCO UNITA' STRATIGRAFICHE</b><br/><b>Scavo: %s <br/>Data: %s <br/>Ditta esecutrice: adArte snc, Rimini</b>" % (sito, data), styH1))

		table_data = []
		for i in range(len(records)):
			exp_index = US_index_pdf_sheet(records[i])
			table_data.append(exp_index.getTable())
		
		styles = exp_index.makeStyles()
		table_data_formatted = Table(table_data,  colWidths=55.5)
		table_data_formatted.setStyle(styles)

		lst.append(table_data_formatted)
		lst.append(Spacer(0,12))

		filename = ('%s%s%s') % (self.PDF_path, os.sep, 'indice_us.pdf')
		f = open(filename, "wb")

		doc = SimpleDocTemplate(f, pagesize=(29*cm, 21*cm), showBoundary=0)
		doc.build(lst, canvasmaker=NumberedCanvas_USindex)

		f.close()
示例#2
0
文件: Relatorio.py 项目: ROAND/Otica
	def gerarSomatorio(self, mostrarDetalhes=False):
		if( mostrarDetalhes == True ): 
			linTotal = 2 #< ultima linha
		else: 
			linTotal = 0 #< unica
		est = [
		('BOX', (0, 0), (-1, -1), 2, cor_kde_quase_preto),
		('LINEABOVE', (0, linTotal), (-1, linTotal), 1, cor_kde_quase_preto),
		('BACKGROUND', (0, linTotal), (-1, linTotal), cor_kde_cinza_escuro),
		('ALIGN', (0, linTotal), (0, linTotal), 'CENTER'),
		('FONTNAME', (0, linTotal), (-1, linTotal), 'Times-Bold'),
		]
		# 'totalNegat' é < 0, por isso o '+' abaixo:
		tabSomat = []
		total = self.totalPosit + self.totalNegat
                tabSomat.append(['Total: ', 'R$ '+str(total) ])
		if( mostrarDetalhes == True ):
			tabSomat.insert(0, ['Saídas: ', 'R$ '+str(self.totalNegat)] )
			tabSomat.insert(1, ['Entradas: ', 'R$ '+str(self.totalPosit)] )
			est.append(estiloNegativo(lin=0))
			est.append(estiloNegrito(lin=2))
		else:
			est.append(estiloNegrito(lin=0))
		try:
			tabSomat = Table(tabSomat)
		except:
			print "tabSomat:"
			print tabSomat
		tabSomat.setStyle(est)
		return tabSomat
示例#3
0
def build_tabla_totales(dic_totales):
    """
    Construye una tabla con los totales del presupuesto.
    La tabla tiene dos columnas. En la primera están las claves del 
    diccionario «dic_totales». En la segunda los valores correspondientes.
    La última fila de la tabla estará en negrita.
    Si el diccionario de totales trae una clave "orden" (que debería) se 
    seguirá ese orden para mostrarlos en las filas.
    """
    try:
        claves = dic_totales["orden"]
    except KeyError:
        claves = dic_totales.keys()
    datos = []
    for clave in claves:
        datos += [["", clave, dic_totales[clave]]]
    datos[-1][1] = Paragraph("<b>%s</b>" % datos[-1][1], 
                             estilos["BodyText"])
    a_derecha = ParagraphStyle("A derecha", 
                                parent = estilos["BodyText"])
    a_derecha.alignment = enums.TA_RIGHT
    datos[-1][-1] = Paragraph("<b>%s</b>" % datos[-1][-1], 
                              a_derecha)
    tabla = Table(datos, 
                  colWidths = (PAGE_WIDTH * 0.55,   # HACK: Para que ocupe lo  
                               PAGE_WIDTH * 0.15,   # mismo que la otra. 
                               PAGE_WIDTH * 0.2))   # Si no, RL la centra.
    tabla.setStyle(TableStyle([
        ("BOX", (1, 0), (-1, -1), 1.0, colors.black),
        ("INNERGRID", (1, 0), (-1, -1), 0.25, colors.black), 
        ("ALIGN", (1, 0), (-2, -1), "LEFT"), 
        ("ALIGN", (-1, 0), (-1, -1), "RIGHT"), 
        ]))
    return tabla
示例#4
0
def make_pdf(data, title):
    tid = str(time()).replace('.', '')
    pdf_file = "reports/" + tid + ".pdf"

    # convert tuple to list
    data = [list(elem) for elem in data]

    doc = SimpleDocTemplate(pdf_file, pagesize=letter)

    styles=getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))

    parts = []
    table_with_style = Table(data)

    table_with_style.setStyle(TableStyle([
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
    ]))

    parts.append(Paragraph(title, styles["Center"]))
    parts.append(Spacer(1, 12))

    parts.append(table_with_style)
    doc.build(parts)

    show_pdf(pdf_file)
示例#5
0
文件: pdf.py 项目: Ameriks/velo.lv
    def _build_top(self):
        width = self.doc.width
        invoice_date = self.invoice.get('invoice_date')

        if self.payment and self.payment.status != 30:
            title = "Avansa rēķins"
        else:
            title = "Rēķins"

        im = None
        if self.invoice.get('organiser_data').get('logo'):
            adv = os.path.join(settings.MEDIA_ROOT, "adverts", self.invoice.get('organiser_data').get('logo'))
            im = Image(adv, 100, 35)
        # self.elements.append(im)

        data = [[im if im else '', Paragraph(title, self.styles.get('h1')), 'Nr.', self.invoice.get('name')],
                ['', invoice_date, '', '']]

        header_table = Table(data, colWidths=list((width / 4.0, width / 2.0, width / 16.0, (width * 3) / 16.0,), ))
        header_table.setStyle(
            TableStyle([
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('ALIGN', (3, 0), (3, 0), 'LEFT'),
                ('ALIGN', (2, 0), (2, 0), 'RIGHT'),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('BOX', (3, 0), (3, 0), 0.25, colors.darkgray),
                ('FONT', (0, 0), (-1, -1), 'Ubuntu'),
                ('SPAN', (0, 0), (0, 1)),
            ]))
        self.elements.append(header_table)
示例#6
0
文件: views.py 项目: luis0794/SIGIF
def generar_pdf_Producto(request):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "productos.pdf" 
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    productos = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Productos", styles['Heading1'])
    productos.append(header)
    headings = ('Proveedor','Nombre', 'Descripcion', 'Marca', 'Precio','Stock Actual')
    allproductos = [(p.prov_id, p.pro_nom, p.pro_des, p.pro_mar, p.pro_pre, p.pro_sto_act) for p in Producto.objects.all()]

    t = Table([headings] + allproductos)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (6, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    
    productos.append(t)
    doc.build(productos)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#7
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)
示例#8
0
文件: views.py 项目: luis16k/ticserp
def generar_pdf(request):
    print ("Genero el PDF");
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "proveedores.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    proveedores = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Proveedores", styles['Heading1'])
    proveedores.append(header)
    headings = ('No. Proveedor','Nombre','RFC','Giro','Direccion','Ciudad','Estado','Pais','Telefono','Correo','Comentario')
    allproveedores = [(p.num_proveedor, p.nombre, p.RFC ,p.giro ,p.direccion ,p.ciudad ,p.estado ,p.pais ,p.telefono ,p.correo ,p.comentario) for p in Proveedor.objects.all()]
    print (allproveedores);

    t = Table([headings] + allproveedores)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (12, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    proveedores.append(t)
    doc.build(proveedores)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#9
0
def outputtopdf(outputfile,title,labels,db,resdb):
    import logging
    log = logging.getLogger('outputtopdf')
    try:
            from reportlab.platypus import TableStyle, Table, SimpleDocTemplate, Paragraph
            from reportlab.lib import colors
            from reportlab.lib.styles import getSampleStyleSheet
            from reportlab.pdfgen import canvas
    except ImportError:
            log.error('Reportlab was not found. To export to pdf you need to have reportlab installed. Check out www.reportlab.org')
            return
    log.debug('ok reportlab library found')
    styles = getSampleStyleSheet()
    rows=list()
    rows.append(labels)
    for k in db.keys():
        cols = [k,db[k]]
        if resdb is not None:
            if resdb.has_key(k):
                cols.append(resdb[k])
            else:
                cols.append('N/A')
        rows.append(cols)    
    t=Table(rows)
    mytable = TableStyle([('BACKGROUND',(0,0),(-1,0),colors.black),
                            ('TEXTCOLOR',(0,0),(-1,0),colors.white)])
    t.setStyle(mytable)
    doc = SimpleDocTemplate(outputfile)
    elements = []
    style = styles["Heading1"]
    Title = Paragraph(title,style)
    elements.append(Title)
    elements.append(t)
    doc.build(elements)
示例#10
0
文件: views.py 项目: luis0794/SIGIF
def generar_pdf_Usuario(request):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "usuarios.pdf"
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    usuarios = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Usuarios", styles['Heading1'])
    usuarios.append(header)
    headings = ('Cedula', 'Nombres', 'Apellidos', 'Sexo','Direccion', 'Telefono', 'Email')
    allusuarios = [(p.usu_ced, p.usu_nom, p.usu_ape, p.usu_sex, p.usu_dir, p.usu_tel, p.usu_ema) for p in Usuario.object.all()]

    t = Table([headings] + allusuarios)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (6, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))

    usuarios.append(t)
    doc.build(usuarios)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#11
0
    def genBandStatsTable(self):
        data = [[Paragraph('<b>Band</b>', self.styleSheet)
               , Paragraph('<b>#Proposals</b>', self.styleSheet)
               , Paragraph('<b>Req Hrs</b>', self.styleSheet)
               ]]
        bandStats = {}
        for rcvr in Receiver.objects.all():
            bandStats[rcvr.code] = (0, 0)

        for p in self.proposals:
            bands = p.bands()
            backends = p.backends()
            if 'Z' in backends:
                bands += 'Z'
            for band in bands:
                num, time = bandStats.get(band, (0,0))
                bandStats[band] = (num + 1, time + (p.requestedTime() / float(len(bands))))
    
        sortedBandStats = sorted(bandStats.iteritems(), key = lambda stat: stat[0])
        for band, stats in sortedBandStats:
            data.append([Paragraph(band, self.styleSheet)
                       , Paragraph('%s' % stats[0], self.styleSheet)
                       , Paragraph('%s' % round(stats[1], 2), self.styleSheet)
                       ])
        bandStatsTable = Table(data, colWidths = [50, 50, 50])
        bandStatsTable.setStyle(self.tableStyle)

        return bandStatsTable
示例#12
0
文件: views.py 项目: luis0794/SIGIF
def generar_pdf_Factura(request):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "facturas.pdf" 
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
        )
    facturas = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Facturas", styles['Heading1'])
    facturas.append(header)
    headings = ('Numero de Factura', 'Cliente', 'Fecha', 'Total')
    allfacturas = [(p.fac_num, p.cli_id, p.fac_fec, p.fac_tot) for p in Factura.objects.order_by('fac_num')]

    t = Table([headings] + allfacturas)
    t.setStyle(TableStyle(
        [
        ('GRID', (0, 0), (5, -1), 1, colors.dodgerblue),
        ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
        ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
        ))

    facturas.append(t)
    doc.build(facturas)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#13
0
        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]
示例#14
0
def reporte_detalle_compra(request):
    print ("Genero el PDF");
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Detalle compra.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    detalles = []
    styles = getSampleStyleSheet()
    header = Paragraph("Detalle de compra", styles['Heading1'])
    detalles.append(header)
    headings = ('Numero de compra','Producto','Cantidad','Precio','Subtotal')
    alldetalles = [(d.compra,d.producto,d.cantidad,d.precio,d.subtotal) for d in DetalleCompra.objects.all()]
    print (alldetalles);

    t = Table([headings] + alldetalles)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (12, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    detalles.append(t)
    doc.build(detalles)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#15
0
    def add_info(self):
        ptext = "<b><font size=14>Report Info</font></b>"
        self.Story.append(Paragraph(ptext, self.styles["BodyText"]))
        self.Story.append(Spacer(1, 0.1 * inch))

        data = [
            ["Request Name", self.request["custom_name"]],
            ["Request Id", str(self.request["_id"])],
            ["Email", self.request["email"]],
            ["Generated on", self.time_str()],
            [
                "Download Link",
                '<a href="http://{0}/query/#/status/{1}">{0}/query/#/status/{1}</a>'.format(
                    self.download_server, self.request["_id"]
                ),
            ],
        ]

        data = [[i[0], pg(i[1], 1)] for i in data]
        t = Table(data)

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

        self.Story.append(t)
示例#16
0
def generar_pdforden(request):
    print "Genero el PDF"
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "ordenes.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    productos = []
    styles = getSampleStyleSheet()
    header = Paragraph("     Listado de Ordenes de Trabajo", styles['Heading1'])
    productos.append(header)
    headings = ('Cliente','Numero','Fecha Recepcion','Fecha Entrega','Tipo','Precio', 'Estado')
    allproductos = [(p.cli_cedula, p.ord_numero, p.ord_fechar, p.ord_fechae,p.ord_tipo,p.ord_precio,p.ord_estado) for p in OrdenTrabajo.objects.all()]
    print allproductos

    t = Table([headings] + allproductos)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (9, -1), 1, colors.springgreen),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.springgreen),
            ('BACKGROUND', (0, 0), (-1, 0), colors.springgreen)
        ]
    ))
    productos.append(t)
    doc.build(productos)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#17
0
def reporte_contactos(request):
    print ("Genero el PDF");
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "contactos.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    contactos = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Contactos de Proveedores", styles['Heading1'])
    contactos.append(header)
    headings = ('Nombre','Telefono','Correo','Proveedor','Fecha Creacion')
    allcontactos = [(c.nombre,c.telefono,c.correo,c.proveedor.nombre,c.fecha_creacion) for c in ContactoProveedor.objects.all()]
    print (allcontactos);

    t = Table([headings] + allcontactos)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (12, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    contactos.append(t)
    doc.build(contactos)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#18
0
    def getFlowable(self):
        self.parseData()
        t = Table(self.data, self.widths, self.heights)
        if self.style:
            t.setStyle(getStyles()[self.style])

        return t
示例#19
0
def generar_pdf(request):
    print "Genero el PDF"
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "productos.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    productos = []
    styles = getSampleStyleSheet()
    header = Paragraph("     Listado de Productos", styles['Heading1'])
    productos.append(header)
    headings = ('Proveedor','Categoria','Nombre','Modelo','Marca','Stock A', 'Stock M', 'Precio P', 'Precio V')
    allproductos = [(p.prov_cedula, p.cat_id, p.pro_nombre, p.pro_modelo,p.pro_marca,p.pro_stocka,p.pro_stockm,p.pro_precio,p.pro_preciov) for p in Producto.objects.all()]
    print allproductos

    t = Table([headings] + allproductos)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (9, -1), 1, colors.springgreen),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.springgreen),
            ('BACKGROUND', (0, 0), (-1, 0), colors.springgreen)
        ]
    ))
    productos.append(t)
    doc.build(productos)
    response.write(buff.getvalue())
    buff.close()
    return response
示例#20
0
文件: models.py 项目: alazo/ase
    def __init__(self, filename, title_left, title_right, portrait=True):
        if portrait is True:
            page_size = A4
            column_width = 8*cm
        else:
            page_size = landscape(A4)
            column_width = 13*cm
        SimpleDocTemplate.__init__(self, filename, pagesize=page_size,
                                   topMargin=0*cm,
                                   leftMargin=2 * cm,
                                   rightMargin=2 * cm,
                                   bottomMargin=0.5 * cm,
                                   )
        self.fileName = filename
        im1 = Image(settings.MEDIA_ROOT + 'logo_EPC.png', width=170, height=80, hAlign=TA_LEFT)
        data = list()
        data.append([im1, ''])
        data.append([Spacer(0, 0.5*cm)])

        data.append([title_left, title_right])
        t = Table(data, colWidths=[column_width]*2, hAlign=TA_LEFT)
        t.setStyle(
            TableStyle(
                [
                    ('SIZE', (0, 0), (-1, -1), 9),
                    ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                    ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                    ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                    ('LINEABOVE', (0, 0), (-1, -1), 0.5, colors.black),
                    ('LINEBELOW', (0, -1), (-1, -1), 0.5, colors.black),
                ]
            )
        )
        self.flowable.append(t)
示例#21
0
def makeSlideTable(slides, pageSize, docWidth, numCols):
    """Returns a table containing a collection of SlideWrapper flowables.
    """

    slides = handleHiddenSlides(slides)

    # Set table style.
    tabStyle = TableStyle([("GRID", (0, 0), (-1, -1), 0.25, colors.black), ("ALIGN", (0, 0), (-1, -1), "CENTRE")])

    # Build table content.
    width = docWidth / numCols
    height = width * pageSize[1] / pageSize[0]
    matrix = []
    row = []
    for slide in slides:
        sw = SlideWrapper(width, height, slide, pageSize)
        if (len(row)) < numCols:
            row.append(sw)
        else:
            matrix.append(row)
            row = []
            row.append(sw)
    if len(row) > 0:
        for i in range(numCols - len(row)):
            row.append("")
        matrix.append(row)

    # Make Table flowable.
    t = Table(matrix, [width + 5] * len(matrix[0]), [height + 5] * len(matrix))
    t.setStyle(tabStyle)

    return t
示例#22
0
    def add_form(self, num_rows, form, print_object):
        cols = print_object.get_form_field_layout()
        field_aliases, field_widths = ['ID'], [5]
        field_aliases.extend([c.field.col_alias for c in cols])
        field_widths.extend([c.width for c in cols])
        field_widths = [n/100.0*self.inner_width for n in field_widths] #normalize
        x, y = self.origin_x, self.origin_y + self.qr_size
        width = self.inner_width
        height = self.inner_height - self.qr_size - 35

        data, rowheights, header_flowables = [], [39], []
        style = ParagraphStyle(name='Helvetica', fontName='Helvetica', fontSize=10)
        for a in field_aliases:
            header_flowables.append(Paragraph('<b>%s</b>' % a, style))
        data.append(header_flowables)
        for n in range(0, num_rows):
            data.append(['' for n in field_widths])
            rowheights.append(39)

        t=Table(data, field_widths, rowheights)
        GRID_STYLE = TableStyle([
            ('GRID', (0,0), (-1,-1), 0.25, colors.black),
            ('FONT', (0,0), (-1,-1), 'HandSean'),
            ('BOX',(0,0),(-1,-1),2,colors.black)
        ])
        t.setStyle(GRID_STYLE)
        frame = Frame(x, y, width, height, showBoundary=0, leftPadding=0,
                      bottomPadding=0, rightPadding=0, topPadding=0)
        frame.addFromList([t], self.canvas)
示例#23
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]
示例#24
0
def build_marco_logo_y_empresa(dde):
    """
    dde es una lista con la ruta al logotipo de la empresa (o None) y una 
    serie de líneas de texto con los datos a mostrar de la empresa.
    Devuelve una tabla con los marcos transparentes con el logo y las 
    líneas.
    """
    if dde[0] != None:
        logo = Image(dde[0])
        logo.drawHeight = 2*cm * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 2*cm
    else:
        logo = Paragraph("", estilos["Normal"])
    lineas_empresa = dde[1:]
    if len(lineas_empresa) <= 3: 
        empresa = Preformatted("\n".join(lineas_empresa), estilos["Normal"])
    else:
        texto_empresa = lineas_empresa[0] + "\n" 
            #+ ". ".join(lineas_empresa[1:])
        resto_lineas = lineas_empresa[1:]
        pivot = len(resto_lineas)/2
        r1, r2 = resto_lineas[:pivot], resto_lineas[pivot:]
        texto_empresa += ". ".join(r1) + "\n" + ". ".join(r2)
        empresa = Preformatted(texto_empresa, estilos["Normal"])
    datos = [[logo, empresa]]
    tabla = Table(datos, 
                  colWidths = (PAGE_WIDTH * 0.25, 
                               PAGE_WIDTH * 0.65)) 
    tabla.setStyle(TableStyle([
        ("ALIGN", (0, 0), (1, 0), "RIGHT"), 
        ("ALIGN", (1, 0), (-1, -1), "LEFT"), 
        ("VALIGN", (0, 0), (-1, -1), "CENTER"), 
        ]))
    return tabla
示例#25
0
def cuadritos_en_ruta():
    """
    Devuelve dos flowables:
    Un texto centrado con el texto de "ENVASES VACÍOS..." y una tabla 
    con el texto y los cuadraditos que se rellenan a mano durante la ruta 
    del transportista.
    """
    estilo_centrado = ParagraphStyle("Alineado centrado", 
                                    parent=estilos["Normal"])
    estilo_centrado.alignment = enums.TA_CENTER
    cab = Paragraph(escribe("ENVASES VACÍOS SIN LIMPIAR, 3 A.D.R."), 
                    estilo_centrado)
    datos = [["G.R.G. 1.000L", "", "", "BIDONES 100L", ""], 
             ["",              "", "", "",             ""], 
             ["DEPÓSITO 600L", "", "", "BIDONES 50L",  ""], 
             ["",              "", "", "",             ""], 
             ["BIDONES 200L",  "", "", "GARRAFAS 60L", ""],
             ["",              "", "", "",             ""], 
             ["BIDONES 25L",   "", "", "BIDONES 10L", ""]]
    datos = [[escribe(c) for c in fila] for fila in datos]
    tabla = Table(datos, 
                  colWidths = (3*cm, 0.75*cm, 5*cm, 3*cm, 0.75*cm))
    tabla.setStyle(TableStyle([
        ("BOX", (1, 0), (1, 0), 1.0, colors.black),
        ("BOX", (4, 0), (4, 0), 1.0, colors.black),
        ("BOX", (1, 2), (1, 2), 1.0, colors.black),
        ("BOX", (4, 2), (4, 2), 1.0, colors.black),
        ("BOX", (1, 4), (1, 4), 1.0, colors.black),
        ("BOX", (4, 4), (4, 4), 1.0, colors.black),
        ("BOX", (1, 6), (1, 6), 1.0, colors.black),
        ("BOX", (4, 6), (4, 6), 1.0, colors.black),
        ]))
    return KeepTogether([Spacer(1, 0.3*cm), cab, Spacer(1, 0.5*cm), tabla])
示例#26
0
def build_encabezado(datos_albaran):
    """
    Devuelve una tabla de dos líneas con los datos del albarán, que es un 
    diccionario de: fecha -como texto-, número (de albarán), kilos, 
    bultos.
    """
    datos_albaran = sanitize(datos_albaran)
    datos = [["Fecha", escribe("Nº Albarán"), "Kilos", "Bultos"], 
             [datos_albaran["fecha"], datos_albaran["número"], 
                datos_albaran["kilos"], datos_albaran["bultos"]]]
    estilo_centrado = ParagraphStyle("Alineado centrado", 
                                     parent=estilos["Normal"])
    estilo_centrado.alignment = enums.TA_CENTER
    estilo_centrado.fontSize += 2
    datos = [[Paragraph(celda, estilos["Normal"]) for celda in datos[0]] ,
             [Paragraph(celda, estilo_centrado) for celda in datos[1]]]
    tabla = Table(datos, 
                  colWidths = (PAGE_WIDTH * 0.9/4,)*4) 
    tabla.setStyle(TableStyle([
        ("BOX", (0, 1), (-1, -1), 1.0, colors.black),
        ("INNERGRID", (0, 1), (-1, -1), 0.25, colors.black), 
        ("ALIGN", (0, 0), (-1, 0), "LEFT"), 
        ("ALIGN", (0, 1), (-1, 1), "CENTER"), 
        ]))
    return tabla
示例#27
0
def build_tabla_contenido(data):
    """
    Construye la tabla del contenido del albaranSalida.
    Los datos deben venir en listas. Cada línea de la tabla, una tupla o lista 
    con el código, descripción, cantidad, precio unitario (con dto. si lo 
    lleva e IVA) y número de pedido.
    El precio y cantidad deben ser flotantes para poder calcular el subtotal.
    """
    estilo_cabecera_tabla = ParagraphStyle("Cabecera tabla", 
                                           parent=estilos["Heading3"])
    estilo_cabecera_tabla.fontName = "Times-Bold"
    estilo_cabecera_tabla.alignment = enums.TA_CENTER
    estilo_numeros_tabla = ParagraphStyle("Números tabla", 
                                           parent=estilos["Normal"])
    estilo_numeros_tabla.alignment = enums.TA_RIGHT
    datos = [(Paragraph(escribe("Código"), estilo_cabecera_tabla), 
              Paragraph(escribe("Descripción"), estilo_cabecera_tabla), 
              Paragraph("Cantidad", estilo_cabecera_tabla), 
              Paragraph("Precio/U", estilo_cabecera_tabla), 
              #Paragraph("Total c/IVA", estilo_cabecera_tabla), 
              # CWT: Prefiere la carta de portes sin IVA.
              Paragraph("Total", estilo_cabecera_tabla), 
              Paragraph(escribe("Nº Pedido"), estilo_cabecera_tabla))
            ]
    for d in data:
        fila = (escribe(d[0]), 
                Paragraph(escribe(d[1]),estilos["Normal"]), 
                Paragraph(escribe(utils.float2str(d[2])),estilo_numeros_tabla),
                Paragraph(escribe(utils.float2str(d[3])),estilo_numeros_tabla),
                Paragraph(escribe(utils.float2str(d[2] * d[3])), 
                    estilo_numeros_tabla),
                escribe(d[4])
               )
        datos.append(fila)
    tabla = Table(datos, 
                  colWidths = (PAGE_WIDTH * 0.13, 
                               PAGE_WIDTH * 0.35, 
                               PAGE_WIDTH * 0.09, 
                               PAGE_WIDTH * 0.09, 
                               PAGE_WIDTH * 0.13, 
                               PAGE_WIDTH * 0.11), 
                  repeatRows = 1)
    tabla.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey), 
        ("LINEBEFORE", (0, 0), (-1, -1), 0.25, colors.black),
        ("LINEBELOW", (0, 0), (-1, 0), 1.0, colors.black), 
        ("LINEBELOW", (0, "splitlast"), (-1, "splitlast"), 1.0, colors.black), 
        ("BOX", (0, 0), (-1, -1), 1.0, colors.black),
        ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), 
        ("VALIGN", (0, 0), (-1, 0), "CENTER"), 
        ("VALIGN", (0, 0), (0, -1), "TOP"), 
        ("ALIGN", (0, 0), (-1, 0), "CENTER"), 
        ("ALIGN", (-3, 1), (-1, -1), "RIGHT"), 
        #("ALIGN", (0, 1), (0, -1), "DECIMAL"), <- No puedo cambiar 
        #                               el pivotChar de "." a ",". No me vale.
        ("ALIGN", (-1, 1), (-1, -1), "CENTER"), 
        ("ALIGN", (0, 1), (0, -1), "CENTER"), 
        #("RIGHTPADDING", (0, 1), (0, -1), 0.75 * cm), 
        ]))
    return tabla
示例#28
0
 def add_form(self, num_rows, form, is_mini_form=False):
     cols = form.get_fields(print_only=True)
     field_aliases, field_widths = ['ID'], [5]
     field_aliases.extend([c.col_alias for c in cols])
     field_widths.extend([c.display_width for c in cols])
     field_widths = [n/100.0*self.inner_width for n in field_widths] #normalize
     x, y = self.origin_x, self.origin_y + self.qr_size
     width = self.inner_width
     height = self.inner_height - self.qr_size - 35
     if is_mini_form:
         height = Units.pixel_to_point(300) #only render a 300-pixel tall form
     
     data, rowheights, header_flowables = [], [39], []
     style = ParagraphStyle(name='Helvetica', fontName='Helvetica', fontSize=10)
     for a in field_aliases:
         header_flowables.append(Paragraph('<b>%s</b>' % a, style))
     data.append(header_flowables)
     for n in range(0, num_rows):
         data.append(['', '', '', ''])
         rowheights.append(39)
 
     t=Table(data, field_widths, rowheights)
     GRID_STYLE = TableStyle([
         ('GRID', (0,0), (-1,-1), 0.25, colors.black),
         ('FONT', (0,0), (-1,-1), 'HandSean'),
         ('BOX',(0,0),(-1,-1),2,colors.black)
     ])
     t.setStyle(GRID_STYLE)
     frame = Frame(x, y, width, height, showBoundary=0, leftPadding=0,
                   bottomPadding=0, rightPadding=0, topPadding=0)
     frame.addFromList([t], self.canvas)
示例#29
0
    def Cases(self, modele=[1, 1, 1, 0, 1, 1, 1], texte="", largeurColonnes=10, couleur=(0.8, 0.8, 0.8)) :
        """ 
        1 = Case à avec texte avec cadre
        2 = Case avec texte sans cadre
        0 = Case sans texte et sans cadre
        """        
        if texte == None : texte = ""
        dataTableau = []
        largeursColonnes = []
        listeStyles = [
            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), 
            ('ALIGN', (0, 0), (-1, -1), "CENTER"), 
            ]
        indexColonne = 0
        indexTexte = 0
        for code in modele :
            largeursColonnes.append(largeurColonnes) 
            
            if code == 1 or code == 2 :
                if len(texte) > indexTexte :
                    dataTableau.append(texte[indexTexte])
                    indexTexte += 1
                else :
                    dataTableau.append("")
                if code == 1 :
                    listeStyles.append(('GRID', (indexColonne, 0), (indexColonne, -1), 0.25, couleur))
            else :
                dataTableau.append("")
            indexColonne += 1

        style = TableStyle(listeStyles)
        tableau = Table([dataTableau,], largeursColonnes)
        tableau.setStyle(style)
        return tableau
示例#30
0
	def add_pdf_text(self, finding_name, phase, findings, risk_level, category_level, PoC_notes):
		
		
		
		
		data = [
		    [Paragraph(finding_name, styles["Normal"]), Paragraph(phase, styles["Normal"])],
		    [Paragraph(findings, styles["Normal"]), Paragraph('Risk Level', styles["Normal"]), Paragraph('Category', styles["Normal"])],
		    [Paragraph('Proof of Concept', styles["Normal"]), Paragraph(risk_level, styles["Normal"]), Paragraph(category_level, styles["Normal"])],
		    [Paragraph(PoC_notes, styles["Normal"])],
		    [Paragraph('======================================================================================================================', styles["Normal"])],
		    ]
		
		
		
		
		
		table = Table(data, [3 * inch, 1.5 * inch, inch])
		table_with_style = Table(data, [5 * inch, 1.5 * inch, inch])
		table_with_style.setStyle(TableStyle([
		    ('FONT', (0, 0), (-1, -1), 'Helvetica'),
		    ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
		    ('FONT', (0, 0), (-1, 1), 'Helvetica-Bold'),
		    ('FONTSIZE', (0, 0), (-1, -1), 8),
		    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
		    ('BOX', (0, 0), (-1, 0), 0.25, colors.green),
		    ('ALIGN', (0, 0), (-1, 0), 'LEFT'),
		]))
		#~ parts.append(table)
		Story = Spacer(1, 0.5 * inch)
		
		parts.append(Story)
		
		parts.append(table_with_style)
def _create_invoice(invoice_buffer, invoice, proposal):

    global DPAW_HEADER_LOGO
    #    if  cols_var["TEMPLATE_GROUP"] == 'rottnest':
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'mooring', 'static', 'mooring', 'img','logo-rottnest-island-sm.png')
    #    else:
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'ledger', 'payments','static', 'payments', 'img','dbca_logo.jpg')
    DPAW_HEADER_LOGO = os.path.join(settings.PROJECT_DIR, 'payments', 'static',
                                    'payments', 'img', 'dbca_logo.jpg')

    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN + 250,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 450,
                             id='EveryPagesFrame',
                             showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN,
                        PAGE_MARGIN,
                        PAGE_WIDTH - 2 * PAGE_MARGIN,
                        PAGE_HEIGHT - 600,
                        id='RemitFrame',
                        showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame, remit_frame],
                                       onPage=_create_header)

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

    # this is the only way to get data into the onPage callback function
    doc.invoice = invoice
    doc.proposal = proposal
    owner = invoice.owner

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                      ('GRID', (0, 0), (-1, -1), 1,
                                       colors.black),
                                      ('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    items = invoice.order.lines.all()
    discounts = invoice.order.basket_discounts
    if invoice.text:
        elements.append(Paragraph(invoice.text, styles['Left']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    data = [['Item', 'Product', 'Quantity', 'Unit Price', 'Total']]
    val = 1
    s = styles["BodyText"]
    s.wordWrap = 'CJK'

    for item in items:
        data.append([
            val,
            Paragraph(item.description, s), item.quantity,
            currency(item.unit_price_incl_tax),
            currency(item.line_price_before_discounts_incl_tax)
        ])
        val += 1
    # Discounts
    data.append(['', '', '', ''])
    for discount in discounts:
        data.append(
            ['', discount.offer, '', '', '-${}'.format(discount.amount)])
        val += 1
    t = Table(data,
              style=invoice_table_style,
              hAlign='LEFT',
              colWidths=(
                  0.7 * inch,
                  None,
                  0.7 * inch,
                  1.0 * inch,
                  1.0 * inch,
              ))
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    if invoice.payment_status != 'paid' and invoice.payment_status != 'over_paid':
        elements.append(
            Paragraph(settings.INVOICE_UNPAID_WARNING, styles['Left']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 6))

    # Remitttance Frame
    elements.append(FrameBreak())
    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN * 1.1))
    elements.append(boundary)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    remittance = Remittance(HEADER_MARGIN, HEADER_MARGIN - 10, proposal,
                            invoice)
    elements.append(remittance)
    #_create_remittance(invoice_buffer,doc)
    doc.build(elements)

    return invoice_buffer
示例#32
0
def export_pdf(request, id, uidb64=None, token=None):
    '''
    Generates a PDF with the contents of a nutrition plan

    See also
    * http://www.blog.pythonlibrary.org/2010/09/21/reportlab
    * http://www.reportlab.com/apis/reportlab/dev/platypus.html
    '''

    # Load the plan
    if uidb64 is not None and token is not None:
        if check_token(uidb64, token):
            plan = get_object_or_404(NutritionPlan, pk=id)
        else:
            return HttpResponseForbidden()
    else:
        if request.user.is_anonymous():
            return HttpResponseForbidden()
        plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)

    plan_data = plan.get_nutritional_values()

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')

    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            title=_('Nutrition plan'),
                            author='wger Workout Manager',
                            subject=_('Nutritional plan %s') %
                            request.user.username)

    # Background colour for header
    # Reportlab doesn't use the HTML hexadecimal format, but has a range of
    # 0 till 1, so we have to convert here.
    header_colour = colors.Color(
        int('73', 16) / 255.0,
        int('8a', 16) / 255.0,
        int('5f', 16) / 255.0)

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

    # Iterate through the Plan
    meal_markers = []
    ingredient_markers = []

    # Meals
    i = 0
    for meal in plan.meal_set.select_related():
        i += 1

        meal_markers.append(len(data))

        if not meal.time:
            p = Paragraph(
                u'<para align="center"><strong>{nr} {meal_nr}</strong></para>'.
                format(nr=_('Nr.'), meal_nr=i), styleSheet["Normal"])
        else:
            p = Paragraph(
                u'<para align="center"><strong>'
                u'{nr} {meal_nr} - {meal_time}'
                u'</strong></para>'.format(
                    nr=_('Nr.'),
                    meal_nr=i,
                    meal_time=meal.time.strftime("%H:%M")),
                styleSheet["Normal"])
        data.append([p])

        # Ingredients
        for item in meal.mealitem_set.select_related():
            ingredient_markers.append(len(data))

            p = Paragraph(u'<para>{0}</para>'.format(item.ingredient.name),
                          styleSheet["Normal"])
            if item.get_unit_type() == MEALITEM_WEIGHT_GRAM:
                unit_name = 'g'
            else:
                unit_name = ' ' + item.weight_unit.unit.name

            data.append([
                Paragraph(u"{0}{1}".format(item.amount, unit_name),
                          styleSheet["Normal"]), p
            ])

    # Set general table styles
    table_style = []

    # Set specific styles, e.g. background for title cells
    for marker in meal_markers:
        # Set background colour for headings
        table_style.append(
            ('BACKGROUND', (0, marker), (-1, marker), header_colour))
        table_style.append(
            ('BOX', (0, marker), (-1, marker), 1.25, colors.black))

        # Make the headings span the whole width
        table_style.append(('SPAN', (0, marker), (-1, marker)))

    # has the plan any data?
    if data:
        t = Table(data, style=table_style)

        # Manually set the width of the columns
        t._argW[0] = 2.5 * cm

    # There is nothing to output
    else:
        t = Paragraph(
            _('<i>This is an empty plan, what did you expect on the PDF?</i>'),
            styleSheet["Normal"])

    # Set the title (if available)
    if plan.description:
        p = Paragraph(
            '<para align="center"><strong>%(description)s</strong></para>' %
            {'description': plan.description}, styleSheet["Bold"])
        elements.append(p)

        # Filler
        elements.append(Spacer(10 * cm, 0.5 * cm))

    # append the table to the document
    elements.append(t)
    elements.append(Paragraph('<para>&nbsp;</para>', styleSheet["Normal"]))

    # Create table with nutritional calculations
    data = []
    data.append([
        Paragraph(
            u'<para align="center">{0}</para>'.format(_('Nutritional data')),
            styleSheet["Bold"])
    ])
    data.append([
        Paragraph(_('Macronutrients'), styleSheet["Normal"]),
        Paragraph(_('Total'), styleSheet["Normal"]),
        Paragraph(_('Percent of energy'), styleSheet["Normal"]),
        Paragraph(_('g per body kg'), styleSheet["Normal"])
    ])
    data.append([
        Paragraph(_('Energy'), styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['total']['energy']),
                  styleSheet["Normal"])
    ])
    data.append([
        Paragraph(_('Protein'), styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['total']['protein']),
                  styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['percent']['protein']),
                  styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['per_kg']['protein']),
                  styleSheet["Normal"])
    ])
    data.append([
        Paragraph(_('Carbohydrates'), styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['total']['carbohydrates']),
                  styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['percent']['carbohydrates']),
                  styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['per_kg']['carbohydrates']),
                  styleSheet["Normal"])
    ])
    data.append([
        Paragraph(_('Sugar content in carbohydrates'), styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['total']['carbohydrates_sugar']),
                  styleSheet["Normal"])
    ])
    data.append([
        Paragraph(_('Fat'), styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['total']['fat']),
                  styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['percent']['fat']),
                  styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['per_kg']['fat']),
                  styleSheet["Normal"])
    ])
    data.append([
        Paragraph(_('Saturated fat content in fats'), styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['total']['fat_saturated']),
                  styleSheet["Normal"])
    ])
    data.append([
        Paragraph(_('Fibres'), styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['total']['fibres']),
                  styleSheet["Normal"])
    ])
    data.append([
        Paragraph(_('Sodium'), styleSheet["Normal"]),
        Paragraph(six.text_type(plan_data['total']['sodium']),
                  styleSheet["Normal"])
    ])

    table_style = []
    table_style.append(('BOX', (0, 0), (-1, -1), 1.25, colors.black))
    table_style.append(('GRID', (0, 0), (-1, -1), 0.40, colors.black))
    table_style.append(('SPAN', (0, 0), (-1, 0)))  # Title
    table_style.append(('SPAN', (1, 2), (-1, 2)))  # Energy
    table_style.append(('SPAN', (1, 5), (-1, 5)))  # Sugar
    table_style.append(('SPAN', (1, 7), (-1, 7)))  # Saturated fats
    table_style.append(('SPAN', (1, 8), (-1, 8)))  # Fibres
    table_style.append(('SPAN', (1, 9), (-1, 9)))  # Sodium
    t = Table(data, style=table_style)
    t._argW[0] = 5 * cm
    elements.append(t)

    # Footer, date and info
    elements.append(Spacer(10 * cm, 0.5 * cm))
    created = datetime.date.today().strftime("%d.%m.%Y")
    url = reverse('nutrition:plan:view', kwargs={'id': plan.id})
    p = Paragraph(
        '''<para align="left">
                        %(date)s -
                        <a href="%(url)s">%(url)s</a> -
                        %(created)s
                        %(version)s
                    </para>''' % {
            'date': _("Created on the <b>%s</b>") % created,
            'created': "wger Workout Manager",
            'version': get_version(),
            'url': request.build_absolute_uri(url),
        }, styleSheet["Normal"])
    elements.append(p)
    doc.build(elements)

    response[
        'Content-Disposition'] = 'attachment; filename=nutritional-plan.pdf'
    response['Content-Length'] = len(response.content)
    return response
示例#33
0
def build(spec, data):
    reload(sys)
    sys.setdefaultencoding("utf-8")
    init()
    global form
    form = spec
    global valor
    valor = data
    story = []
    head = []
    header = form['header']['name']  # Title Form
    for group in form['payload']:  # Load Group
        # si el grupo tiene propiedad showby y no tiene 'data' no se imprime el mismo.
        if 'showby' in group[group.keys()[0]]['properties']:
            showby = group[group.keys()[0]]['properties']['showby']
            if showby == None:
                group_showby = True
            elif showby == 'true':
                group_showby = True
            elif showby == '':
                group_showby = True
            elif showby == False:
                group_showby = False
            elif showby == True:
                group_showby = True
            elif len(showby) != 0:
                if group.keys()[0] in valor:  # si el grupo tiene datos
                    if len(valor[group.keys()[0]]) == 0:
                        group_showby = False
                    else:
                        group_showby = True
                else:
                    group_showby = False
            else:
                group_showby = True
        else:
            group_showby = True

        # check 'notshowgroupinpdf'
        if 'notshowgroupinpdf' in group[group.keys()[0]]['properties']:
            if group[group.keys()
                     [0]]['properties']['notshowgroupinpdf'] == True:
                group_showby = False

        if group_showby:
            head = []
            if 'label' in group[group.keys()[0]]['properties']:
                head.append(
                    [
                        Preformatted(
                            group[group.keys()[0]]['properties']['label'],
                            styles['stileheader2'],
                            maxLineLength=500)
                    ]
                )  # Titulo del Grupo / meto el titulo dentro de la tabla para obtener la misma tabulacion de los detalles
            else:
                head.append(
                    [
                        Preformatted('',
                                     styles['stileheader2'],
                                     maxLineLength=150)
                    ]
                )  # Titulo del Grupo / meto el titulo dentro de la tabla para obtener la misma tabulacion de los detalles
            table = Table(head, colWidths='100%')
            table.hAlign = TA_LEFT
            story.append(table)
            story.append(Spacer(1, 3))
            #story.append(separador)
            story.append(Spacer(1, 5))
            table = Table([''])

            grupo = group[group.keys()[0]]['properties'][
                'name']  # nombre del Grupo
            if 'usedatagrid' in group[group.keys()[0]]['properties']:
                datagrid = group[group.keys()[0]]['properties']['usedatagrid']
            else:
                datagrid = False

            if 'components' in group[group.keys()[0]] and datagrid == True:
                data_Grid = Grid(group, grupo)
                if len(data_Grid) != 0:
                    table = Table(data_Grid, colWidths='100%')
            elif 'components' in group[group.keys()[0]] and datagrid == False:
                table = Table(Group(group, grupo), colWidths='100%')
            else:
                table = Table([''])

            table.hAlign = TA_LEFT
            story.append(table)
            story.append(Spacer(1, 15))

    doc = docTemplate(files)
    doc.build(story)  # save pdf

    with open(files, "rb") as image_file:  # Transforma PDF en binario base64
        encoded_string = base64.b64encode(image_file.read())
    os.remove(files)  # remove  file

    return encoded_string
示例#34
0
    def contenido(self, pdf, y):
        width, height = A4
        styles = getSampleStyleSheet()
        styleN = styles["BodyText"]
        styleN.alignment = TA_CENTER
        Numero = Paragraph('<b>N.-</b>', styleN)
        Codigo = Paragraph('<b>Codigo</b>', styleN)
        N_evento = Paragraph('<b>Nombre del evento</b>', styleN)
        Cedula = Paragraph('<b>Cedula</b>', styleN)
        N_part = Paragraph('<b>Nombre del Participante</b>', styleN)
        Asistencia = Paragraph('<b>Asistencia</b>', styleN)
        N_final = Paragraph('<b>Nota final</b>', styleN)
        encabezado1 = [[
            Numero, Codigo, N_evento, Cedula, N_part, Asistencia, N_final
        ], ['1', '', '', '', '', '%', ''], ['2', '', '', '', '', '', ''],
                       ['3', '', '', '', '', '', ''],
                       ['4', '', '', '', '', '', '']]

        t = Table(encabezado1,
                  colWidths=[
                      1 * cm, 2 * cm, 5 * cm, 3.1 * cm, 5 * cm, 2.3 * cm,
                      2 * cm
                  ])
        t.setStyle(
            TableStyle([
                ('BOX', (0, 0), (-1, -1), 0.20, colors.black),
                ('INNERGRID', (0, 0), (-1, -1), 0.10, colors.black),
                ('BOTTOMPADDING', (0, 0), (5, 0), 10),
            ]))

        t.wrapOn(pdf, width, height)
        t.drawOn(pdf, 8, 650)
        #Formulario Inferior
        styleB = styles["BodyText"]
        styleB.alignment = TA_LEFT
        var_1 = Paragraph('<b>Total reprobados por asistencia</b>', styleB)
        var_2 = Paragraph('<b>Total por Evento</b>', styleB)
        var_3 = Paragraph('<b>Total reprobados por  calificación</b>', styleB)
        var_4 = Paragraph('<b>Total inscritos personalmente</b>', styleB)
        var_5 = Paragraph('<b>Total inscritos Auspiciados </b>', styleB)
        form_inferior = [[
            var_1, 'Σ total', 'Asistencia minina del 80%', var_2, 'Σ total'
        ], [var_3, 'Σ total', 'Nota mínima 70/100', var_4, 'Σ total'],
                         ['', '', '', var_5, 'Σ total']]
        t_form = Table(form_inferior,
                       colWidths=[5 * cm, 2 * cm, 4.5 * cm, 5 * cm, 4 * cm])
        t_form.setStyle(
            TableStyle([
                ('BOTTOMPADDING', (3, 0), (3, 0), 15),
                ('BOTTOMPADDING', (1, 0), (1, 0), 15),
                ('BOTTOMPADDING', (1, 1), (1, 1), 15),
                ('BOTTOMPADDING', (2, 0), (2, 0), 15),
                ('BOTTOMPADDING', (2, 1), (2, 1), 15),
                ('BOTTOMPADDING', (4, 0), (4, 0), 15),
                ('BOTTOMPADDING', (4, 1), (4, 1), 15),
                ('BOTTOMPADDING', (4, 2), (4, 2), 15),
            ]))

        t_form.wrapOn(pdf, width, height)
        t_form.drawOn(pdf, 8, 90)
	def create_sheet(self):
		styleSheet = getSampleStyleSheet()
		styNormal = styleSheet['Normal']
		styNormal.spaceBefore = 20
		styNormal.spaceAfter = 20
		styNormal.alignment = 0 #LEFT

		styleSheet = getSampleStyleSheet()
		styDescrizione = styleSheet['Normal']
		styDescrizione.spaceBefore = 20
		styDescrizione.spaceAfter = 20
		styDescrizione.alignment = 4 #Justified

		#format labels

		#0 row
		intestazione = Paragraph("<b>SCHEDA TAFONOMICA<br/>" + str(self.datestrfdate()) + "</b>", styNormal)

		
		#intestazione2 = Paragraph("<b>pyArchInit</b><br/>pyarchinit", styNormal)
		
		#intestazione2  = Paragraph("<b>Ditta esecutrice</b><br/>", styNormal)
		if os.name == 'posix':
			home = os.environ['HOME']
		elif os.name == 'nt':
			home = os.environ['HOMEPATH']

		home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder')
		logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg')
		logo = Image(logo_path)

		##		if test_image.drawWidth < 800:

		logo.drawHeight = 1.5*inch*logo.drawHeight / logo.drawWidth
		logo.drawWidth = 1.5*inch

		#1 row
		sito = Paragraph("<b>Sito</b><br/>"  + str(self.sito), styNormal)
		sigla_struttura = Paragraph("<b>Sigla struttura</b><br/>"  + str(self.sigla_struttura)+str(self.nr_struttura), styNormal)
		nr_individuo = Paragraph("<b>Nr. Individuo</b><br/>"  + str(self.nr_individuo), styNormal)
		nr_scheda = Paragraph("<b>Nr. Scheda</b><br/>"  + str(self.nr_scheda_taf), styNormal)

		#2 row
		periodizzazione = Paragraph("<b>PERIODIZZAZIONE DEL RITO DI SEPOLTURA</b><br/>", styNormal)

		#3 row
		if  str(self.periodo_iniziale) == "None":
			periodo_iniziale = Paragraph("<b>Periodo iniziale</b><br/>", styNormal)
		else:
			periodo_iniziale = Paragraph("<b>Periodo iniziale</b><br/>" + str(self.periodo_iniziale), styNormal)
		
		if  str(self.fase_iniziale) == "None":
			fase_iniziale = Paragraph("<b>Fase iniziale</b><br/>", styNormal)
		else:
			fase_iniziale = Paragraph("<b>Fase iniziale</b><br/>" + str(self.fase_iniziale), styNormal)

		if  str(self.periodo_finale) == "None":
			periodo_finale = Paragraph("<b>Periodo finale</b><br/>", styNormal)
		else:
			periodo_finale = Paragraph("<b>Periodo finale</b><br/>" + str(self.periodo_finale), styNormal)
			

		if  str(self.fase_finale) == "None":
			fase_finale = Paragraph("<b>Fase finale</b><br/>", styNormal)
		else:
			fase_finale = Paragraph("<b>Fase finale</b><br/>" + str(self.fase_finale), styNormal)

		#4 row
		if  str(self.datazione_estesa) == "None":
			datazione_estesa = Paragraph("<b>Datazione estesa</b><br/>", styNormal)
		else:
			datazione_estesa = Paragraph("<b>Datazione estesa</b><br/>" + str(self.datazione_estesa), styNormal)

		#5 row
		elementi_strutturali = Paragraph("<b>ELEMENTI STRUTTURALI</b></b>",styNormal)

		#6row
		tipo_contenitore_resti = Paragraph("<b>Tipo contenitore resti</b><br/>"  + str(self.tipo_contenitore_resti), styNormal)
		tipo_copertura = Paragraph("<b>Tipo copertura</b><br/>"  + str(self.copertura_tipo), styNormal)
		segnacoli = Paragraph("<b>Segnacoli</b><br/>"  + str(self.segnacoli), styNormal)
		canale_libatorio = Paragraph("<b>Canale libatorio</b><br/>"  + str(self.canale_libatorio_si_no), styNormal)

		#7 row
		dati_deposizionali = Paragraph("<b>DATI DEPOSIZIONALI INUMATO<b></b>",styNormal)

		#8 row
		rito = Paragraph("<b>Rito</b><br/>"  + self.rito, styNormal)
		orientamento_asse = Paragraph("<b>Orientamento asse</b><br/>"  + str(self.orientamento_asse), styNormal)
		if str(self.orientamento_azimut) == "None":
			orientamento_azimut = Paragraph("<b>Azimut</b><br/>", styNormal)
		else:
			orientamento_azimut_conv = self.PU.conversione_numeri(self.orientamento_azimut)
			orientamento_azimut = Paragraph("<b>Azimut</b><br/>"  + orientamento_azimut_conv + "°", styNormal)
		posizione_cranio = Paragraph("<b>Posizione cranio</b><br/>"  +  str(self.posizione_cranio), styNormal)

		#9 row
		posizione_scheletro = Paragraph("<b>Posizione scheletro</b><br/>"  + str(self.posizione_scheletro), styNormal)
		if str(self.lunghezza_scheletro) == "None":
			lunghezza_scheletro = Paragraph("<b>Lunghezza scheletro</b><br/>", styNormal)
		else:
			lunghezza_scheletro_conv = self.PU.conversione_numeri(self.lunghezza_scheletro)
			lunghezza_scheletro = Paragraph("<b>Lunghezza scheletro</b><br/>"  + lunghezza_scheletro_conv +" m", styNormal)
		posizione_arti_superiori = Paragraph("<b>Posizione arti superiori</b><br/>"  + str(self.posizione_arti_superiori), styNormal)
		posizione_arti_inferiori = Paragraph("<b>Posizione arti inferiori</b><br/>"  + str(self.posizione_arti_inferiori), styNormal)

		#10 row
		dati_postdeposizionali = Paragraph("<b>DATI POSTDEPOSIZIONALI<b></b>",styNormal)

		#11 row
		stato_conservazione = Paragraph("<b>Stato di conservazione</b><br/>"  + str(self.stato_di_conservazione), styNormal)
		disturbato = Paragraph("<b>Disturbato</b><br/>"  + str(self.segnacoli), styNormal)
		completo = Paragraph("<b>Completo</b><br/>"  + str(self.canale_libatorio_si_no), styNormal)
		in_connessione = Paragraph("<b>In connessione</b><br/>"  + str(self.oggetti_rinvenuti_esterno), styNormal)

		#12 row
		caratteristiche_tafonomiche = ''
		caratteristiche_list = eval(self.caratteristiche)
		if len(caratteristiche_list) > 0 :
			for i in caratteristiche_list:
				if caratteristiche_tafonomiche == '':
					caratteristiche_tafonomiche = ("Tipo caratteristica: %s, posizione: %s") % (str(i[0]), str(i[1]))
				else:
					caratteristiche_tafonomiche += ("<br/>Tipo caratteristica: %s, posizione: %s") % (str(i[0]), str(i[1]))

		caratteristiche_tafonomiche_txt = Paragraph("<b>CARATTERISTICHE TAFONOMICHE</b><br/>"  + caratteristiche_tafonomiche, styNormal)


		#13 row
		descrizione = ''
		try:
			descrizione = Paragraph("<b>Descrizione</b><br/>" + str(self.descrizione_taf), styDescrizione)
		except:
			pass

		interpretazione = ''
		try:
			interpretazione = Paragraph("<b>Interpretazione</b><br/>" + str(self.interpretazione_taf),styDescrizione)
		except:
			pass
		
		#14 row
		corredo = Paragraph("<b>CORREDO</b></b>",styNormal)

		#15 row
		corredo_presente = Paragraph("<b>Presenza</b><br/>" + str(self.corredo_presenza),styDescrizione)
		
		#16 row
		corredo_descrizione = Paragraph("<b>Descrizione</b><br/>" + str(self.corredo_descrizione),styDescrizione)

		#17 row
		corredo_tipo = ''
		if eval(self.corredo_tipo) > 0 :
			for i in eval(self.corredo_tipo):
				if corredo_tipo == '':
					try:
						corredo_tipo += ("Nr. reperto %s, tipo corredo: %s, descrizione: %s") % (str(i[0]), str(i[1]), str(i[2]))
					except:
						pass
				else:
					try:
						corredo_tipo += ("<br/>Nr. reperto %s, tipo corredo: %s, descrizione: %s") % (str(i[0]), str(i[1]), str(i[2]))
					except:
						pass

		corredo_tipo_txt = Paragraph("<b>Singoli oggetti di corredo</b><br/>"  + corredo_tipo, styNormal)
		
		#18 row
		misure_tafonomia = ''
		if eval(self.misure_tafonomia) > 0 :
			for i in eval(self.misure_tafonomia):
				if misure_tafonomia == '':
					try:
						misure_tafonomia += ("%s: %s %s") % (str(i[0]), str(i[2]), str(i[1]))
					except:
						pass
				else:
					try:
						misure_tafonomia += ("<br/>%s: %s %s") % (str(i[0]), str(i[2]), str(i[1]))
					except:
						pass

		misure_tafonomia_txt = Paragraph("<b>Misurazioni</b><br/>"  + misure_tafonomia, styNormal)

		#19 row
		quote_tafonomia = Paragraph("<b>QUOTE INDIVIDUO E STRUTTURA</b><br/>", styNormal)

		#20 row
		quota_min_ind = Paragraph("<b>Quota min individuo</b><br/>" + str(self.quota_min_ind), styNormal)
		quota_max_ind = Paragraph("<b>Quota max individuo</b><br/>" + str(self.quota_max_ind), styNormal)
		quota_min_strutt = Paragraph("<b>Quota min struttura</b><br/>" + str(self.quota_min_strutt), styNormal)
		quota_max_strutt = Paragraph("<b>Quota max struttura</b><br/>" + str(self.quota_max_strutt), styNormal)


		#schema
		cell_schema =  [ #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
						[intestazione, '01', '02', '03', '04','05', '06', logo, '08', '09'], #0 row  ok
						[sito, '01', '02', '03', '04', sigla_struttura, '06', '07',nr_individuo,nr_scheda], #1 row ok
						[periodizzazione, '01', '02', '03', '04', '07', '06', '07','08', '09'], #2 row ok
						[periodo_iniziale, '01', '02', fase_iniziale, '04', periodo_finale, '06', fase_finale,'08','09'], #3 row ok
						[datazione_estesa, '01', '02', '03', '04', '07', '06', '07','08', '09'], #4 row ok
						[elementi_strutturali, '01', '02', '03', '04', '07', '06', '07','08', '09'], #5 row ok
						[tipo_contenitore_resti, '01', '02', tipo_copertura,'04', segnacoli,'06', canale_libatorio, '08'], #6 row ok
						[dati_deposizionali, '01', '02','03','04', '05','06', '07', '08','09'], #7 row ok
						[rito, '01', '02',orientamento_asse,'04', orientamento_azimut,'06', posizione_cranio, '08','09'], #8 row ok
						[posizione_scheletro, '01', lunghezza_scheletro, '03', posizione_arti_superiori,'05','06', posizione_arti_inferiori, '08','09'], #9 row ok
						[dati_postdeposizionali, '01', '02','03','04', '05','06', '07', '08','09'], #10 row ok
						[stato_conservazione, '01', '02', disturbato,'04', completo,'06', in_connessione, '08'], #11 row ok
						[caratteristiche_tafonomiche_txt, '01', '02','03','04', '05','06', '07', '08','09'], #12 row ok
						[descrizione, '01','02', '03', '04', interpretazione, '06', '07', '08', '09'], #13 row ok
						[corredo, '01', '02', '03', '04', '05', '06', '07', '08', '09'], #14 row ok
						[corredo_presente,'01', '02', '03', '04','05', '06', '07', '08', '09'], #15 ow
						[corredo_descrizione,'01', '02', '03', '04','05', '06', '07', '08', '09'], #16 row
						[corredo_tipo_txt,'01', '02', '03', '04','05', '06', '07', '08', '09'], #17 row
						[misure_tafonomia_txt,'01', '02', '03', '04','05', '06', '07', '08', '09'], #18 row
						[quote_tafonomia, '01', '02', '03', '04', '07', '06', '07','08', '09'], #19 row ok
						[quota_min_ind, '01', '02', quota_max_ind, '04', quota_min_strutt, '06', quota_max_strutt,'08','09'] #20 row ok
						]

		#table style
		table_style=[
					('GRID',(0,0),(-1,-1),0.5,colors.black),
					#0 row
					('SPAN', (0,0),(6,0)),  #intestazione
					('SPAN', (7,0),(9,0)),  #intestazione

					#1 row
					('SPAN', (0,1),(4,1)),  #dati identificativi
					('SPAN', (5,1),(7,1)),  #dati identificativi
					('SPAN', (8,1),(8,1)),  #dati identificativi
					('SPAN', (9,1),(9,1)),  #dati identificativi

					#2 row
					('SPAN', (0,2),(9,2)),  #Periodizzazione
	
					#3 row
					('SPAN', (0,3),(2,3)),  #
					('SPAN', (3,3),(4,3)),  #
					('SPAN', (5,3),(6,3)),  #
					('SPAN', (7,3),(9,3)),  #
					
					#4 row
					('SPAN', (0,4),(9,4)),  #datazione estesa
					##################################
					#5 row
					('SPAN', (0,5),(9,5)),  #Elementi strutturali

					#6 row
					('SPAN', (0,6),(2,6)),  #
					('SPAN', (3,6),(4,6)),  #
					('SPAN', (5,6),(6,6)),  #
					('SPAN', (7,6),(9,6)),  #

					#7 row
					('SPAN', (0,7),(9,7)),  #

					#8 row
					('SPAN', (0,8),(2,8)),  #
					('SPAN', (3,8),(4,8)),  #
					('SPAN', (5,8),(6,8)),  #
					('SPAN', (7,8),(9,8)),  #

					#9 row
					('SPAN', (0,9),(1,9)),  #
					('SPAN', (2,9),(3,9)),  #
					('SPAN', (4,9),(6,9)),  #
					('SPAN', (7,9),(9,9)),  #

					#10 row
					('SPAN', (0,10),(9,10)),  #

					#11 row
					('SPAN', (0,11),(2,11)),  #
					('SPAN', (3,11),(4,11)),  #
					('SPAN', (5,11),(6,11)),  #
					('SPAN', (7,11),(9,11)),  #

					#12 row
					('SPAN', (0,12),(9,12)),  #

					#13 row
					('SPAN', (0,13),(4,13)),  #
					('SPAN', (5,13),(9,13)),  #

					#14 row
					('SPAN', (0,14),(9,14)),  #

					#15 row
					('SPAN', (0,15),(9,15)),  #

					#16 row
					('SPAN', (0,16),(9,16)),  

					#17 row
					('SPAN', (0,17),(9,17)),  #

					#18 row
					('SPAN', (0,18),(9,18)),  #

					('SPAN', (0,19),(9,19)),  #Periodizzazione

					#3 row
					('SPAN', (0,20),(2,20)),  #
					('SPAN', (3,20),(4,20)),  #
					('SPAN', (5,20),(6,20)),  #
					('SPAN', (7,20),(9,20)),  #

					('VALIGN',(0,0),(-1,-1),'TOP')

					]

		t=Table(cell_schema, colWidths=50, rowHeights=None,style= table_style)

		return t
    def create_sheet_en(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  # Justified

        # format labels

        # 0 row
        intestazione = Paragraph(
            "<b>STONE FORM<br/>" + str(self.datestrfdate()) + "</b>",
            styNormal)
        # intestazione2 = Paragraph("<b>pyArchInit</b>", styNormal)

        home = os.environ['PYARCHINIT_HOME']

        conn = Connection()
        lo_path = conn.logo_path()
        lo_path_str = lo_path['logo']
        home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder')
        logo_path = lo_path_str  # '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg')
        alma = Image(logo_path)

        ##      if test_image.drawWidth < 800:

        alma.drawHeight = 1.5 * inch * alma.drawHeight / alma.drawWidth
        alma.drawWidth = 1.5 * inch

        # 1 row
        sito = Paragraph("<b>Context</b><br/>" + str(self.sito), styNormal)
        scheda_numero = Paragraph(
            "<b>N° Form</b><br/>" + str(self.scheda_numero), styNormal)

        # 2 row
        collocazione = Paragraph("<b>Place</b><br/>" + str(self.collocazione),
                                 styNormal)

        # 3 row
        materiale = Paragraph("<b>Material</b><br/>" + self.materiale,
                              styNormal)

        # 4 row
        oggetto = Paragraph("<b>Object</b><br/>" + str(self.oggetto),
                            styNormal)

        # 5 row
        tipologia = Paragraph("<b>Typology</b><br/>" + self.tipologia,
                              styNormal)

        # 6 row
        d_letto_posa = Paragraph(
            "<b>D (bed pose)</b><br/>" + self.d_letto_posa, styNormal)

        # 7 row
        d_letto_attesa = Paragraph(
            "<b>D (waiting bed)</b><br/>" + self.d_letto_attesa, styNormal)

        # 8 row
        toro = Paragraph("<b>Toro</b><br/>" + self.toro, styNormal)

        # 9 row
        spessore = Paragraph("<b>Thikness</b><br/>" + self.spessore, styNormal)

        # 10 row
        lunghezza = Paragraph("<b>Weight</b><br/>" + self.lunghezza, styNormal)

        # 11 row
        larghezza = Paragraph("<b>Lenght</b><br/>" + self.larghezza, styNormal)

        # 12 row
        h = Paragraph("<b>h</b><br/>" + self.h, styNormal)

        # 13row
        lavorazione_e_stato_di_conservazione = Paragraph(
            "<b>Lavorazione e stato di conservazione</b><br/>" +
            self.lavorazione_e_stato_di_conservazione, styNormal)

        # 14 row
        confronti = Paragraph("<b>Comparision</b><br/>" + self.confronti,
                              styNormal)

        # 15 row
        cronologia = Paragraph("<b>Chronology</b><br/>" + self.cronologia,
                               styNormal)

        # 16 row
        compilatore = Paragraph("<b>Filler</b><br/>" + self.compilatore,
                                styNormal)

        # 17 row
        descrizione = ''
        try:
            descrizione = Paragraph(
                "<b>Description</b><br/>" + self.descrizione, styDescrizione)
        except:
            pass

            # 18 row
        bibliografia = ''
        if len(eval(self.bibliografia)) > 0:
            for i in eval(self.bibliografia):  # gigi
                if bibliografia == '':
                    try:
                        bibliografia += (
                            "<b>Autor: %s, Year: %s, Title: %s, Pag.: %s, Fig.: %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]), str(
                            i[3]), str(i[4]))
                    except:
                        pass
                else:
                    try:
                        bibliografia += (
                            "<b>Autor: %s, Year: %s, Title: %s, Pag.: %s, Fig.: %s"
                        ) % (str(i[0]), str(i[1]), str(i[2]), str(
                            i[3]), str(i[4]))
                    except:
                        pass

        bibliografia = Paragraph("<b>Bibliography</b><br/>" + bibliografia,
                                 styNormal)

        # schema
        cell_schema = [  # 00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                alma, '01', '02', '03', '04', '05', '06', intestazione, '08',
                '09'
            ],  # 0 row ok
            [
                sito, '01', '02', '03', '04', '05', '06', '07', scheda_numero,
                '09'
            ],  # 1 row ok
            [
                collocazione, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 2 row ok
            [materiale, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 3 row ok
            [oggetto, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 4 row ok
            [tipologia, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 5 row ok
            [
                d_letto_posa, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 6 row ok
            [
                d_letto_attesa, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 7 row ok
            [toro, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 8 row ok
            [spessore, '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 9 row ok
            [larghezza, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 10 row ok
            [lunghezza, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 11 row ok
            [h, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 12 row ok
            [
                descrizione, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 13 row ok
            [
                lavorazione_e_stato_di_conservazione, '01', '02', '03', '04',
                '05', '06', '07', '08', '09'
            ],
            # 14 row ok
            [confronti, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 15 row ok
            [cronologia, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  # 16 row ok
            [
                bibliografia, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 17 row ok
            [
                compilatore, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  # 18 row ok
        ]

        # table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            # 0 row
            ('SPAN', (0, 0), (6, 0)),  # intestazione
            ('SPAN', (7, 0), (9, 0)),  # logo

            # 1 row
            ('SPAN', (0, 1), (7, 1)),  # sito
            ('SPAN', (8, 1), (9, 1)),  # scheda numero

            # 2 row
            ('SPAN', (0, 2), (9, 2)),  # collocazione
            #                   ('VALIGN',(0,2),(9,2),'TOP'),

            # 3 row
            ('SPAN', (0, 3), (9, 3)),  # materiale

            # 4 row
            ('SPAN', (0, 4), (9, 4)),  # oggetto

            # 5row
            ('SPAN', (0, 5), (9, 5)),  # tipologia

            # 6 row
            ('SPAN', (0, 6), (9, 6)),  # d_letto_posa

            # 7 row
            ('SPAN', (0, 7), (9, 7)),  # d_letto_attesa

            # 8 row
            ('SPAN', (0, 8), (9, 8)),  # toro

            # 9 row
            ('SPAN', (0, 9), (9, 9)),  # spessore

            # 10 row
            ('SPAN', (0, 10), (9, 10)),  # larghezza

            # 11 row
            ('SPAN', (0, 11), (9, 11)),  # lunghezza

            # 12row
            ('SPAN', (0, 12), (9, 12)),  # h

            # 13 row
            ('SPAN', (0, 13), (9, 13)),  # descrizione

            # 14 row
            ('SPAN', (0, 14), (9, 14)),  # lavorazione

            # 15 row
            ('SPAN', (0, 15), (9, 15)),  # confronti

            # 16 row
            ('SPAN', (0, 16), (9, 16)),  # cronologia

            # 17 row
            ('SPAN', (0, 17), (9, 17)),  # bibliografia

            # 18 row
            ('SPAN', (0, 18), (9, 18)),  # autore scheda
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

        t = Table(cell_schema,
                  colWidths=50,
                  rowHeights=None,
                  style=table_style)

        return t
示例#37
0
    def get_story(self, doc, form_data):
        cl = self.event.checkin_lists.get(pk=form_data['list'])

        questions = list(
            Question.objects.filter(event=self.event,
                                    id__in=form_data['questions']))

        headlinestyle = self.get_style()
        headlinestyle.fontSize = 15
        headlinestyle.fontName = 'OpenSansBd'
        colwidths = [3 * mm, 8 * mm, 8 * mm] + [
            a * (doc.width - 8 * mm)
            for a in [.1, .25, (.25 if questions else .60)] +
            ([.35 / len(questions)] * len(questions) if questions else [])
        ]
        tstyledata = [
            ('VALIGN', (0, 0), (-1, 0), 'BOTTOM'),
            ('ALIGN', (2, 0), (2, 0), 'CENTER'),
            ('VALIGN', (0, 1), (-1, -1), 'TOP'),
            ('FONTNAME', (0, 0), (-1, 0), 'OpenSansBd'),
            ('ALIGN', (0, 0), (0, -1), 'CENTER'),
            ('TEXTCOLOR', (0, 0), (0, -1), '#990000'),
            ('FONTNAME', (0, 0), (0, -1), 'OpenSansBd'),
        ]

        story = [Paragraph(cl.name, headlinestyle), Spacer(1, 5 * mm)]

        tdata = [
            [
                '',
                '',
                # Translators: maximum 5 characters
                TableTextRotate(pgettext('tablehead', 'paid')),
                _('Order'),
                _('Name'),
                _('Product') + '\n' + _('Price'),
            ],
        ]

        headrowstyle = self.get_style()
        headrowstyle.fontName = 'OpenSansBd'
        for q in questions:
            txt = str(q.question)
            p = Paragraph(txt, headrowstyle)
            while p.wrap(colwidths[len(tdata[0])], 5000)[1] > 30 * mm:
                txt = txt[:len(txt) - 50] + "..."
                p = Paragraph(txt, headrowstyle)
            tdata[0].append(p)

        qs = self._get_queryset(cl, form_data)

        for op in qs:
            try:
                ian = op.order.invoice_address.name
                iac = op.order.invoice_address.company
            except:
                ian = ""
                iac = ""

            name = op.attendee_name or (op.addon_to.attendee_name
                                        if op.addon_to else '') or ian
            if iac:
                name += "<br/>" + iac

            row = [
                '!!' if op.item.checkin_attention or op.order.checkin_attention
                else '',
                CBFlowable(bool(op.last_checked_in)),
                '✘' if op.order.status != Order.STATUS_PAID else '✔',
                op.order.code,
                Paragraph(name, self.get_style()),
                Paragraph(
                    str(op.item) +
                    (" – " + str(op.variation.value) if op.variation else "") +
                    "<br/>" + ((str(op.seat) + " / ") if op.seat else "") +
                    money_filter(op.price, self.event.currency),
                    self.get_style()),
            ]
            acache = {}
            if op.addon_to:
                for a in op.addon_to.answers.all():
                    # We do not want to localize Date, Time and Datetime question answers, as those can lead
                    # to difficulties parsing the data (for example 2019-02-01 may become Février, 2019 01 in French).
                    if a.question.type in Question.UNLOCALIZED_TYPES:
                        acache[a.question_id] = a.answer
                    else:
                        acache[a.question_id] = str(a)
            for a in op.answers.all():
                # We do not want to localize Date, Time and Datetime question answers, as those can lead
                # to difficulties parsing the data (for example 2019-02-01 may become Février, 2019 01 in French).
                if a.question.type in Question.UNLOCALIZED_TYPES:
                    acache[a.question_id] = a.answer
                else:
                    acache[a.question_id] = str(a)
            for q in questions:
                txt = acache.get(q.pk, '')
                p = Paragraph(txt, self.get_style())
                while p.wrap(colwidths[len(row)], 5000)[1] > 50 * mm:
                    txt = txt[:len(txt) - 50] + "..."
                    p = Paragraph(txt, self.get_style())
                row.append(p)
            if op.order.status != Order.STATUS_PAID:
                tstyledata += [
                    ('BACKGROUND', (2, len(tdata)), (2, len(tdata)),
                     '#990000'),
                    ('TEXTCOLOR', (2, len(tdata)), (2, len(tdata)), '#ffffff'),
                    ('ALIGN', (2, len(tdata)), (2, len(tdata)), 'CENTER'),
                ]
            tdata.append(row)

        table = Table(tdata, colWidths=colwidths, repeatRows=1)
        table.setStyle(TableStyle(tstyledata))
        story.append(table)
        return story
示例#38
0
def draw_pdf(buffer, invoice):
    """ Draws the invoice """
    canvas = Canvas(buffer, pagesize=A4)
    canvas.translate(0, 29.7 * cm)
    canvas.setFont('Helvetica', 10)

    canvas.saveState()
    header_func(canvas)
    canvas.restoreState()

    canvas.saveState()
    footer_func(canvas)
    canvas.restoreState()

    canvas.saveState()
    address_func(canvas)
    canvas.restoreState()

    # Client address
    textobject = canvas.beginText(1.5 * cm, -2.5 * cm)
    if invoice.address.contact_name:
        textobject.textLine(invoice.address.contact_name)
    textobject.textLine(invoice.address.address_one)
    if invoice.address.address_two:
        textobject.textLine(invoice.address.address_two)
    textobject.textLine(invoice.address.town)
    if invoice.address.county:
        textobject.textLine(invoice.address.county)
    textobject.textLine(invoice.address.postcode)
    textobject.textLine(invoice.address.country.name)
    canvas.drawText(textobject)

    # Info
    textobject = canvas.beginText(1.5 * cm, -6.75 * cm)
    textobject.textLine(u'Invoice ID: %s' % invoice.invoice_id)
    textobject.textLine(u'Invoice Date: %s' % invoice.invoice_date.strftime('%d %b %Y'))
    textobject.textLine(u'Client: %s' % invoice.user.username)
    canvas.drawText(textobject)

    # Items
    data = [[u'Quantity', u'Description', u'Amount', u'Total'], ]
    for item in invoice.items.all():
        data.append([
            item.quantity,
            item.description,
            format_currency(item.unit_price, invoice.currency),
            format_currency(item.total(), invoice.currency)
        ])
    data.append([u'', u'', u'Total:', format_currency(invoice.total(), invoice.currency)])
    table = Table(data, colWidths=[2 * cm, 11 * cm, 3 * cm, 3 * cm])
    table.setStyle([
        ('FONT', (0, 0), (-1, -1), 'Helvetica'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),
        ('TEXTCOLOR', (0, 0), (-1, -1), (0.2, 0.2, 0.2)),
        ('GRID', (0, 0), (-1, -2), 1, (0.7, 0.7, 0.7)),
        ('GRID', (-2, -1), (-1, -1), 1, (0.7, 0.7, 0.7)),
        ('ALIGN', (-2, 0), (-1, -1), 'RIGHT'),
        ('BACKGROUND', (0, 0), (-1, 0), (0.8, 0.8, 0.8)),
    ])
    tw, th, = table.wrapOn(canvas, 15 * cm, 19 * cm)
    table.drawOn(canvas, 1 * cm, -8 * cm - th)

    canvas.showPage()
    canvas.save()
示例#39
0
    def render(self, tab):
        from reportlab.pdfgen.canvas import Canvas
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.cidfonts import UnicodeCIDFont
        pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Table, TableStyle

        stylemap = {}
        for name, style in tab.styles.items():
            stylemap[name] = style
        colormap = {
            'red': colors.red,
            'green': colors.green,
            'blue': colors.blue,
            'black': colors.black,
            'white': colors.white,
        }

        def transcolor(c):
            return colormap.get(c) or colors.black

        tabdata = []
        styles = [
            ('FONTNAME', (0, 0), (-1, -1), 'STSong-Light'),
            #             ('FONTNAME', (1, 1), (-1, -1), 'STSong-Light'),
            ('GRID', (0, 0), (-1, -1), 0.5, '#FF000000'),
            ('VALIGN', (0, 1), (-1, -1), 'MIDDLE'),
        ]
        for r in range(tab.maxRow + 1):
            cols = []
            for c in range(tab.maxCol + 1):
                cell = tab.getCellByRowCol(r, c) or {}
                if cell and cell.get('span'):
                    cols.append('')
                    continue
                value = tab.getValue(cell)  # cell.get('value')
                rowspan = cell.get('rowspan', 1)
                colspan = cell.get('colspan', 1)
                style = tab.getStyle(cell)
                if style and style not in stylemap:
                    raise Exception(u'%s not in styles' % style)
                styled = stylemap.get(style) or {}
                if isinstance(value, str):
                    value = u'%s' % value
                col = c  # + 1
                row = r  # + 1
                cix = (r, c)

                styles += [
                    ('FONTSIZE', cix, (0, 0),
                     int(styled.get('fontSize', 12) * self.fontSizeRatio)),
                    ('ALIGN', cix, (0, 0), styled.get('align',
                                                      'left').upper()),
                    ('TEXTCOLOR', cix, (0, 0),
                     transcolor(styled.get('color', 'black')))
                ]
                if rowspan > 1 or colspan > 1:
                    styles.append(('SPAN', (col, row), (col + colspan - 1,
                                                        row + rowspan - 1)))
                cols.append(value)
            tabdata.append(cols)
        widths = [20 for _ in range(len(tab.widths))]
        for col, width in tab.widths.items():
            if len(widths) > col >= 0 and width > 0:
                widths[col] = int(width * self.widthRatio)
        pdftab = Table(tabdata, colWidths=(widths or None))
        pdftab.setStyle(TableStyle(styles))
        return pdftab
示例#40
0
def operacion():
    if opt.get() == 0:
        showinfo('Operación', "Generar Análisis")
        analisis_arrendatarios.pdf_analisis_arre()
    else:
        showinfo('Operación', "Generar Facturación")
        for c in dato1:
            canon = c[0]
            subtotal = c[1]
            iva = c[2]
            retef = c[3]
            ivajuridi = c[4]
            retei = c[5]
            resolucion = c[6]

        doc = SimpleDocTemplate(
            "facturas/factura_auto_inquilino.pdf",
            pagesize=(595.27, 400.00),
            #rightMargin=72,leftMargin=72,
            topMargin=10,
            bottomMargin=0)
        #pagesize = (595.27,841.89)
        story = []

        for i in dato2:
            nit = i[0]
            prop = i[1]
            folder = i[2]
            inm = i[3]
            loc = i[4]
            renta = i[5]
            tel = i[6]
            cc = i[7]
            arrend = i[8]
            tipo = i[9]
            contri = i[10]
            #SI ARREND ES NATURAL(1)
            if tipo == 1:
                tipo = 0
            #SI ARREND ES JURÍDICO(2)
            if tipo == 2:
                tipo = renta * ivajuridi / 100

            total = renta + tipo

            tiempo = datetime.date.today()
            anio = time.strftime("%Y")
            mes = time.strftime("%B")

            #-------------------------------------------- CABECERA DEL DOCUMENTO

            #VARIABLES
            logo = Image("img/logo.gif", width=150, height=45)  #LOGO
            logo.hAlign = 'LEFT'  #Posicion de la img en la hoja

            info = Paragraph(
                '''<para align=center leading=8><font size=6>CALLE 11A N°42-68 LOC,195<br/>
                                TELEFONO: 3110513 FAX:2664154<br/>
                                AA.75105 ED. EL DORADO<br/>
                                AFILIADO A FENALCO<br/>
                                M.A.V.U N°000078</font></para>''',
                styleSheet["BodyText"])

            tipoDoc = Paragraph(
                '''<para align=right><b>FACTURA DE VENTA<br/>N°</b></para>''',
                styleSheet["BodyText"])

            #TABLA 1
            tabla1 = Table([[logo, info, tipoDoc]],
                           colWidths=160,
                           rowHeights=None)
            tabla1.setStyle([
                ('VALIGN', (1, 0), (2, 0), 'TOP'),
                ('ALIGN', (2, 0), (2, 0), 'RIGHT')  #ALINEAR A LA DER
            ])

            story.append(
                tabla1)  #Construye la tabla 't' definida anteriormente
            story.append(Spacer(
                0, -10))  #Espacio del salto de línea con el siguiente Ejemplo

            #-------------------------------------------- DATOS GENERALES DEL DOCUMENTO

            #VARIABLES
            inquilino = Paragraph(
                '''<font size=6><b>Nombre Arrendatario:</b><br/></font>%s''' %
                arrend, styleSheet["BodyText"])
            docID = Paragraph(
                '''<font size=6><b>CC/Nit: </b></font>       %s''' % nit,
                styleSheet["BodyText"])
            locImn = Paragraph(
                '''<font size=6><b>Dirección Inmueble:</b><br/></font>%s''' %
                loc, styleSheet["BodyText"])
            telefono = Paragraph(
                '''<font size=6><b>Teléfono:</b><br/></font>%s''' % tel,
                styleSheet["BodyText"])
            IDpropietario = Paragraph(
                '''<font size=6><b>CC/Nit:</b><br/></font>%s''' % cc,
                styleSheet["BodyText"])
            propietario = Paragraph(
                '''<font size=6><b>Propietario: </b></font>%s''' % prop,
                styleSheet["BodyText"])
            fechaFormato = Paragraph(
                '''<para align=center fontSize=6>Día Mes Año</para>''',
                styleSheet["BodyText"])
            hoy = time.strftime("%d/%m/%Y")
            fecha = Paragraph(
                '''<para align=center spaceBefore=0>%s</para>''' % hoy,
                styleSheet["BodyText"])
            codigoImn = Paragraph(
                '''<font size=6><b>Código Inmueble:</b><br/></font>%s''' % inm,
                styleSheet["BodyText"])

            #TABLA 2
            datos = [[inquilino, '', '', '', '', [fechaFormato, fecha]],
                     [docID, '', '', propietario, '', ''],
                     [locImn, '', telefono, IDpropietario, '', codigoImn]]

            tabla2 = Table(
                datos,
                style=[
                    ('BOX', (0, 0), (2, 2), 0.5, colors.black),
                    ('VALIGN', (0, 0), (2, 0), 'TOP'),
                    (
                        'SPAN', (0, 0), (2, 0)
                    ),  #Combinar 3 filas (col0,row0) hasta (col2,row0) Arrendatario #0
                    ('SPAN', (0, 1), (2, 1)),  #Combinar 3 filas CC/Nit #1
                    ('SPAN', (0, 2), (1, 2)),  #Combinar 2 filas Dirección #2
                    ('SPAN', (3, 1),
                     (5, 1)),  #Combinar 3 filas Nombre Propietario #
                    ('SPAN', (3, 2),
                     (4, 2)),  #Combinar 2 filas CC/Nit Propietario #
                    ('GRID', (3, 1), (4, 2), 0.5, colors.black),
                    ('GRID', (5, 0), (5, 2), 0.5, colors.black)
                ],
                colWidths=80,
                rowHeights=None)

            #Constructor y espaciado
            story.append(Spacer(
                0, 15))  #Espacio del salto de línea con el siguiente Ejemplo
            story.append(
                tabla2)  #Construye la tabla 't' definida anteriormente

            #-------------------------------------------- DETALLES DEL DOCUMENTO

            #VARIABLES
            desc = Paragraph(
                '''<para align=center><b>DESCRIPCION</b></para>''',
                styleSheet["BodyText"])
            vlr = Paragraph('''<para align=center><b>VALOR</b></para>''',
                            styleSheet["BodyText"])
            concepto = Paragraph(
                '''Valor Arrendamiento Mes: %s/%s''' % (mes, anio),
                styleSheet["BodyText"])

            resol = "Resolucion Dian N°110000658514 de Diciembre de 2015 Consectivo Facturacion 33001 al 36000. P"

            #TABLA 3
            data = [
                [desc, '', vlr],  #0
                [concepto, '', renta],  #1
                ['', '', ''],  #2
                ['', '', ''],  #3
                ['', '', ''],  #4
                ['', '', ''],  #5
                ['', '', ''],  #6
                ['Observaciones', 'SUBTOTAL', renta],  #7
                ['', 'IVA', tipo],  #8
                [resolucion, 'TOTAL', total]
            ]  #9

            #Formato de la tabla
            tabla3 = Table(
                data,
                style=[
                    ('GRID', (0, 0), (2, 0), 0.5,
                     colors.grey),  #Color regilla de DESCRIPCION & VALOR
                    (
                        'BOX', (2, 1), (2, 9), 0.5, colors.grey
                    ),  #Color & grosor de la tabla o marco externo de los VALORES
                    ('BACKGROUND', (0, 0), (2, 0),
                     colors.pink),  #Color de fondo de DESCRIPCION & VALOR #0
                    ('SPAN', (0, 0), (1, 0)),  #Combinar filas DESCRIPCION #0
                    (
                        'BOX', (0, 1), (2, 6), 0.5, colors.grey
                    ),  #Color & grosor de la tabla o marco externo de los DETALLES
                    ('ALIGN', (2, 1), (2, 1), 'RIGHT'),  #Centrar renta #1
                    ('ALIGN', (2, 7), (2, 7), 'RIGHT'),  #Centrar renta #7
                    ('ALIGN', (2, 8), (2, 8), 'RIGHT'),  #Centrar tipo #8
                    ('ALIGN', (2, 9), (2, 9), 'RIGHT'),  #Centrar total #9
                    #('ALIGN', (2,9), (2,9), 'CENTER'),#Centrar total #9
                    ('SPAN', (0, 1), (1, 1)),  #Combinar filas de Detalle #1
                    ('SPAN', (0, 2), (1, 2)),  #Combinar filas de Detalle #2
                    ('SPAN', (0, 3), (1, 3)),  #Combinar filas de Detalle #3
                    ('SPAN', (0, 4), (1, 4)),  #Combinar filas de Detalle #4
                    ('SPAN', (0, 5), (1, 5)),  #Combinar filas de Detalle #5
                    ('SPAN', (0, 6), (1, 6)),  #Combinar filas de Detalle #6
                    ('GRID', (1, 7), (2, 8), 0.5,
                     colors.grey),  #Color regilla de SUBTOTAL, IVA, TOTAL
                    (
                        'BOX', (0, 7), (0, 9), 0.5, colors.grey
                    ),  #Color & grosor de la tabla o marco externo de los OBSERVACIONES Y RESOLUCION
                    ('FONTSIZE', (0, 9), (0, 9), 7),  #Tamaño de la Resolucion
                    ('BACKGROUND', (1, 9), (1, 9),
                     colors.black),  #Color de fondo de TOTAL
                    ('TEXTCOLOR', (1, 9), (1, 9),
                     colors.white),  #Color de letra de TOTAL
                    ('BACKGROUND', (2, 9), (2, 9), colors.grey
                     )  #Color de fondo de VALOR TOTAL
                ],
                colWidths=[300, 80, 100],
                rowHeights=None)

            story.append(Spacer(
                0, 15))  #Espacio del salto de línea con el siguiente Ejemplo
            story.append(
                tabla3)  #Construye la tabla 't' definida anteriormente

            #-------------------------------------------- FIN PDF

        doc.build(story)  #Constructor del documento

        if sys.platform == 'linux2':
            os.system("xdg-open ~/SBIENES/facturas/factura_auto_inquilino.pdf"
                      )  #DEBIAN
        elif sys.platform == 'linux2':
            os.system("/usr/bin/gnome-open facturas/factura_auto_inquilino.pdf"
                      )  #UBUNTU
        else:
            os.startfile(
                "F:/SBIENES/facturas/factura_auto_inquilino.pdf")  #WINDOWS
示例#41
0
    def gen_pdf(self,family_data,variant_data,project_id,phenotype_entry_counts,family_statuses):
      '''
        Generate a PDF report
      '''
      story=[]
      doc = SimpleDocTemplate("test.pdf",
                              pagesize=letter,
                              rightMargin=72,
                              leftMargin=72,
                              topMargin=72,
                              bottomMargin=18)

      #styling
      styles=getSampleStyleSheet()
      styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
      styles.add(ParagraphStyle(name='main_title_text', fontName ='Helvetica',fontSize=18, backColor = colors.white, textColor=colors.black, alignment=TA_LEFT))
      styles.add(ParagraphStyle(name='sub_title_text', fontName ='Helvetica',fontSize=16, backColor = colors.white, textColor=colors.black, alignment=TA_LEFT))
      styles.add(ParagraphStyle(name='section_title_text', fontName ='Helvetica',fontSize=12, backColor = colors.white, textColor=colors.black, alignment=TA_LEFT))
      styles.add(ParagraphStyle(name='regular_text', fontName ='Helvetica',fontSize=9, backColor = colors.white, textColor=colors.black, alignment=TA_LEFT))
      
      story.append(Spacer(1, 12))
      
       #add main title
      para = 'The Center For Mendelian Genomics'
      story.append(Paragraph(para, styles["main_title_text"])) 
      story.append(Spacer(width=1, height=20))
      
      #add title
      para = 'Project Report for %s' % project_id
      story.append(Paragraph(para, styles["sub_title_text"])) 
      story.append(Spacer(1, 12))
      
      #add time stamp
      t = time.time()
      tstamp = datetime.datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
      para = 'Report generated at: %s' % tstamp
      story.append(Paragraph(para, styles["regular_text"])) 
      para = 'Tool version: %s' % self.__VERSION__
      story.append(Paragraph(para, styles["regular_text"])) 
      story.append(Spacer(1, 12))
      
      #Sections
      #--------Causal variants
      para = 'Causal Variants found in project'
      story.append(Paragraph(para, styles["section_title_text"]))       
      story.append(Spacer(1, 12))
      
      table_data = [['Family ID','Gene symbol']]
      for i,fam in enumerate(family_data):
        for gene_id,gene_data in fam['extras']['genes'].iteritems():
          table_data.append([i,gene_data['symbol']])
      t=Table(table_data,hAlign='LEFT')
      t.setStyle(TableStyle([('BACKGROUND',(0,0),(1,0),colors.gray),
                       ('TEXTCOLOR',(0,0),(1,0),colors.white)]))
      story.append(t)     
      story.append(Spacer(1, 12))
      #--------Individuals
      para = 'Summary of individuals in project'
      story.append(Paragraph(para, styles["section_title_text"]))       
      story.append(Spacer(1, 12))
      
      table_data=[['Family ID','Status','Individual ID','Gender','Affected status','Phenotypes entry count']]
      
      for family_id,variant_data in variant_data.iteritems():
        for individual in variant_data['individuals']:
          table_data.append([variant_data['family_id'],
                             family_statuses[variant_data['family_id']],
                             individual['indiv_id'],
                             individual['gender'],
                             individual['affected'],
                             phenotype_entry_counts[individual['indiv_id']]['count']
                             ])
      t=Table(table_data,hAlign='LEFT')
      t.setStyle(TableStyle([('BACKGROUND',(0,0),(5,0),colors.gray),
                       ('TEXTCOLOR',(0,0),(5,0),colors.white)]))
      
      story.append(t)  
      doc.build(story)
示例#42
0
    "figs": 1,
    "apples": 2,
    "durians": 3,
    "bananas": 5,
    "cherries": 8,
    "grapes": 13
}

# for pdf tables data must be in a list of lists
table_data = []
for k, v in fruit.items():
    table_data.append([k, v])

report_title = Paragraph("A Complete Inventory of My Fruit", styles["h1"])
table_style = [('GRID', (0, 0), (-1, -1), 1, colors.black)]
report_table = Table(data=table_data, style=table_style, hAlign="LEFT")

# for pie charts we need two lists, one for data, one for labels
#report_pie = Pie(width=3*inch, height=3*inch)
report_pie = Pie(width=3 * inch, height=3 * inch)
report_pie.data = []
report_pie.labels = []
for fruit_name in sorted(fruit):
    report_pie.data.append(fruit[fruit_name])
    report_pie.labels.append(fruit_name)

report_chart = Drawing()
report_chart.add(report_pie)

report.build([report_title, report_table, report_chart])
示例#43
0
    def Imprimer(self, event=None):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]

        # Initialisation du PDF
        PAGE_HEIGHT = defaultPageSize[1]
        PAGE_WIDTH = defaultPageSize[0]
        nomDoc = FonctionsPerso.GenerationNomDoc("LISTE_ATTENTE", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30)
        story = []

        largeurContenu = 520

        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ((420, 100))
            dateDuJour = DateEngFr(str(datetime.date.today()))
            dataTableau.append((_(u"Liste d'attente"), _(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, 20))

        # Insère un header
        Header()

        # Un tableau par date
        for date, listeGroupes in self.listeImpression:

            dataTableau = []
            largeursColonnes = [180, 180, 160]

            dataTableau.append((date, "", ""))

            # Groupes
            listeIndexGroupes = []
            indexLigne = 0
            for nomGroupe, listeIndividus in listeGroupes:
                indexLigne += 1
                listeIndexGroupes.append(indexLigne)

                dataTableau.append((nomGroupe, "", ""))

                # Individus
                for dictIndividu in listeIndividus:
                    placeDispo = dictIndividu["placeDispo"]
                    texteIndividu = dictIndividu["texteIndividu"]
                    texteUnites = dictIndividu["texteUnites"]
                    texteDateSaisie = _(
                        u"Saisie le %s") % dictIndividu["texteDateSaisie"]
                    dataTableau.append((
                        texteIndividu, texteUnites,
                        texteDateSaisie))  # Paragraph(memo_journee, paraStyle)
                    indexLigne += 1

            couleurFond = (0.8, 0.8, 1)  # Vert -> (0.5, 1, 0.2)

            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, 1), (-1, -1), 'CENTRE'),  # Centre les cases
                ('ALIGN', (0, 1), (-1, 1),
                 'CENTRE'),  # Ligne de labels colonne alignée au centre
                ('FONT', (0, 1), (-1, 1), "Helvetica", 6
                 ),  # Donne la police de caract. + taille de police des labels
                (
                    'SPAN', (0, 0), (-1, 0)
                ),  # Fusionne les lignes du haut pour faire le titre du groupe
                (
                    'FONT', (0, 0), (0, 0), "Helvetica-Bold", 10
                ),  # Donne la police de caract. + taille de police du titre de groupe
                ('BACKGROUND', (0, 0), (-1, 0),
                 couleurFond),  # Donne la couleur de fond du titre de groupe
            ]

            # Formatage des lignes "Activités"
            for indexGroupe in listeIndexGroupes:
                listeStyles.append(
                    ('SPAN', (0, indexGroupe), (-1, indexGroupe)))
                listeStyles.append(('FONT', (0, indexGroupe),
                                    (-1, indexGroupe), "Helvetica-Bold", 7))
                listeStyles.append(
                    ('ALIGN', (0, indexGroupe), (-1, indexGroupe), 'LEFT'))

            # 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)
示例#44
0
文件: views.py 项目: aljazv/trafika
def natisni_narocilnica(request, narocilo):

    narocila_izdelka = narocilo.narocila_izdelka.all()

    uporabnik = narocilo.uporabnik
    story = []

    formatted_time = datetime.date.today()
    formatted_time = str(formatted_time)
    tabela = formatted_time.split("-")
    formatted_time = tabela[2] + "." + tabela[1] + "." + tabela[0]

    #GretaSansStd-Bold
    #GretaSansStd-Regular

    styles = getSampleStyleSheet()
    p0 = ParagraphStyle('MyNormal',
                        parent=styles['Normal'],
                        alignment=TA_RIGHT)
    p1 = styles.add(
        ParagraphStyle(name='Center',
                       fontName='GretaSansStd-Regular',
                       alignment=TA_CENTER))
    p2 = styles.add(
        ParagraphStyle(name='Right',
                       fontName='GretaSansStd-Regular',
                       alignment=TA_RIGHT))
    p3 = styles.add(
        ParagraphStyle(name='Left',
                       fontName='GretaSansStd-Regular',
                       alignment=TA_LEFT))
    p4 = styles.add(
        ParagraphStyle(name='Line_Data',
                       fontName='GretaSansStd-Regular',
                       alignment=TA_LEFT,
                       fontSize=9,
                       leading=14))
    p5 = styles.add(
        ParagraphStyle(name='Line_Data_Small',
                       fontName='GretaSansStd-Regular',
                       alignment=TA_LEFT,
                       fontSize=7,
                       leading=14))
    p6 = styles.add(
        ParagraphStyle(name='Line_Data_Large',
                       fontName='GretaSansStd-Regular',
                       alignment=TA_LEFT,
                       fontSize=12,
                       leading=14))
    p7 = styles.add(
        ParagraphStyle(name='Line_Data_Largest',
                       fontName='GretaSansStd-Regular',
                       alignment=TA_LEFT,
                       fontSize=20,
                       leading=14))
    p8 = styles.add(
        ParagraphStyle(name='Line_Label',
                       fontName='GretaSansStd-Bold',
                       font='GretaSansStd-Bold',
                       fontSize=7,
                       leading=14,
                       alignment=TA_LEFT))
    p9 = styles.add(
        ParagraphStyle(name='Line_Label_Center',
                       fontName='GretaSansStd-Bold',
                       font='GretaSansStd-Bold',
                       fontSize=14,
                       alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name='sidarta_label',
                       fontName='GretaSansStd-Bold',
                       font='GretaSansStd-Bold',
                       fontSize=17,
                       leading=14,
                       alignment=TA_LEFT))

    width = 6 * cm
    logo_path = "media/gallery/logo.jpg"
    img = utils.ImageReader(logo_path)
    iw, ih = img.getSize()
    aspect = ih / float(iw)
    logo_slika = Image(logo_path, width=width, height=(width * aspect))

    data1 = [[
        Paragraph('NAROČILNICA', styles["Line_Data_Largest"]),
        Paragraph('', styles["Line_Label"]), logo_slika
    ]]

    t1 = Table(data1,
               colWidths=(10 * cm, 1.81 * cm, 8.49 * cm),
               rowHeights=(0.5 * cm))
    t1.setStyle(TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
    ]))
    story.append(t1)

    story.append(Spacer(1, 30))

    #
    podjetje = uporabnik.podjetje
    prodajno_mesto = uporabnik.prodajno_mesto
    podjetje_glavno = PodjetjeGlavno.objects.get(pk=1)

    podjetje_podatki = '%s <br/> %s <br/> %s, %s <br/> %s <br/> ' % (
        podjetje.ime, podjetje.naslov, podjetje.postna_stevilka,
        podjetje.obcina, podjetje.davcna_stevilka)

    prodajno_mesto_podatki = '%s <br/>%s <br/>%s %s <br/>' % (
        prodajno_mesto.ime, prodajno_mesto.naslov,
        prodajno_mesto.postna_stevilka, prodajno_mesto.obcina)

    sidarta = '%s <br/>%s <br/>%s <br/> %s' % (
        podjetje_glavno.naslov, podjetje_glavno.tel_fax, podjetje_glavno.email,
        podjetje_glavno.spletna_stran)

    prodajno_mesto.kontaktna_oseba, prodajno_mesto.telefon

    datum = narocilo.datum.strftime("%d.%m.%Y, %H:%M")

    data1 = [  #1 vrstica
        [
            Paragraph('Prodajno mesto/naslov dostave', styles["Line_Label"]),
            Paragraph('Številka naročilnice', styles["Line_Label"]),
            Paragraph('', styles["sidarta_label"])
        ],
        #2
        [
            Paragraph(prodajno_mesto_podatki, styles["Line_Data_Large"]),
            Paragraph(narocilo.st_narocila, styles["Line_Data_Large"]),
            Paragraph(sidarta, styles["Line_Data_Small"])
        ],
        #3
        [
            Paragraph('', styles["Line_Label"]),
            Paragraph('Datum naročila', styles["Line_Label"]),
            Paragraph('', styles["Line_Label"])
        ],
        #4
        [
            Paragraph('', styles["Line_Data_Large"]),
            Paragraph(datum, styles["Line_Data_Large"]),
            Paragraph('', styles["Line_Data_Large"])
        ],
        #5
        [
            Paragraph('Kontaktna oseba', styles["Line_Label"]),
            Paragraph('', styles["Line_Label"]),
            Paragraph('Potnik', styles["Line_Label"])
        ],
        #6
        [
            Paragraph(prodajno_mesto.kontaktna_oseba,
                      styles["Line_Data_Large"]),
            Paragraph('', styles["Line_Data_Large"]),
            Paragraph(
                narocilo.potnik.uporabnik.user.first_name + " " +
                narocilo.potnik.uporabnik.user.last_name,
                styles["Line_Data_Large"])
        ],
        #7
        [
            Paragraph('Telefon', styles["Line_Label"]),
            Paragraph('', styles["Line_Label"]),
            Paragraph('Telefon', styles["Line_Label"])
        ],
        #8
        [
            Paragraph(prodajno_mesto.telefon, styles["Line_Data_Large"]),
            Paragraph('', styles["Line_Data_Large"]),
            Paragraph(narocilo.potnik.telefon, styles["Line_Data_Large"])
        ],
        #9
        [
            Paragraph('Sedež podjetja', styles["Line_Label"]),
            Paragraph('', styles["Line_Label"]),
            Paragraph('mail', styles["Line_Label"])
        ],
        #10
        [
            Paragraph(podjetje_podatki, styles["Line_Data"]),
            Paragraph('', styles["Line_Data_Large"]),
            Paragraph(narocilo.potnik.email, styles["Line_Data_Large"])
        ],
        #11
        [
            Paragraph('', styles["Line_Label"]),
            Paragraph('', styles["Line_Label"]),
            Paragraph('', styles["Line_Label"])
        ],
        #12
        [
            Paragraph('', styles["Line_Data_Large"]),
            Paragraph('', styles["Line_Data_Large"]),
            Paragraph('', styles["Line_Data_Large"])
        ]
    ]

    t1 = Table(data1,
               colWidths=(6.5 * cm),
               rowHeights=(
                   0.5 * cm,
                   1.1 * cm,
                   0.5 * cm,
                   1 * cm,
                   0.5 * cm,
                   1 * cm,
                   0.5 * cm,
                   1 * cm,
                   0.5 * cm,
                   1 * cm,
                   0.5 * cm,
                   1 * cm,
               ),
               hAlign='LEFT')

    t1.setStyle(
        TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                    ('VALIGN', (2, 1), (2, 1), 'MIDDLE'),
                    ('SPAN', (0, 1), (0, 3)), ('SPAN', (2, 1), (2, 3)),
                    ('SPAN', (0, 9), (0, 11)),
                    ('LINEBELOW', (2, 3), (2, 3), 2, colors.black)]))
    story.append(t1)

    #
    story.append(Spacer(1, 20))

    #
    data1 = [[
        Paragraph('#', styles["Line_Label"]),
        Paragraph('IME IZDELKA', styles["Line_Label"]),
        Paragraph('SLIKA', styles["Line_Label"]),
        Paragraph('KODA IZDELKA', styles["Line_Label"]),
        Paragraph('VRSTA IZDELKA', styles["Line_Label"]),
        Paragraph('KOLIČINA', styles["Line_Label"]),
        Paragraph('', styles["Line_Label"])
    ]]

    t1 = Table(data1,
               colWidths=(1 * cm, 3.6 * cm, 4.75 * cm, 5 * cm, 3 * cm,
                          1.6 * cm, 0.7 * cm))
    t1.setStyle(
        TableStyle([('LINEBELOW', (0, 0), (-1, -1), 0.25, colors.black)]))
    story.append(t1)
    #
    d = Drawing(15, 15)
    d.add(
        Rect(0,
             0,
             15,
             15,
             strokeColor=colors.black,
             fillColor=colors.white,
             strokeWidth=1))

    for i, narocilo_izdelka in enumerate(narocila_izdelka):
        iteracija = str(i + 1) + "."
        img = utils.ImageReader(narocilo_izdelka.izdelek.image_thumbnail)
        iw, ih = img.getSize()
        aspect = ih / float(iw)

        im = Image(narocilo_izdelka.izdelek.image_thumbnail, 2 * cm,
                   2 * cm * aspect)

        data1 = [[
            Paragraph(iteracija, styles["Line_Data"]),
            Paragraph(narocilo_izdelka.izdelek.ime, styles["Line_Data"]), im,
            Paragraph(narocilo_izdelka.izdelek.koda, styles["Line_Data"]),
            Paragraph(narocilo_izdelka.izdelek.skupina_izdelkov.ime,
                      styles["Line_Data"]),
            Paragraph(str(narocilo_izdelka.kolicina), styles["Line_Data"]), d
        ]]

        t1 = Table(data1,
                   colWidths=(1 * cm, 3.6 * cm, 4.75 * cm, 5 * cm, 3 * cm,
                              1.6 * cm, 0.6 * cm))
        t1.setStyle(
            TableStyle([('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ('LINEBELOW', (0, 0), (-1, -1), 0.25, colors.black)]))
        story.append(t1)

    return story
示例#45
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
def generate_certificate_of_service(sample_data):
    buff = cStringIO.StringIO()
    doc = SignatureDocTemplate(buff, pagesize=letter)
    f = Frame(gutters[0],
              gutters[2],
              usable_width,
              usable_height,
              showBoundary=0)
    story = [
        Table(
            [[
                Image("brookhaven.jpg", 24 * mm, 14 * mm),
                Table(
                    [
                        [
                            Paragraph(
                                """
                                    <b>BROOKHAVEN MUNICIPAL COURT </b> <br />
                                    2665 BUFORD HWY, BROOKHAVEN, GA 30324 <br />
                                    Phone: 404-637-660 <br />
                                    Fax: (404) 671-3410
                                    """,
                                extend_style(styles["rc-doc-header-info"]),
                            ),
                        ],
                        [None],
                        [None],
                        [
                            Paragraph(
                                """
                                    <b>CERTIFICATE OF SERVICE</b> <br/>
                                    """,
                                styles["rc-doc-header-fda"],
                            )
                        ],
                        [None],
                        [
                            Paragraph(
                                """
                                    STATE OF GEORGIA, DEKALB COUNTY <br />
                                    """,
                                extend_style(styles["rc-doc-sub-header"]),
                            )
                        ],
                    ],
                    style=extend_table_style(
                        styles["rc-main-table"],
                        [("VALIGN", (0, 0), (-1, -1), "TOP")],
                    ),
                ),
                Paragraph(
                    """
                        """,
                    extend_style(styles["rc-doc-sub-header"],
                                 alignment=TA_RIGHT,
                                 fontSize=9),
                ),
            ]],
            style=extend_table_style(
                styles["rc-main-table"],
                [
                    ("VALIGN", (0, 0), (-1, -1), "TOP"),
                    ("TOPPADDING", (0, 0), (0, 0), 12 * mm),
                    ("TOPPADDING", (2, 0), (0, 0), 1.2 * mm),
                ],
            ),
            colWidths=(45 * mm, 108 * mm, 40 * mm),
        ),
        Table(
            [
                [None],
                [None],
                [
                    Paragraph(
                        """
                        <b>
                        CITY OF BROOKHAVEN <br/>
                        VS. <br/>
                        """ + sample_data["person"] + "</b>",
                        styles["rc-aawp-main-header"],
                    ),
                    None,
                    Paragraph(
                        """
                        <br/>
                        <b>Case Number:
                        """ + sample_data["case_number"] + """
                        </b>
                        """,
                        styles["rc-doc-sub-header"],
                    ),
                ],
                [None],
                [None],
                [None],
            ],
            style=extend_table_style(styles["rc-main-table"],
                                     [("VALIGN", (0, 0), (-1, -1), "TOP")]),
            colWidths=(60 * mm, 50 * mm, 60 * mm),
        ),
        Paragraph(
            """
            CERTIFICATE OF SERVICE <br/>
            OF CLERK'S OFFICE TRANSMITTAL TO THE COURT APPOINTED ATTORNEY <br/>
            """,
            style=styles["rc-doc-content-header-fda"],
        ),
        Spacer(0, 6 * mm),
        Paragraph(
            "This is to certify that I have this day served by the attorney appointed by the court in the "
            "above-styled case with a true and correct copy of the document(s) checked below:",
            style=styles["rc-aawp-main-content"],
        ),
        Spacer(0, 6 * mm),
        Table([[
            XBox(10, sample_data["by_deposit"]),
            None,
            Paragraph(
                "by depositing same in the U.S.Mail, properly addressed and with sufficient postage affixed to "
                "insure delivery or ",
                style=styles["rc-aawp-main-content"]),
        ], [None],
               [
                   XBox(10, sample_data["by_email"]),
                   None,
                   Paragraph("by email provided by the appointed attorney.",
                             style=styles["rc-aawp-main-content"]),
               ]],
              style=extend_table_style(styles["rc-main-table"],
                                       [("VALIGN", (0, 0), (-1, -1), "TOP")]),
              colWidths=(0 * mm, 6 * mm, 194 * mm)),
        Spacer(0, 12 * mm),
        Table(
            [
                [
                    XBox(10, sample_data["check_box_a"]),
                    None,
                    Paragraph("a. Copy of Citation(s)",
                              style=styles["rc-aawp-main-content"]),
                ],
                [None],
                [
                    XBox(10, sample_data["check_box_b"]),
                    None,
                    Paragraph(
                        "b. List of Witnesses - [AS CONTAINED IN ATTACHED (PORTION OF) INCIDENT AND/OR ACCIDENT REPORT "
                        "& Scientific Reports)",
                        style=styles["rc-aawp-main-content"],
                    ),
                ],
                [None],
                [
                    XBox(10, sample_data["check_box_c"]),
                    None,
                    Paragraph(
                        "c. Defendant's Oral Statements - [AS CONTAINED IN ATTACHED (PORTION OF) INCIDENT AND/OR "
                        "ACCIDENT REPORT",
                        style=styles["rc-aawp-main-content"],
                    ),
                ],
                [None],
                [
                    XBox(10, sample_data["check_box_d"]),
                    None,
                    Paragraph(
                        "d. Defendant's Written Statements - [ATTACHED][N/A]",
                        style=styles["rc-aawp-main-content"],
                    ),
                ],
                [None],
                [
                    XBox(10, sample_data["check_box_e"]),
                    None,
                    Paragraph(
                        "e. Written Scientific Reports - Intox or Division of Forensic Science Report",
                        style=styles["rc-aawp-main-content"],
                    ),
                ],
                [None],
                [
                    XBox(10, sample_data["check_box_f"]),
                    None,
                    Paragraph(
                        "f. Form for request of video if applicable",
                        style=styles["rc-aawp-main-content"],
                    ),
                ],
            ],
            style=extend_table_style(styles["rc-main-table"],
                                     [("VALIGN", (0, 0), (-1, -1), "TOP")]),
            colWidths=(0 * mm, 6 * mm, 194 * mm),
        ),
        Spacer(0, 10 * mm),
        Paragraph("The day of " + sample_data["date"].strftime("%m/%d/%Y"),
                  style=styles["rc-aawp-main-content"]),
        Spacer(0, 12 * mm),
        Paragraph("______________________________________",
                  style=styles["rc-doc-signature"]),
        Spacer(0, 3 * mm),
        Paragraph("Clerk / Deputy Court Clerk",
                  style=styles["rc-doc-signature"]),
    ]

    main_template = PageTemplate(id="main_template", frames=[f])
    doc.addPageTemplates([main_template])
    doc.build(story, canvasmaker=PageNumCanvas)
    del doc

    buff.seek(0)
    return buff
示例#47
0
pdfReportPages = "C:\\Temp\\test.pdf"
doc = SimpleDocTemplate(pdfReportPages, pagesize=A4)

# container for the "Flowable" objects
elements = []
styles=getSampleStyleSheet()
styleN = styles["Normal"]

# Make heading for each column and start data list
column1Heading = "COLUMN ONE HEADING"
column2Heading = "COLUMN TWO HEADING"
# Assemble data for each column using simple loop to append it into data list
data = [[column1Heading,column2Heading]]
for i in range(1,100):
    data.append([str(i),str(i)])

tableThatSplitsOverPages = Table(data, [6 * cm, 6 * cm], 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),
                       ('BOX',(0,0),(-1,-1),1,colors.black),
                       ('BOX',(0,0),(0,-1),1,colors.black)])
tblStyle.add('BACKGROUND',(0,0),(1,0),colors.lightblue)
tblStyle.add('BACKGROUND',(0,1),(-1,-1),colors.white)
tableThatSplitsOverPages.setStyle(tblStyle)
elements.append(tableThatSplitsOverPages)

doc.build(elements)
示例#48
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
示例#49
0
def reporteproduccion(request, pk):
    #definimos los modelos para el reporte
    salida = Produccion.objects.get(pk=pk)
    productosalida = ProductoProduccion.objects.filter(produccion__pk=pk)

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="H' + salida.referencia(
    ) + '.pdf"'

    # Create the PDF object, using the BytesIO object as its "file."
    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=letter)

    #Definimos la fuente que vamos a utilizar
    c.setFont("Helvetica", 12)

    data = [['Reporte de entrada ' + salida.referencia()],
            ['Fecha de creacion: ' + str(salida.fecha_creacion)]]

    tabla = Table(data, colWidths=[612])
    tabla.setStyle(TableStyle([
        ('ALIGN', (0, 0), (0, -1), 'CENTER'),
    ]))

    tabla.wrapOn(c, 0, 0)
    tabla.drawOn(c, 0, 730)

    #Conceptos
    data = [[
        'PRODUCTO A PRODUCIR', 'CANTIDAD', 'PRODUCTO PRODUCIDO', 'CANTIDAD'
    ]]
    for i in range(37):
        data.append(['', '', '', ''])

    j = 1
    for i in productosalida:
        data[j][
            0] = i.producto_para_producir.codigo_de_barras + ' ' + i.producto_para_producir.producto
        data[j][1] = i.cantidad_para_producir
        data[j][
            2] = i.producto_producido.codigo_de_barras + ' ' + i.producto_producido.producto
        data[j][3] = i.cantidad_producido
        j += 1

    t = Table(data, colWidths=[195, 60, 195, 60])
    t.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('BOX', (0, 0), (-1, -1), 2, colors.black),
            ('BOX', (0, 0), (3, 0), 2, colors.black),
            ('LINEAFTER', (0, 0), (0, -1), 1, colors.black),
            ('LINEAFTER', (1, 0), (1, -1), 1, colors.black),
            ('LINEAFTER', (2, 0), (2, -1), 1, colors.black),
            ('LINEAFTER', (2, 0), (2, -1), 1, colors.black),
        ]))
    #Importe con letra
    t.wrapOn(c, 20, 50)
    t.drawOn(c, 50, 35)

    c.showPage()
    c.save()

    # Get the value of the BytesIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
示例#50
0
def get_labels_pdf(item_codes: list,
                   api_key: Optional[str] = Security(api_key_header)):
    """
    "Get labels for list of codes "
    - param item_code: list of item codes
    - return: Bytes object of PDF
    """
    if item_codes is None or item_codes[0] is None or not item_codes:
        raise HTTPException(status_code=404, detail="Invalid query.")
    collection = db[api_key]
    # GENERATE ALL LABELS IN LIST
    labels = list()
    for item_code in item_codes:
        ret = collection.find_one({"code": item_code})
        ret.pop("_id")
        filename, image = gen_label(ret, api_key)
        image.save(filename, quality=100)
        labels.append(filename)  # 0 is filename, 1 is image in memory
    labels_iter = iter(labels)
    # MAKE PDF OF LABELS
    pdf_filename = f"generated-pdfs/{api_key}.pdf"
    doc = SimpleDocTemplate(pdf_filename,
                            pagesize=LETTER,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)
    Story = []
    data = list()
    table_style = [
        # ('GRID', (0, 1), (-1, -1), 1, colors.black),
        ('ALIGN', (1, 1), (1, -1), 'CENTER')
    ]
    Story.append(Spacer(0.25 * inch, 0.25 * inch))
    Story.append(Paragraph(f"This is an auto generated document."))
    Story.append(Spacer(0.25 * inch, 0.25 * inch))
    while True:
        try:
            row = list()
            for i in range(0, 4):
                if len(labels) < 2:
                    entry = labels[0]
                    entry = next(labels_iter)
                    canvas = (
                        platyImage(entry,
                                   width=LABEL_SIZE[0] / 6,
                                   height=LABEL_SIZE[1] / 5.5,
                                   hAlign=1),
                        Spacer(0.1 * inch, 0.1 * inch),
                    )
                    row.append(canvas)
                    print("one entry")
                    raise StopIteration
                else:
                    entry = next(labels_iter)
                    canvas = (
                        platyImage(entry,
                                   width=LABEL_SIZE[0] / 6,
                                   height=LABEL_SIZE[1] / 5.5,
                                   hAlign=1),
                        Spacer(0.1 * inch, 0.1 * inch),
                    )
                    row.append(canvas)
            data.append(row)
        except StopIteration:
            data.append(row)
            break
    t = Table(data)
    t.setStyle(table_style)
    Story.append(t)
    doc.build(Story)
    return FileResponse(pdf_filename, filename=f"{api_key}.pdf")
示例#51
0
def processRequest(req):

    sessionID = req.get('responseId')
    result = req.get("queryResult")
    user_says = result.get("queryText")
    parameters = result.get("parameters")

    intent = result.get("intent").get('displayName')

    if (intent == 'cust_details'):
        result = req.get("queryResult")
        user_says = result.get("queryText")

        parameters = result.get("parameters")
        cust_name = parameters.get("name")

        cust_contact = parameters.get("phone")
        cust_email = parameters.get("email")
        #===============================================WEB-SCRAPPING================================================

        # offical ministry of health website
        url = 'https://www.mohfw.gov.in/'

        # make a GET request to fetch the raw HTML content
        web_content = requests.get(url).content

        # parse the html content
        soup = BeautifulSoup(web_content, "html.parser")

        # remove any newlines and extra spaces from left and right
        extract_contents = lambda row: [x.text.replace('\n', '') for x in row]

        stats = []  # initialize stats
        all_rows = soup.find_all('tr')  # find all table rows

        for row in all_rows:
            stat = extract_contents(row.find_all('td'))  # find all data cells
            # notice that the data that we require is now a list of length 5
            if len(stat) == 5:
                stats.append(stat)

        # convert the data into a pandas dataframe and then to list for further processing
        new_cols = ["Sr.No", "States/UT", "Confirmed", "Recovered", "Deceased"]
        state_data = pd.DataFrame(data=stats, columns=new_cols)
        state_data1 = state_data.drop(['Sr.No'], axis=1)
        state_dic = state_data1.to_dict("records")

        #Converting to list
        state = [state_data.columns.values.tolist()
                 ] + state_data.values.tolist()

        #=================================================INTERACTION WITH MONGO DB==============================

        # Pushing data to database
        from pymongo import MongoClient
        client = MongoClient(
            'mongodb+srv://test:[email protected]/test?retryWrites=true&w=majority'
        )
        mydb = client['covid']
        information = mydb.collection
        information.delete_many({})
        information.insert_many(state_dic)
        users_dic = [{
            "cust_name": cust_name
        }, {
            "cust_email": cust_email
        }, {
            "cust_contact": cust_contact
        }]
        mydb = client['users']
        information = mydb.collection
        information.insert_many(users_dic)

        #================================================REPORT GENERATION USING REPORT LAB======================

        # Report generation
        fileName = 'report.pdf'

        from reportlab.platypus import SimpleDocTemplate
        from reportlab.lib.pagesizes import letter

        pdf = SimpleDocTemplate(fileName, pagesize=letter)

        from reportlab.platypus import Table
        table = Table(state)

        # add style
        from reportlab.platypus import TableStyle
        from reportlab.lib import colors

        style = TableStyle([
            ('BACKGROUND', (0, 0), (4, 0), colors.green),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
            ('ALIGN', (2, 0), (-1, -1), 'CENTER'),
            ('FONTNAME', (0, 0), (-1, 0), 'Courier-Bold'),
            ('FONTSIZE', (0, 0), (-1, 0), 12),
            ('BOTTOMPADDING', (0, 0), (-1, 0), 6),
            ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
        ])
        table.setStyle(style)

        # 2) Alternate backgroud color
        rowNumb = len(state)
        for i in range(1, rowNumb):
            if i % 2 == 0:
                bc = colors.burlywood
            else:
                bc = colors.beige

            ts = TableStyle([('BACKGROUND', (0, i), (-1, i), bc)])
            table.setStyle(ts)

        # 3) Add borders
        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, 1), (-1, -1), 2, colors.black),
        ])
        table.setStyle(ts)
        # adding date
        from datetime import datetime
        now = datetime.now()
        # dd/mm/YY H:M:S
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
        preventive = "To prevent the spread of COVID-19:<br /> Clean your hands often. Use soap and water, or an alcohol-based hand rub.<br /> Maintain a safe distance from anyone who is coughing or sneezing.<br /> Don’t touch your eyes, nose or mouth.<br /> Cover your nose and mouth with your bent elbow or a tissue when you cough or sneeze.<br /> Stay home if you feel unwell.<br /> If you have a fever, a cough, and difficulty breathing, seek medical attention. Call in advance.<br /> Follow the directions of your local health authority. "
        from reportlab.lib.styles import getSampleStyleSheet
        sample_style_sheet = getSampleStyleSheet()
        items = []
        from reportlab.platypus import Paragraph
        paragraph_1 = Paragraph("Latest updates on COVID-19 cases in India",
                                sample_style_sheet['Heading2'])
        paragraph_2 = Paragraph("Retrived at: " + dt_string,
                                sample_style_sheet['BodyText'])
        paragraph_3 = Paragraph(preventive, sample_style_sheet['BodyText'])
        items.append(paragraph_1)
        items.append(paragraph_2)
        items.append(table)
        items.append(paragraph_3)
        pdf.build(items)

        #================================================================SENDING EMAIL=================================================

        #sending email

        fromaddr = "*****@*****.**"
        toaddr = cust_email

        # instance of MIMEMultipart
        msg = MIMEMultipart()

        # storing the senders email address
        msg['From'] = fromaddr

        # storing the receivers email address
        msg['To'] = toaddr

        # storing the subject
        msg['Subject'] = "COVID19 Chatbot report"

        # string to store the body of the mail
        body = "Thanks for using COVID19 chat bot. Please find attached latest update on COVID19 cases in India. "

        # attach the body with the msg instance
        msg.attach(MIMEText(body, 'plain'))

        # open the file to be sent
        filename = "report.pdf"
        attachment = open("report.pdf", "rb")

        # instance of MIMEBase and named as p
        p = MIMEBase('application', 'octet-stream')

        # To change the payload into encoded form
        p.set_payload((attachment).read())

        # encode into base64
        encoders.encode_base64(p)

        p.add_header('Content-Disposition',
                     "attachment; filename= %s" % filename)

        # attach the instance 'p' to instance 'msg'
        msg.attach(p)

        # creates SMTP session
        s = smtplib.SMTP('smtp.gmail.com', 587)

        # start TLS for security
        s.starttls()

        # Authentication
        s.login(fromaddr, "<password>")

        # Converts the Multipart msg into a string
        text = msg.as_string()

        # sending the mail
        s.sendmail(fromaddr, toaddr, text)

        # terminating the session
        s.quit()
        # terminating the session
        fulfillmentText = "Thanks for sharing details, a report has been sent to your email id"

        return {"fulfillmentText": fulfillmentText}

#=============================================INTENT FOR STAT QUERY============================================
    elif (intent == 'stat'):

        state_ut = parameters.get("geo-state")

        from pymongo import MongoClient
        from bson.json_util import dumps

        client = MongoClient(
            'mongodb+srv://<name>:<password>@cluster0-buydi.mongodb.net/test?retryWrites=true&w=majority'
        )
        mydb = client['covid']
        information = mydb.collection
        statistics = dumps(information.find({"States/UT": state_ut}).limit(1))
        print(statistics)
        string = statistics[47:]
        string = string.replace('"', '')
        string = string.replace(']', '')
        string = string.replace('}', '')

        return {"fulfillmentText": string}
示例#52
0
def reporteventa(request, pk):
    venta = Venta.objects.get(pk=pk)
    productoventas = ProductoVenta.objects.filter(venta__pk=pk)
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="H' + venta.referencia(
    ) + '.pdf"'

    # Create the PDF object, using the BytesIO object as its "file."
    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=letter)

    #Ancho=612 y alto=792 de la página
    ancho, alto = letter

    #informacion de la empresa
    c.setFont("Helvetica", 30)
    fn = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                      'logo-barismo1.jpg')
    c.drawImage(fn, 50, 680, width=220, height=90)
    c.setFont("Helvetica", 8)
    c.drawString(250, 745, datos['razon_social'])
    c.drawString(250, 735, datos['rfc'])
    c.drawString(250, 725, datos['direccion'] + " CP:" + datos['cp'])
    c.drawString(250, 715, datos['ciudad'] + ", " + datos['estado'])
    c.drawString(250, 705, datos['telefono'] + "  " + datos['correo'])

    #Datos de la cotizacion
    c.setFont("Helvetica", 10)
    d = [['   VENTA N°   '], [venta.referencia()], ['FECHA'],
         [venta.fecha_creacion], ['FACTURA'], [venta.no_de_factura],
         ['ESTADO'], [venta.pago()]]

    table = Table(d)
    table.setStyle(
        TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 2, colors.black),
            ('BACKGROUND', (0, 0), (0, 0), colors.lavender),
            ('BACKGROUND', (0, 2), (0, 2), colors.lavender),
            ('BACKGROUND', (0, 4), (0, 4), colors.lavender),
            ('BACKGROUND', (0, -2), (0, -2), colors.lavender),
        ]))

    #Importe con letra
    table.wrapOn(c, 20, 50)
    table.drawOn(c, 495, 620)

    #Datos del cliente
    c.setFont("Helvetica", 10)
    c.drawString(55, 660, "CLIENTE:" + venta.cliente.contacto)
    c.drawString(55, 645, "RAZON SOCIAL:" + venta.cliente.razon_social)
    c.drawString(55, 630, "RFC:" + venta.cliente.rfc)
    c.drawString(
        55, 615, "DIRECCION:" + venta.cliente.direccion + ' ' +
        venta.cliente.ciudad + " CP:" + venta.cliente.codigo_postal)

    #Conceptos
    data = [['CANTIDAD', 'DESCRIPCION', 'PRECIOU', 'PRECIO TOTAL'],
            ['', '', '', ''], ['', '', '', ''], ['', '', '', ''],
            ['', '', '', ''], ['', '', '', ''], ['', '', '', ''],
            ['', '', '', ''], ['', '', '', ''], ['', '', '', ''],
            ['', '', '', ''], ['', '', '', ''], ['', '', '', ''],
            ['', '', '', ''], ['', '', '', ''], ['', '', '', ''],
            ['', '', '', ''], ['', '', '', ''], ['', '', '', ''],
            ['', '', '', ''], ['', '', '', ''], ['', '', '', ''],
            ['', '', '', ''], ['', '', '', ''], ['', '', '', ''],
            ['', '', '', ''], ['', '', 'SUBTOTAL', ''], ['', '', 'IVA', ''],
            ['', '', 'TOTAL', '']]

    j = 1
    sub = 0
    total = 0
    for i in productoventas:
        cantidad = i.cantidad
        precio = i.producto.precio_de_venta
        total = cantidad * precio
        data[j][0] = cantidad
        data[j][1] = i.producto.codigo_de_barras + ' ' + i.producto.producto
        data[j][2] = precio
        data[j][3] = format(total, '.2f')
        sub += total
        j += 1

    data[26][3] = "$" + format(sub, '.2f')
    if venta.iva > 0:
        data[27][3] = "$" + format(sub * venta.iva / 100, '.2f')
    else:
        data[27][3] = "$0.00"
    data[28][3] = "$" + str(venta.total)

    t = Table(data, colWidths=[60, 310, 58, 86])
    t.setStyle(
        TableStyle([
            ('ALIGN', (0, 1), (0, -1), 'CENTER'),
            ('ALIGN', (2, 1), (2, -4), 'CENTER'),
            ('ALIGN', (3, 1), (3, -1), 'CENTER'),
            ('BOX', (0, 0), (-1, -4), 2, colors.black),
            ('BOX', (0, 0), (4, 0), 2, colors.black),
            ('INNERGRID', (-2, -3), (-1, -1), 0.25, colors.black),
            ('BOX', (-2, -3), (-1, -1), 2, colors.black),
            ('BOX', (-1, -3), (-1, -1), 2, colors.black),
            ('BOX', (0, -3), (-2, -1), 2, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), colors.lavender),
            ('BACKGROUND', (-2, -3), (-2, -1), colors.lavender),
            ('LINEAFTER', (0, 0), (0, -4), 1, colors.black),
            ('LINEAFTER', (1, 0), (1, -4), 1, colors.black),
            ('LINEAFTER', (2, 0), (2, -4), 1, colors.black),
        ]))
    #Importe con letra
    c.drawString(60, 95, "TOTAL CON LETRA:")
    decimales = int((float(venta.total) - int(venta.total)) * 100)
    c.drawString(
        60, 73,
        to_word(total) + ' PESOS ' + '%02d' % int(decimales) + '/100' + ' MN')

    t.wrapOn(c, 20, 50)
    t.drawOn(c, 55, 55)

    c.showPage()
    c.save()

    # Get the value of the BytesIO buffer and write it to the response.
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response
示例#53
0
def render_statement(data, paragraphss, quarterly, fileName):
    doc = SimpleDocTemplate(fileName,
                            pagesize=A4,
                            rightMargin=72,
                            leftMargin=56,
                            topMargin=5,
                            bottomMargin=18)
    Story = []
    logo = "logos/toplogo.png"
    logo2 = "logos/bottomlogo.png"
    im = Image(logo, 8 * inch, 3 * inch)
    im2 = Image(logo2, 7 * inch, 1 * inch)
    t_keep = KeepInFrame(0,
                         0,
                         Story,
                         mode='shrink',
                         hAlign='CENTER',
                         vAlign='MIDDLE')
    lista = [data.columns[:, ].values.astype(str).tolist()
             ] + data.values.tolist()
    t1 = None
    if not quarterly:
        t1 = Table(lista,
                   4 * [1.5 * inch, 1.5 * inch, 2 * inch, 1.5 * inch],
                   (len(lista)) * [0.3 * inch],
                   hAlign='CENTER')
    else:
        t1 = Table(lista,
                   2 * [3.2 * inch, 3.2 * inch], (len(lista)) * [0.3 * inch],
                   hAlign='CENTER')

    # t1.setStyle(TableStyle([('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
    #                         ('TEXTCOLOR', (1, 1), (-2, -2), colors.red),
    #                         ('VALIGN', (0, 0), (0, -1), 'TOP'),
    #                         ('TEXTCOLOR', (0, 0), (0, -1), colors.blue),
    #                         ('ALIGN', (0, -1), (-1, -1), 'CENTER'),
    #                         ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'),
    #                         ('TEXTCOLOR', (0, -1), (-1, -1), colors.green),
    #                         ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    #                         ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    #                         ]))
    t1.setStyle(
        TableStyle([("BOX", (0, 0), (-1, -1), 0.25, colors.black),
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('TEXTCOLOR', (0, -1), (-1, -1), colors.green),
                    ('FONTNAME', (0, -1), (-1, -1), 'Courier-Bold')]))
    data_len = len(lista)

    for each in range(data_len):
        if each % 2 == 0:
            bg_color = colors.whitesmoke
        else:
            bg_color = colors.lightgrey

        t1.setStyle(
            TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)]))
        if each == data_len:
            t1.setStyle(
                TableStyle([('FONTNAME', (0, each), (0, each), 'Courier-Bold')
                            ]))
            t1.setStyle(
                TableStyle([('BACKGROUND', (0, each), (0, each), colors.green)
                            ]))
    Story.append(im)
    style = ParagraphStyle(
        name='Normal',
        fontSize=12,
        borderPadding=1,
        padding=1,
        alignment=TA_LEFT,
        leading=24,
        leftMargin=10,
    )
    for x, y in paragraphss.items():
        p = ""
        p += '<b>' + x + '</b>' + ":" + y
        p += "\n"
        Story.append(Paragraph(p, style=style))
    Story.append(t1)

    Story.append(Spacer(1, 12))
    Story.append(im2)
    Story.append(t_keep)
    doc.build(Story)
示例#54
0
    def __init__(self, liste_labelsColonnes=[], listeValeurs=[], listeSelections=[]):
        """ Imprime la liste de personnes """
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.pagesizes import A4, portrait, landscape
        from reportlab.lib import colors
        
        hauteur_page = defaultPageSize[0]
        largeur_page = defaultPageSize[1]
        largeur_ligne = largeur_page - (75 * 2)

        # Initialisation du PDF
        nomDoc = UTILS_Fichiers.GetRepTemp("liste_emplois.pdf")
        if "win" in sys.platform : nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, pagesize=landscape(A4))
        story = []

        # Création du titre du document
        dataTableau = []
        largeursColonnes = ( (620, 100) )
        dateDuJour = DateEngFr(str(datetime.date.today()))
        dataTableau.append( (_(u"Liste des offres d'emploi"), _(u"Edité le %s") % 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,20))       
        
        # Tableau de données
        dataTableau = []
        
        # Création des colonnes
        largeursColonnes = []
        labelsColonnes = []

        index = 0
        for labelCol, alignement, largeur, nomChamp in liste_labelsColonnes :
            if largeur == 0 : largeur = 30
            largeursColonnes.append(largeur/2*1.4)
            labelsColonnes.append(labelCol)
            index += 1
        dataTableau.append(labelsColonnes)
        
        # Création des lignes
        for valeurs in listeValeurs :
            ligne = []
            if int(valeurs[0]) in listeSelections :
                for valeur in valeurs :
                    ligne.append(valeur)
                dataTableau.append(ligne)
    
        # Style du tableau
        style = TableStyle([
                            ('GRID', (0,0), (-1,-1), 0.25, colors.black), # Crée la bordure noire pour tout le tableau
                            ('ALIGN', (0,0), (-1,-1), 'CENTRE'), # Titre du groupe à gauche
                            ('VALIGN', (0,0), (-1,-1), 'TOP'),
                            ('FONT',(0,0),(-1,-1), "Helvetica", 7), # Donne la police de caract. + taille de police 
                            ])
           
        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0,20))
            
        # Enregistrement du PDF
        doc.build(story)
        
        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
示例#55
0
def users_passwords_to_pdf(pdf):
    """
    Create access data sheets for all users as PDF
    """
    users_pdf_wlan_ssid = config["users_pdf_wlan_ssid"] or "-"
    users_pdf_wlan_password = config["users_pdf_wlan_password"] or "-"
    users_pdf_wlan_encryption = config["users_pdf_wlan_encryption"] or "-"
    users_pdf_url = config["users_pdf_url"] or "-"
    users_pdf_welcometitle = config["users_pdf_welcometitle"]
    users_pdf_welcometext = config["users_pdf_welcometext"]
    if config['users_sort_users_by_first_name']:
        sort = 'first_name'
    else:
        sort = 'last_name'
    qrcode_size = 2 * cm
    # qrcode for system url
    qrcode_url = QrCodeWidget(users_pdf_url)
    qrcode_url.barHeight = qrcode_size
    qrcode_url.barWidth = qrcode_size
    qrcode_url.barBorder = 0
    qrcode_url_draw = Drawing(45, 45)
    qrcode_url_draw.add(qrcode_url)
    # qrcode for wlan
    text = "WIFI:S:%s;T:%s;P:%s;;" % (users_pdf_wlan_ssid,
                                      users_pdf_wlan_encryption,
                                      users_pdf_wlan_password)
    qrcode_wlan = QrCodeWidget(text)
    qrcode_wlan.barHeight = qrcode_size
    qrcode_wlan.barWidth = qrcode_size
    qrcode_wlan.barBorder = 0
    qrcode_wlan_draw = Drawing(45, 45)
    qrcode_wlan_draw.add(qrcode_wlan)

    for user in User.objects.all().order_by(sort):
        pdf.append(Paragraph(user, stylesheet['h1']))
        pdf.append(Spacer(0, 1 * cm))
        data = []
        # WLAN access data
        cell = []
        cell.append(Paragraph(_("WLAN access data"), stylesheet['h2']))
        cell.append(
            Paragraph("%s:" % _("WLAN name (SSID)"), stylesheet['formfield']))
        cell.append(
            Paragraph(users_pdf_wlan_ssid, stylesheet['formfield_value']))
        cell.append(
            Paragraph("%s:" % _("WLAN password"), stylesheet['formfield']))
        cell.append(
            Paragraph(users_pdf_wlan_password, stylesheet['formfield_value']))
        cell.append(
            Paragraph("%s:" % _("WLAN encryption"), stylesheet['formfield']))
        cell.append(
            Paragraph(users_pdf_wlan_encryption,
                      stylesheet['formfield_value']))
        cell.append(Spacer(0, 0.5 * cm))
        # OpenSlides access data
        cell2 = []
        cell2.append(Paragraph(_("OpenSlides access data"), stylesheet['h2']))
        cell2.append(Paragraph("%s:" % _("Username"), stylesheet['formfield']))
        cell2.append(Paragraph(user.username, stylesheet['formfield_value']))
        cell2.append(Paragraph("%s:" % _("Password"), stylesheet['formfield']))
        cell2.append(
            Paragraph(user.default_password, stylesheet['formfield_value']))
        cell2.append(Paragraph("URL:", stylesheet['formfield']))
        cell2.append(Paragraph(users_pdf_url, stylesheet['formfield_value']))
        data.append([cell, cell2])
        # QRCodes
        cell = []
        if users_pdf_wlan_ssid != "-" and users_pdf_wlan_encryption != "-":
            cell.append(qrcode_wlan_draw)
            cell.append(
                Paragraph(_("Scan this QRCode to connect WLAN."),
                          stylesheet['qrcode_comment']))
        cell2 = []
        if users_pdf_url != "-":
            cell2.append(qrcode_url_draw)
            cell2.append(
                Paragraph(_("Scan this QRCode to open URL."),
                          stylesheet['qrcode_comment']))
        data.append([cell, cell2])
        # build table
        table = Table(data)
        table._argW[0] = 8 * cm
        table._argW[1] = 8 * cm
        table.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')]))
        pdf.append(table)
        pdf.append(Spacer(0, 2 * cm))

        # welcome title and text
        pdf.append(Paragraph(users_pdf_welcometitle, stylesheet['h2']))
        pdf.append(
            Paragraph(users_pdf_welcometext.replace('\r\n', '<br/>'),
                      stylesheet['Paragraph12']))
        pdf.append(PageBreak())
    return pdf
示例#56
0
    def body_story(self, team):
        def general_items():
            yield Paragraph(
                "L'équipe a désigné un(e) capitaine qui s'est présenté(e) aux organisateurs",
                style=cell_body)
            yield Paragraph(
                "L'équipe a préparé un dossier de recherche sur la thématique de la compétition "
                "et a remis son poster aux organisateurs",
                style=cell_body)
            yield Paragraph(
                "L'équipe a bien compris que ne pas se présenter à l'exposé ou ne pas remettre le poster "
                "empêche tout classement dans la compétition",
                style=cell_body)
            yield Paragraph(
                "L'équipe a bien compris que ne pas se présenter à une épreuve correspond à un forfait "
                "et qu'elle sera classée derrière toutes les autres pour cette épreuve",
                style=cell_body)

        def robotics_items():
            is_mindstorms = team.category == Category.Mindstorms
            yield "Le robot ne comporte qu'une seule %s programmable" % (
                "brique" if is_mindstorms else 'carte')
            if is_mindstorms:
                yield Paragraph(
                    "Aucun moyen de solidification <i>(vis, colle, autocollants, adhésif,...)</i> "
                    "n'est utilisé dans la construction du robot",
                    style=cell_body)
            yield Paragraph(
                "Le robot est entièrement autonome, y compris en matière d'énergie",
                style=cell_body)
            yield Paragraph(
                "L'équipe est capable de démontrer qu'elle a parfaitement compris l'utilisation et le principe "
                "de fonctionnement des capteurs et actionneurs utilisées",
                style=cell_body)
            yield Paragraph(
                "L'équipe a bien compris les règles du jeu ainsi que la procédure de départ",
                style=cell_body)
            yield Paragraph(
                "L'équipe a bien compris que toute intervention sur le robot pendant le match entraîne "
                "la disqualification pour l'épreuve",
                style=cell_body)
            yield Paragraph(
                "L'équipe est informée que 2 équipiers seulement sont autorisés à être autour de la table de jeu "
                "pendant les matchs",
                style=cell_body)
            yield Paragraph(
                "L'équipe accepte que les décisions des arbitres sont souveraines et qu'aucune contestation "
                "ne peut être faite après avoir quitté la table de jeu",
                style=cell_body)

        for _ in (
                Table([['Arbitre', '']],
                      colWidths=[6.7 / 2 * inch] * 2,
                      style=default_table_style + [('BACKGROUND', (0, 0),
                                                    (0, 0), cell_bkgnd_color),
                                                   ('ALIGN', (0, 0),
                                                    (0, 0), 'RIGHT')]),
                Paragraph("Déroulement de la compétition",
                          style=section_title),
                Table([(_, '') for _ in general_items()],
                      colWidths=[6 * inch, 0.7 * inch],
                      style=self.items_table_style),
                Paragraph("Epreuves de robotique", style=section_title),
                Table([(_, '') for _ in robotics_items()],
                      colWidths=[6 * inch, 0.7 * inch],
                      style=self.items_table_style),
                tables_spacer,
                Paragraph("Signature équipe :", style=section_title),
        ):
            yield _
	def create_pdf(self):
		"""
		Create a pdf
		"""
		story = []

		doc = SimpleDocTemplate(self.refile, pagesize=A4)
		styles = getSampleStyleSheet()

		spacer = Spacer(0, 0.07 * inch)

		story.append(spacer)
		story.append(spacer)

		ptext = "<font size=10><a>Customer Name :{}</a></font>".format(self.cust.name)
		p = Paragraph(ptext, styles["Normal"])
		story.append(p)

		ptext = "<font size=10><a>Customer Mobile # :{}</a></font>".format(self.cust.mobile_number)
		p = Paragraph(ptext, styles["Normal"])
		story.append(p)
		story.append(spacer)
		story.append(spacer)
		"""
				Create the line items
				"""
		text_data = ["#", "Material Name", "Material Type", "QTY"]
		d = []
		font_size = 8
		centered = ParagraphStyle(name="centered", alignment=TA_CENTER)
		for text in text_data:
			ptext = "<font size=%s><b>%s</b></font>" % (font_size, text)
			p = Paragraph(ptext, centered)
			d.append(p)

		data = [d]

		line_num = 1

		formatted_line_data = []

		outlist = getOutbounOneCustomerRow(self.cust)
		for idx, val in enumerate(outlist):
			if val.rawMaterial:
				mname = val.rawMaterial.name
				typeName = "Raw Material"
			if val.spareParts:
				mname = val.spareParts.name
				typeName = "Spare Parts"
			if val.tools:
				mname = val.tools.name
				typeName = "Tools"
			if val.finishProducts:
				mname = val.finishProducts.name
				typeName = "Finish Product"
			line_data = [str(line_num), mname, typeName, val.req_qty]

			for item in line_data:
				ptext = "<font size=%s>%s</font>" % (font_size - 1, item)
				p = Paragraph(ptext, centered)
				formatted_line_data.append(p)
			data.append(formatted_line_data)
			formatted_line_data = []
			line_num += 1

		table = Table(data, colWidths=[30, 150, 150, 80, 80], rowHeights=20
					  , style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black)])
		story.append(table)
		story.append(spacer)
		#########################################################################################
		actxt = '<font size=11><p><u>Accountant</u><br/>Rani Mohamed</p></font>'
		pactxt = Paragraph(actxt, centered)

		matxtnum = '<font size=11><p><u>Manager</u><br/>Mohamed Althubiti</p></font>'
		pmatxtnum = Paragraph(matxtnum, centered)
		data = [[pactxt, '', '', '', pmatxtnum]]
		t = Table(data, colWidths=[150, 5, 250, 5, 150])
		story.append(t)
		#########################################################################################

		story.append(spacer)

		doc.build(story, onFirstPage=self.createDocument, onLaterPages=self.createDocument)

		subprocess.Popen([self.refile], shell=True)
示例#58
0
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib.pagesizes import letter

doc = SimpleDocTemplate("simple_table.pdf", pagesize=letter)

elements = []

data = [['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'],
        ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34']]

t = Table(data)
elements.append(t)

doc.build(elements)
示例#59
0
 def generate_padding(padding):
     t = Table([''])
     t.setStyle([('TOPPADDING', (0, 0), (0, 0), padding)])
     return t
示例#60
0
    def __generar_tabla_principal(self, lista):
        data = self.__procesar_datos_info(lista)

        # self.__mostrar_lista(data)
        anc = self.tamaño[0] - 36

        tam_col = [
            anc * .46, anc * .08, anc * .14, anc * .07, anc * .07, anc * .18
        ]
        alt = .31 * inch
        tam_fil = (len(data)) * [alt]

        if len(self.ref) <= 10:
            textsize_ref, align_ref = (15, "TOP")
        elif len(self.ref) < 15:
            textsize_ref, align_ref = (12, "MIDDLE")
        else:
            # self.ref = self.__partir_string(self.ref)
            textsize_ref, align_ref = (10, "MIDDLE")

        # if len(self.ref)<=10 else (10, "MIDDLE")
        textsize_anchoylargo = 8
        textsize_cliente = 15
        textsize_proyecto = 16

        style = TableStyle([
            ('SPAN', (-3, 0), (-1, 0)),
            ('SPAN', (-3, 1), (-1, 1)),
            ('SPAN', (-3, 2), (-2, 2)),
            ('SPAN', (-1, 2), (-1, -2)),
            ('SPAN', (-3, -1), (-2, -1)),
            ('SPAN', (0, 0), (0, -1)),
            # ('ALIGN',(0,0),(-1,-1),'CENTER'),
            # ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
            ('FONTNAME', (-3, 0), (-1, -1), "Helvetica-Bold"),
            ('FONTSIZE', (-3, 0), (-1, -1), 13),
            ('FONTSIZE', (-3, 0), (-1, 0), textsize_cliente),
            ('FONTSIZE', (-3, 1), (-1, 1), textsize_proyecto),
            ('INNERGRID', (-4, 0), (-1, -1), 0.75, self.verde_inmetar),
            ('FONTSIZE', (-3, 3), (-2, 3), textsize_anchoylargo),
            ('FONTSIZE', (-3, -4), (-2, -4), 10),  ##
            ('FONTSIZE', (-4, -1), (-1, -1), 15),  ##
            ('FONTSIZE', (-3, 2), (-2, 2), textsize_ref),  ##
            ('TEXTCOLOR', (-4, 0), (-4, -1), colors.white),
            ('TEXTCOLOR', (-4, -1), (-1, -1), colors.white),
            ('TEXTCOLOR', (-1, 0), (-1, -1), colors.white),
            ('BACKGROUND', (-4, 0), (-4, -1), self.verde_inmetar),
            ('BACKGROUND', (-4, -1), (-1, -1), self.verde_inmetar),
            ('FONTNAME', (-4, 0), (-4, -1), "Helvetica-Bold"),
            ('FONTSIZE', (-4, 0), (-4, -1), 10),
            ('ALIGN', (-4, 0), (-4, -1), 'LEFT'),
            ('BOX', (0, 0), (0, -1), 2, self.verde_inmetar),
            ('BOX', (2, 0), (-1, -1), 2, self.verde_inmetar),
            ('INNERGRID', (-4, 0), (-4, -1), 0.75, colors.white),
            ('INNERGRID', (-4, -1), (-1, -1), 0.75, colors.white),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('VALIGN', (-3, 2), (-2, 2), align_ref),
            ('VALIGN', (-3, 0), (-1, 1), "TOP"),  #CLIENTE Y PROYECTO
            ('VALIGN', (-3, -1), (-1, -1), "TOP"),  #UND Y KGS
        ])

        t = Table(data, tam_col, tam_fil)
        t.setStyle(style)
        return t