コード例 #1
0
ファイル: albaran_porte.py プロジェクト: pacoqueen/bbinn
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
コード例 #2
0
    def _add_secondary_scale(self):
        """ add the secondary scale to the table (text + styles) """

        Y_pos = 1
        X_pos = 1

        # write the label
        ps = ParagraphStyle("secondary_scale_label")
        ps.alignment = TA_RIGHT
        ps.fontName = self.DEFAULT_FONT
        ps.fontSize = self.DEFAULT_FONT_SIZE

        title = Paragraph(self.data.scale.secondary_label, ps)
        self.table[Y_pos][0] = title

        ps = ParagraphStyle("secondary_scale")
        ps.alignment = TA_CENTER
        ps.fontName = self.DEFAULT_FONT
        ps.fontSize = self.DEFAULT_FONT_SIZE

        # the secondary scale is not define the same way as the primary scale.
        # it's defined by groups of same label. (start_pos, start_end, item)
        # see ScaleData._group_scale() for details
        for group in self.data.scale.secondary_scale_groups:
            pos_start, pos_end, item = group
            p = Paragraph(item, ps)

            # draw the label in the middle of the similar cells
            self.table[Y_pos][int((pos_start + pos_end) / 2) + 1] = p

            # draw light border arrounds items
            self.styles.append(("BOX", (pos_start + X_pos, Y_pos), (pos_end + X_pos, Y_pos), 0.2, "#bbbbbb"))
コード例 #3
0
ファイル: pdf_support.py プロジェクト: KarolBedkowski/alldb
def _prepare_styles():
	styles = {}
	stylesheet = getSampleStyleSheet()

	style = ParagraphStyle("Normal", stylesheet['Normal'])
	style.alignment = TA_LEFT
	style.fontSize = 6
	style.fontName = 'FreeSans'
	style.leading = 8
	styles['Normal'] = style

	style = ParagraphStyle("ItemTitle", stylesheet['Heading1'])
	style.alignment = TA_LEFT
	style.fontSize = 8
	style.fontName = 'FreeSansBold'
	style.fontSize = 10
	styles['ItemTitle'] = style

	style = ParagraphStyle("Heading", stylesheet['Heading2'])
	style.alignment = TA_CENTER
	style.fontSize = 6
	style.fontName = 'FreeSansBold'
	styles['Heading'] = style

	style = ParagraphStyle("FieldHead", stylesheet['Heading2'])
	style.alignment = TA_LEFT
	style.fontSize = 6
	style.fontName = 'FreeSansBold'
	style.leading = 8
	styles['FieldHead'] = style

	return styles
コード例 #4
0
ファイル: log.py プロジェクト: dairdr/notes
	def drawHeader(self, canvas, doc):
		logo_path = os.path.join(settings.STATIC_ROOT, 'assets/escudo.jpg')
		logo = Image(logo_path, width=0.7*inch, height=0.7*inch)

		title_style = ParagraphStyle(name='Title')
		title_style.fontName = 'Helvetica-Bold'
		title_style.fontSize = 11
		title_style.alignment = TA_CENTER
		
		subtitle_style = ParagraphStyle(name='Subtitle')
		subtitle_style.fontName = 'Helvetica'
		subtitle_style.fontSize = 8
		subtitle_style.alignment = TA_CENTER

		subtitle2_style = ParagraphStyle(name='Subtitle2')
		subtitle2_style.fontName = 'Helvetica'
		subtitle2_style.fontSize = 8
		subtitle2_style.alignment = TA_CENTER

		subtitle3_style = ParagraphStyle(name='Subtitle3')
		subtitle3_style.fontName = 'Helvetica'
		subtitle3_style.fontSize = 8
		subtitle3_style.alignment = TA_CENTER

		subtitle4_style = ParagraphStyle(name='Subtitle4')
		subtitle4_style.fontName = 'Helvetica'
		subtitle4_style.fontSize = 8
		subtitle4_style.alignment = TA_CENTER

		data = [
			[logo, [
					Paragraph('INSTITUCION EDUCATIVA AUGUSTO ESPINOSA VALDERRAMA', title_style),
					Paragraph('Reconocido oficialmente por la Secretaría de Educación Municipal de Montería mediante resolución 0751 de junio 12 de 2009', subtitle_style),
					Paragraph('Corregimiento Santa Clara – Municipio de Montería', subtitle2_style),
					Paragraph('Tel. 7905949 Código DANE 223001005404', subtitle3_style),
					Paragraph('Nit 812007342', subtitle4_style)
				]
			]
		]
		LIST_STYLE = TableStyle([
			# ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
			# ('BOX', (0,0), (-1,-1), 0.25, colors.black),
			('TEXTCOLOR',(0,0),(-1,-1),colors.black),
			('ALIGN', (0,0), (-1,-1), 'CENTER'),
			('FONTSIZE', (-1, -1), (-1, -1), 8),
			('VALIGN',(0,0),(-1,-1),'MIDDLE'),
			('TOPPADDING', (0, 0), (-1, -1), 0),
			('BOTTOMPADDING', (0, 0), (-1, -1), 0),
			('LEFTPADDING', (0, 0), (-1, -1), 0),
			('RIGHTPADDING', (0, 0), (-1, -1), 0),
		])
		colWidths = [0.7*inch, '*']
		table = Table(data, colWidths=colWidths, style=LIST_STYLE)
		w, h = table.wrap(doc.width, 0)
		table.drawOn(canvas, doc.leftMargin + 5, doc.height + 150)
コード例 #5
0
ファイル: pdf_utils.py プロジェクト: fthuin/osis
def main_data(tutor, academic_year, session_exam, styles, learning_unit_year, pgm, content):
    content.append(SMALL_INTER_LINE)
    p_structure = ParagraphStyle('entete_structure')
    p_structure.alignment = TA_LEFT
    p_structure.fontSize = 10

    p = ParagraphStyle('entete_droite')
    p.alignment = TA_RIGHT
    p.fontSize = 10

    content.append(Paragraph('%s : %s' % (_('Academic year'), str(academic_year)), p))
    content.append(Paragraph('Session : %d' % session_exam.number_session, p))
    content.append(BIG_INTER_LINE)

    if pgm.structure is not None:
        content.append(Paragraph('%s' % pgm.structure, p_structure))
        content.append(SMALL_INTER_LINE)

    content.append(Paragraph("<strong>%s : %s</strong>" % (learning_unit_year.acronym,learning_unit_year.title), styles["Normal"]) )
    content.append(SMALL_INTER_LINE)

    tutor = None
    if tutor is None:
        p_tutor = Paragraph(''' ''' , styles["Normal"])
    else:
        p_tutor = Paragraph('''<b>%s %s</b>''' % (tutor.person.last_name, tutor.person.first_name), styles["Normal"])

    data_tutor= [[p_tutor],
       [''],
       [''],
       ['']]
    table_tutor=Table(data_tutor)
    p_pgm = Paragraph('''<b>%s : %s</b>''' % (_('Program'),pgm.acronym), styles["Normal"])
    data_pgm= [[p_pgm],
               [_('Deliberation date') + ' : '],
               [_('Chair of the exam board') + ' : '],
               [_('Exam board secretary') + ' : '],
              ]
    table_pgm=Table(data_pgm)
    table_pgm.setStyle(TableStyle([
    ('LEFTPADDING',(0,0),(-1,-1), 0),
                         ('RIGHTPADDING',(0,0),(-1,-1), 0),
                       ('VALIGN',(0,0), (-1,-1), 'TOP')
                       ]))
    dataTT = [[table_pgm,table_tutor]]

    tt=Table(dataTT, colWidths='*')
    tt.setStyle(TableStyle([
        ('LEFTPADDING',(0,0),(-1,-1), 0),
                             ('RIGHTPADDING',(0,0),(-1,-1), 0),
                       ('VALIGN',(0,0), (-1,-1), 'TOP')
                       ]))
    content.append(tt)
    content.append(Spacer(1, 12))
コード例 #6
0
ファイル: albaran_porte.py プロジェクト: pacoqueen/bbinn
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
コード例 #7
0
ファイル: albaran_porte.py プロジェクト: pacoqueen/bbinn
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])
コード例 #8
0
ファイル: pdfcanvas.py プロジェクト: mcccclean/card-renderer
 def addStyle(self, data):
     def addFont(fontfile):
         if not fontfile:
             return None
         elif fontfile.endswith(".ttf") or fontfile.endswith(".otf"):
             fontname = os.path.splitext(fontfile)[0]
             pdfmetrics.registerFont(TTFont(fontname, fontfile))
             print "Registered", fontfile
             return fontname
         else:
             return fontfile
     name = data.get('name', "")
     s = ParagraphStyle(name)
     normal = addFont(data.get('font', "Helvetica"))
     bold = addFont(data.get('bold', None))
     italic = addFont(data.get('italic', None))
     bolditalic = addFont(data.get('bolditalic', None))
     pdfmetrics.registerFontFamily(normal, normal=normal, bold=bold or normal, italic=italic or normal, boldItalic=bolditalic or normal)
     s.fontName = normal
     s.fontSize = data.get('size', 10)
     s.alignment = dict(center=TA_CENTER, left=TA_LEFT, right=TA_RIGHT)[data.get('align', 'left')]
     s.leading = data.get('leading', s.leading)
     s.valign = data.get('valign', "top")
     s.textColor = data.get('color', "#ff000000")
     self.styles[name] = s
コード例 #9
0
 def test3(self):
     '''compare CJK splitting in some edge cases'''
     from reportlab.pdfgen.canvas import Canvas
     from reportlab.platypus.paragraph import Paragraph
     from reportlab.lib.styles import ParagraphStyle
     from reportlab.pdfbase import pdfmetrics
     from reportlab.lib.enums import TA_LEFT
     sty = ParagraphStyle('A')
     sty.fontSize = 15
     sty.leading = sty.fontSize*1.2
     sty.fontName = 'Courier'
     sty.alignment = TA_LEFT
     sty.wordWrap = 'CJK'
     p0=Paragraph('ABCDEFGHIJKL]N',sty)
     p1=Paragraph('AB<font color="red">C</font>DEFGHIJKL]N',sty)
     canv = Canvas('test_platypus_paragraph_cjk3.pdf')
     ix = len(canv._code)
     aW = pdfmetrics.stringWidth('ABCD','Courier',15)
     w,h=p0.wrap(aW,1000000)
     y = canv._pagesize[1]-72-h
     p0.drawOn(canv,72,y)
     w,h=p1.wrap(aW,1000000)
     y -= h+10
     p1.drawOn(canv,72,y)
     w,h=p0.wrap(aW*0.25-2,1000000)
     y -= h+10
     p0.drawOn(canv,72,y)
     w,h=p1.wrap(aW/4.-2,1000000)
     y -= h+10
     p1.drawOn(canv,72,y)
     assert canv._code[ix:]==['q', '1 0 0 1 72 697.8898 cm', 'q', '0 0 0 rg', 'BT 1 0 0 1 0 57 Tm /F2 15 Tf 18 TL (ABCD) Tj T* (EFGH) Tj T* (IJKL]) Tj T* (N) Tj T* ET', 'Q', 'Q', 'q', '1 0 0 1 72 615.8898 cm', 'q', 'BT 1 0 0 1 0 57 Tm 18 TL /F2 15 Tf 0 0 0 rg (AB) Tj 1 0 0 rg (C) Tj 0 0 0 rg (D) Tj T* (EFGH) Tj T* (IJKL]) Tj T* (N) Tj T* ET', 'Q', 'Q', 'q', '1 0 0 1 72 353.8898 cm', 'q', '0 0 0 rg', 'BT 1 0 0 1 0 237 Tm /F2 15 Tf 18 TL (A) Tj T* (B) Tj T* (C) Tj T* (D) Tj T* (E) Tj T* (F) Tj T* (G) Tj T* (H) Tj T* (I) Tj T* (J) Tj T* (K) Tj T* (L) Tj T* (]) Tj T* (N) Tj T* ET', 'Q', 'Q', 'q', '1 0 0 1 72 91.88976 cm', 'q', 'BT 1 0 0 1 0 237 Tm 18 TL /F2 15 Tf 0 0 0 rg (A) Tj T* (B) Tj T* 1 0 0 rg (C) Tj T* 0 0 0 rg (D) Tj T* (E) Tj T* (F) Tj T* (G) Tj T* (H) Tj T* (I) Tj T* (J) Tj T* (K) Tj T* (L) Tj T* (]) Tj T* (N) Tj T* ET', 'Q', 'Q']
     canv.showPage()
     canv.save()
コード例 #10
0
ファイル: pisa_context.py プロジェクト: nbio/frnda
 def toParagraphStyle(self, first, full=False):
     style = ParagraphStyle('default%d' % self.UID(), keepWithNext=first.keepWithNext)
     style.fontName = first.fontName
     style.fontSize = first.fontSize
     style.leading = max(first.leading, first.fontSize * 1.25)
     style.backColor = first.backColor
     style.spaceBefore = first.spaceBefore
     style.spaceAfter = first.spaceAfter
     style.leftIndent = first.leftIndent
     style.rightIndent = first.rightIndent
     style.firstLineIndent = first.firstLineIndent
     style.textColor = first.textColor
     style.alignment = first.alignment
     style.bulletFontName = first.bulletFontName or first.fontName 
     style.bulletFontSize = first.fontSize
     style.bulletIndent = first.bulletIndent
     # Border handling for Paragraph
     style.borderWidth = 0
     if getBorderStyle(first.borderTopStyle):
         style.borderWidth = max(first.borderLeftWidth, first.borderRightWidth, first.borderTopWidth, first.borderBottomWidth)
         style.borderPadding = first.borderPadding # + first.borderWidth
         style.borderColor = first.borderTopColor
         # If no border color is given, the text color is used (XXX Tables!)
         if (style.borderColor is None) and style.borderWidth:
             style.borderColor = first.textColor      
     if full:
         style.fontName = tt2ps(first.fontName, first.bold, first.italic)
     return style       
コード例 #11
0
ファイル: presupuesto2.py プロジェクト: pacoqueen/upy
def build_encabezado(datos_empresa = []):
    """
    Devuelve una lista de "Flowables" de reportlab con los datos de la empresa. 
    Los datos de la empresa se reciben como una lista de textos.
    """
    cabecera = []
    estilo_encabezado = ParagraphStyle("Encabezado", 
                                       parent = estilos["Heading2"])
    estilo_encabezado.rightIndent = PAGE_WIDTH * 0.25
    estilo_encabezado.alignment = enums.TA_JUSTIFY
    estilo_encabezado.spaceAfter = 0
    estilo_encabezado.spaceBefore = 4
    datos_empresa[0] = datos_empresa[0].upper()
    for linea in datos_empresa:
        if linea is datos_empresa[0]:
            estilo_encabezado.fontSize += 3
        p = Paragraph(escribe(linea), estilo_encabezado) 
        cabecera.append(p)
        estilo_encabezado.fontSize -= 1
        if estilo_encabezado.spaceAfter > -4:
            estilo_encabezado.spaceAfter -= 1
        estilo_encabezado.spaceBefore = estilo_encabezado.spaceAfter
        if linea is datos_empresa[0]:
            estilo_encabezado.fontSize -= 3
    return cabecera
コード例 #12
0
ファイル: presupuesto.py プロジェクト: pacoqueen/upy
def build_datos_cliente(datos_cliente = []):
    """
    Devuelve una lista de Flowables con las líneas recibidas como texto.
    """
    datos_c = []
    estilo_datos_c = ParagraphStyle("Cliente", 
                                    parent = estilos["Heading3"])
    estilo_datos_c.alignment = enums.TA_RIGHT
    estilo_datos_c.spaceAfter = estilo_datos_c.spaceBefore = 2
    if datos_cliente:
        try:
            datos_cliente[0] = "<strong>%s</strong>" % datos_cliente[0]
        except TypeError:
            datos_cliente = ["<strong>%s</strong>" % datos_cliente[0]] \
                            + list(datos_cliente[1:])
    tamanno_predeterminado = estilo_datos_c.fontSize
    for linea in datos_cliente:
        # ¡Esto debería hacerlo ReportLab, pero no sé por qué el markup 
        # sólo funciona con el estilo normal!
        if "<strong>" in linea:
            estilo_datos_c.fontSize += 4
        else:
            estilo_datos_c.fontSize = tamanno_predeterminado
        p = Paragraph(escribe(linea), estilo_datos_c) 
        datos_c.append(p)
    return datos_c
コード例 #13
0
ファイル: presupuesto.py プロジェクト: pacoqueen/upy
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
コード例 #14
0
ファイル: color_legend.py プロジェクト: Yajo/c2c-rd-addons
    def _add_items(self):
        """ add labels and color to the table """
        
        #X starting position
        X_pos = 0 
        if self.title != None:
            X_pos = 1
        Y_pos = 0 
        
        cpt = 0
        for i in self.items_order:


            #add the label
            txt = c2c_helper.encode_entities(self.items[i].label)
            ps = ParagraphStyle('color_legend')
            ps.alignment = TA_CENTER
            ps.fontName = self.DEFAULT_FONT
            ps.fontSize = self.DEFAULT_FONT_SIZE
            p = Paragraph(txt, ps)            
            self.table[0][cpt+X_pos] = p
            
            #add the color
            self.styles.append(('BACKGROUND', (cpt+X_pos,0), (cpt+X_pos,0), self.items[i].color))
            cpt+=1
コード例 #15
0
ファイル: color_legend.py プロジェクト: Yajo/c2c-rd-addons
 def _build_table(self):
     """ return the list of list that represent the table structure """
     
     line = []
     if self.title != None:
         txt = c2c_helper.encode_entities(self.title)
         ps = ParagraphStyle('color_legend')
         ps.alignment = TA_CENTER
         ps.fontName = self.DEFAULT_FONT
         ps.fontSize = self.DEFAULT_FONT_SIZE
         p = Paragraph(txt, ps)        
         line.append([p])
         
     for i in self.items_order:
         line.append('')
     self.table.append(line)
     #global font for the whole graphic
     self.styles.append(('FONT', (0,0), (-1,-1),self.DEFAULT_FONT, self.DEFAULT_FONT_SIZE))
     # main frame arround the whole table
     self.styles.append(('BOX', (0,0), (-1,-1), 1, "#000000"))
     #in cells, text start in the top left corner
     self.styles.append(('VALIGN', (0,0), (-1,-1), 'TOP'))
     
     if self.title != None:
         #background of the legend title
         self.styles.append(('BACKGROUND', (0,0), (0,0), "#cccccc"))
コード例 #16
0
    def get_content(self, column_data, row_values, col_values):
        """ return the content formated as defined in the constructor or in the column object """
        value = self.value
        
        if value == None or value == False:
            return ""
        
        #should we trunc the text
        if self.truncate_length != None:
            value = c2c_helper.ellipsis(value, self.truncate_length, ellipsis="[...]")

        ps = ParagraphStyle('standard_text')
        ps.fontName = self.get_font(column_data)
        ps.fontSize = self.get_font_size(column_data)
        ps.alignment = self.get_align_code(column_data)

        
        #should we indent the content
        if self.indent != None:
            ps.leftIndent = self.indent * 2 * mm
        elif type(column_data) == TextColData and column_data.indent != None:
            ps.leftIndent = column_data.indent * 2 * mm
        
        p = Paragraph(c2c_helper.encode_entities(value), ps)
        return p
コード例 #17
0
    def get_content(self, column_data, row_values, col_values):
        """return the content formated as defined in the constructor or in the column """
        
        if self.value == None or self.value == False:
            return ""
                
        format = self.DEFAULT_FORMAT
        if self.format != None:
            format = self.format
        elif type(column_data) == DateColData and column_data.format != None:
            format = column_data.format
        
        value = super(DateCellData,self).get_content(column_data, row_values, col_values)
                
        if format != None:
            value = time.strftime(format, value)
        else: 
            value = time.strftime(self.format, value) 

        
        ps = ParagraphStyle('date_cell')
        ps.fontName = self.get_font(column_data)
        ps.fontSize = self.get_font_size(column_data)
        ps.alignment = self.get_align_code(column_data)
        res = Paragraph(c2c_helper.encode_entities(value), ps)                 
        
        return res
コード例 #18
0
ファイル: albaran_multipag.py プロジェクト: pacoqueen/bbinn
def build_tabla_totales(totales):
    """
    Construye una tabla con los totales del albaranSalida.
    La tabla tiene dos filas, cabecera y desglose. La variable «totales» es 
    una lista con los totales *en el siguiente orden*:
    base imponible, porcentaje IVA en fracción de 1, y total.
    La base imponible incluye los descuentos de las LDVs y demás.
    """
    datos = [["Base imponible", "%d%% IVA" % (totales[1]*100), "Total"], 
             [totales[0], totales[2] - totales[0], totales[2]]] 
    datos = sanitize(datos)
    estilo_numeros_tabla = ParagraphStyle("Números tabla", 
                                           parent=estilos["Normal"])
    estilo_numeros_tabla.alignment = enums.TA_RIGHT
    estilo_numeros_tabla.fontSize += 2
    datos = [[Paragraph(celda, estilos["Normal"]) for celda in datos[0]] ,
             [Paragraph(celda, estilo_numeros_tabla) for celda in datos[1]]]
    tabla = TablaFija(78, 
                      2*cm,
                      datos, 
                      colWidths = (PAGE_WIDTH * (0.9/3),)*3)
    #tabla = Table(datos, 
    #              colWidths = (PAGE_WIDTH * (0.9/3),)*3) 
    tabla.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey), 
        ("LINEBELOW", (0, 0), (-1, 0), 1.0, colors.black), 
        ("BOX", (0, 0), (-1, -1), 1.0, colors.black),
        ("INNERGRID", (0, 0), (-1, -1), 1.0, colors.black), 
        ("ALIGN", (0, 0), (-1, 0), "LEFT"), 
        ]))
    return tabla
コード例 #19
0
ファイル: reports.py プロジェクト: joseamaya/tambox
 def tabla_detalle(self):
     requerimiento = self.requerimiento
     encabezados = ['Nro', 'Cantidad', 'Unidad', u'Descripción', 'Uso']
     detalles = DetalleRequerimiento.objects.filter(requerimiento=requerimiento)
     sp = ParagraphStyle('parrafos')
     sp.alignment = TA_JUSTIFY
     sp.fontSize = 8
     sp.fontName = "Times-Roman"
     lista_detalles = []
     for detalle in detalles:
         tupla_producto = [Paragraph(str(detalle.nro_detalle), sp),
                           Paragraph(str(detalle.cantidad), sp),
                           Paragraph(detalle.producto.unidad_medida.descripcion, sp),
                           Paragraph(detalle.producto.descripcion, sp),
                           Paragraph(detalle.uso, sp)]
         lista_detalles.append(tupla_producto)
     adicionales = [('', '', '', '', '')] * (15 - len(detalles))
     tabla_detalle = Table([encabezados] + lista_detalles, colWidths=[0.8 * cm, 2 * cm, 2.5 * cm, 7 * cm, 7.7 * cm])
     style = TableStyle(
         [
             ('ALIGN', (0, 0), (4, 0), 'CENTER'),
             ('GRID', (0, 0), (-1, -1), 1, colors.black),
             ('FONTSIZE', (0, 0), (-1, -1), 7),
             ('ALIGN', (4, 1), (-1, -1), 'LEFT'),
             ('VALIGN', (0, 0), (-1, -1), 'TOP'),
         ]
     )
     tabla_detalle.setStyle(style)
     return tabla_detalle
コード例 #20
0
ファイル: timebox_chart.py プロジェクト: Yajo/c2c-rd-addons
    def _add_main_scale(self):
        """ add the main scale to the table (text + style) """
        
        Y_pos = 2
        X_pos = 1
        
        
        #write the label
        ps = ParagraphStyle('scale_label')
        ps.alignment = TA_RIGHT
        ps.fontName = self.DEFAULT_FONT
        ps.fontSize = self.DEFAULT_FONT_SIZE

        title = Paragraph(self.data.scale.main_label, ps)
        self.table[Y_pos][0] = title

        
        
        ps = ParagraphStyle('scale')
        ps.alignment = TA_CENTER
        ps.fontName = self.DEFAULT_FONT
        ps.fontSize = self.DEFAULT_FONT_SIZE
        
        #reduce the size of the font for large scales
        if len(self.data.scale.scale_items) > 80: 
            ps.fontSize = 6
        
        #add labels for each scale item
        #also add weekend grayed column
        cpt = X_pos
        for item in self.data.scale.scale_items:
            p = Paragraph(item, ps)
            self.table[Y_pos][cpt] = p
            
            #handle weekemd
            if self.data.scale.weekend[cpt-X_pos]:
                #light grey columns 
                self.styles.append(('BACKGROUND', (cpt,Y_pos), (cpt,-1), "#dddddd"))
            
            
            cpt+= 1


        #light grid beetween     
        self.styles.append(('INNERGRID', (X_pos,Y_pos), (-1,Y_pos), 0.2, "#bbbbbb"))
        #line that separate the dates and the datas
        self.styles.append(('LINEBELOW', (0, Y_pos), (-1,Y_pos), 1, colors.black))
コード例 #21
0
ファイル: log.py プロジェクト: dairdr/notes
	def drawResume(self, canvas, doc):
		# First table
		style = ParagraphStyle(name='Style')
		style.fontName = 'Helvetica-Bold'
		style.fontSize = 10
		style.alignment = TA_CENTER
		data = [
			[Paragraph('INFORME ACADÉMICO DEL %s' % self.time.upper(), style)],
			['SEDE PRINCIPAL BACHILLERATO']
		]
		LIST_STYLE = TableStyle([
			('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
			('BOX', (0,0), (-1,-1), 0.25, colors.black),
			('TEXTCOLOR',(0,0),(-1,-1),colors.black),
			('ALIGN', (0,0), (-1,-1), 'CENTER'),
			('BACKGROUND', (0, 0), (-1, -1), colors.gray),
			('FONTSIZE', (-1, -1), (-1, -1), 8),
			('VALIGN',(0,0),(-1,-1),'MIDDLE')
		])
		table = Table(data, colWidths='*', rowHeights=0.2 * inch, style=LIST_STYLE)
		w, h = table.wrap(doc.width, 0)

		# Second table
		data = [
			[self.getResumeFirstColum(), self.getSecondColum(), self.getThirdColum(), self.getFourthColum()]
		]
		LIST_STYLE = TableStyle([
			('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
			('BOX', (0, 0), (-1, -1), 0.25, colors.black),
			('BACKGROUND', (0, 0), (-1, -1), colors.gray),
			('TOPPADDING', (0, 0), (-1, -1), 0),
			('BOTTOMPADDING', (0, 0), (-1, -1), 0),
			('LEFTPADDING', (0, 0), (-1, -1), 0),
			('RIGHTPADDING', (0, 0), (-1, -1), 0),
			('FONTSIZE', (0, 0), (-1, -1), 8),
			('ALIGN', (0, 0), (-1, -1), 'CENTER'),
			('VALIGN',(0, 0),(-1, -1),'TOP')
		])
		colWidths = [3*inch, 1.2*inch, 1.4*inch, '*']
		table2 = Table(data, colWidths=colWidths, style=LIST_STYLE)
		w, h = table2.wrap(doc.width, 0)

		wrapper_style = TableStyle([
			('ALIGN', (0, 0), (-1, -1), 'CENTER'),
			('VALIGN',(0, 0),(-1, -1),'MIDDLE'),
			('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
			('BOX', (0, 0), (-1, -1), 0.25, colors.black),
			('TOPPADDING', (0, 0), (-1, -1), 0),
			('BOTTOMPADDING', (0, 0), (-1, -1), 0),
			('LEFTPADDING', (0, 0), (-1, -1), 0),
			('RIGHTPADDING', (0, 0), (-1, -1), 0),
		])
		data = [
			[table],
			[table2]
		]
		wrapper = Table(data, colWidths='*', style=wrapper_style)
		w, h = wrapper.wrap(doc.width, 0)
		wrapper.drawOn(canvas, doc.leftMargin, doc.height + 80)
コード例 #22
0
    def addPara(self, force=False):

        # Cleanup the trail
        for frag in reversed(self.fragList):
            frag.text = frag.text.rstrip()
            if frag.text:
                break

        if force or (self.text.strip() and self.fragList):

            # Strip trailing whitespaces
            # for f in self.fragList:
            #    f.text = f.text.lstrip()
            #    if f.text:
            #        break
            # self.fragList[-1].lineBreak = self.fragList[-1].text.rstrip()

            # Update paragraph style by style of first fragment
            first = self.fragBlock
            style = ParagraphStyle("default%d" % self.UID(), keepWithNext=first.keepWithNext)
            style.fontName = first.fontName
            style.fontSize = first.fontSize
            style.leading = max(first.leading, first.fontSize * 1.25)
            style.backColor = first.backColor
            style.spaceBefore = first.spaceBefore
            style.spaceAfter = first.spaceAfter
            style.leftIndent = first.leftIndent
            style.rightIndent = first.rightIndent
            style.firstLineIndent = first.firstLineIndent
            style.alignment = first.alignment

            style.bulletFontName = first.fontName
            style.bulletFontSize = first.fontSize
            style.bulletIndent = first.bulletIndent

            style.borderWidth = max(
                first.borderLeftWidth, first.borderRightWidth, first.borderTopWidth, first.borderBottomWidth
            )
            style.borderPadding = first.borderPadding  # + first.borderWidth
            style.borderColor = first.borderTopColor
            # borderRadius: None,

            # print repr(self.text.strip()), style.leading, "".join([repr(x.text) for x in self.fragList])

            # print first.leftIndent, first.listStyleType,repr(self.text)

            # Add paragraph to story
            para = PmlParagraph(
                self.text, style, frags=self.fragAnchor + self.fragList, bulletText=copy.copy(first.bulletText)
            )
            para.outline = frag.outline
            para.outlineLevel = frag.outlineLevel
            para.outlineOpen = frag.outlineOpen
            self.addStory(para)

            self.fragAnchor = []
            first.bulletText = None

        self.clearFrag()
コード例 #23
0
ファイル: presupuesto2.py プロジェクト: pacoqueen/ginn
def build_condicionado(condicionado):
    a_derecha = ParagraphStyle("A derecha", 
                                parent = estilos["Normal"])
    a_derecha.alignment = enums.TA_LEFT
    a_derecha.fontName = "Courier"
    a_derecha.fontSize = 13
    texto_condicionado = "Condiciones particulares: " + condicionado
    return Paragraph(texto_condicionado, a_derecha)
コード例 #24
0
ファイル: albaran_porte.py プロジェクト: pacoqueen/upy
def build_todavia_mas_texto():
    """
    Construye más texto genérico de la carta de portes.
    """
    estilo_texto = ParagraphStyle("Texto", parent=estilos["Normal"])
    estilo_texto.alignment = enums.TA_JUSTIFY
    estilo_texto.firstLineIndent = 24
    estilo_texto.fontSize = 12
    texto = """
    Transporte que no excede de los límites establecidos en el capítulo 1.1.3.6.
    """
    estilo_texto2 = ParagraphStyle("Texto2", parent=estilo_texto)
    estilo_texto2.alignment = enums.TA_CENTER
    estilo_texto2.firstLineIndent = 0
    # estilo_texto2.fontSize = 8
    p = Paragraph(escribe(texto), estilo_texto2)
    return p
コード例 #25
0
def _ptoTestCase(self):
    """PTO stands for Please Turn Over and is a means for
    specifying content to be inserted when stuff goes over a page.
    This makes one long multi-page paragraph."""

    # Build story.
    story = []
    def fbreak(story=story):
        story.append(FrameBreak())

    styleSheet = getSampleStyleSheet()
    H1 = styleSheet['Heading1']
    H1.pageBreakBefore = 0
    H1.keepWithNext = 0

    bt = styleSheet['BodyText']
    pto = ParagraphStyle('pto',parent=bt)
    pto.alignment = TA_RIGHT
    pto.fontSize -= 1
    def ColorParagraph(c,text,style):
        return Paragraph('<para color="%s">%s</para>' % (c,text),style)

    def ptoblob(blurb,content,trailer=None,header=None, story=story, H1=H1):
        if type(content) not in (type([]),type(())): content = [content]
        story.append(PTOContainer([Paragraph(blurb,H1)]+list(content),trailer,header))

    t0 = [ColorParagraph('blue','Please turn over', pto )]
    h0 = [ColorParagraph('blue','continued from previous page', pto )]
    t1 = [ColorParagraph('red','Please turn over(inner)', pto )]
    h1 = [ColorParagraph('red','continued from previous page(inner)', pto )]
    ptoblob('First Try at a PTO',[Paragraph(text0,bt)],t0,h0)
    fbreak()
    c1 = Table([('alignment', 'align\012alignment'),
                ('bulletColor', 'bulletcolor\012bcolor'),
                ('bulletFontName', 'bfont\012bulletfontname'),
                ('bulletFontSize', 'bfontsize\012bulletfontsize'),
                ('bulletIndent', 'bindent\012bulletindent'),
                ('firstLineIndent', 'findent\012firstlineindent'),
                ('fontName', 'face\012fontname\012font'),
                ('fontSize', 'size\012fontsize'),
                ('leading', 'leading'),
                ('leftIndent', 'leftindent\012lindent'),
                ('rightIndent', 'rightindent\012rindent'),
                ('spaceAfter', 'spaceafter\012spacea'),
                ('spaceBefore', 'spacebefore\012spaceb'),
                ('textColor', 'fg\012textcolor\012color')],
            style = [
                ('VALIGN',(0,0),(-1,-1),'TOP'),
                ('INNERGRID', (0,0), (-1,-1), 0.25, black),
                ('BOX', (0,0), (-1,-1), 0.25, black),
                ],
            )
    ptoblob('PTO with a table inside',c1,t0,h0)
    fbreak()
    ptoblob('A long PTO',[Paragraph(text0+' '+text1,bt)],t0,h0)
    fbreak()
    ptoblob('2 PTO (inner split)',[ColorParagraph('pink',text0,bt),PTOContainer([ColorParagraph(black,'Inner Starts',H1),ColorParagraph('yellow',text2,bt),ColorParagraph('black','Inner Ends',H1)],t1,h1),ColorParagraph('magenta',text1,bt)],t0,h0)
    _showDoc('test_platypus_pto.pdf',story)
コード例 #26
0
    def get_title(self):
        """return the title of the col"""

        ps = ParagraphStyle('header')
        ps.fontName = self.header_font
        ps.fontSize = self.header_font_size
        ps.alignment = self.get_align_code()
        
        return Paragraph(self._title, ps)
コード例 #27
0
ファイル: context.py プロジェクト: AntycSolutions/xhtml2pdf
    def toParagraphStyle(self, first):
        style = ParagraphStyle('default%d' % self.UID(), keepWithNext=first.keepWithNext)
        style.fontName = first.fontName
        style.fontSize = first.fontSize
        style.letterSpacing = first.letterSpacing
        style.leading = max(first.leading + first.leadingSpace, first.fontSize * 1.25)
        style.backColor = first.backColor
        style.spaceBefore = first.spaceBefore
        style.spaceAfter = first.spaceAfter
        style.leftIndent = first.leftIndent
        style.rightIndent = first.rightIndent
        style.firstLineIndent = first.firstLineIndent
        style.textColor = first.textColor
        style.alignment = first.alignment
        style.bulletFontName = first.bulletFontName or first.fontName
        style.bulletFontSize = first.fontSize
        style.bulletIndent = first.bulletIndent
        style.wordWrap = first.wordWrap

        # Border handling for Paragraph

        # Transfer the styles for each side of the border, *not* the whole
        # border values that reportlab supports. We'll draw them ourselves in
        # PmlParagraph.
        style.borderTopStyle = first.borderTopStyle
        style.borderTopWidth = first.borderTopWidth
        style.borderTopColor = first.borderTopColor
        style.borderBottomStyle = first.borderBottomStyle
        style.borderBottomWidth = first.borderBottomWidth
        style.borderBottomColor = first.borderBottomColor
        style.borderLeftStyle = first.borderLeftStyle
        style.borderLeftWidth = first.borderLeftWidth
        style.borderLeftColor = first.borderLeftColor
        style.borderRightStyle = first.borderRightStyle
        style.borderRightWidth = first.borderRightWidth
        style.borderRightColor = first.borderRightColor

        # If no border color is given, the text color is used (XXX Tables!)
        if (style.borderTopColor is None) and style.borderTopWidth:
            style.borderTopColor = first.textColor
        if (style.borderBottomColor is None) and style.borderBottomWidth:
            style.borderBottomColor = first.textColor
        if (style.borderLeftColor is None) and style.borderLeftWidth:
            style.borderLeftColor = first.textColor
        if (style.borderRightColor is None) and style.borderRightWidth:
            style.borderRightColor = first.textColor

        style.borderPadding = first.borderPadding

        style.paddingTop = first.paddingTop
        style.paddingBottom = first.paddingBottom
        style.paddingLeft = first.paddingLeft
        style.paddingRight = first.paddingRight
        style.fontName = tt2ps(first.fontName, first.bold, first.italic)

        return style
コード例 #28
0
ファイル: views.py プロジェクト: efornal/mollys
def parag_style():
    from  reportlab.lib.styles import ParagraphStyle
    from reportlab.lib.enums import TA_LEFT
    style = ParagraphStyle('test')
    style.textColor = 'black'
    style.borderColor = 'black'
    style.borderWidth = 0
    style.alignment = TA_LEFT
    style.fontSize = 9
    return style
コード例 #29
0
ファイル: factura_multipag.py プロジェクト: pacoqueen/upy
def build_tabla_vencimientos(observaciones, vencimientos, forma_de_pago):
    """
    Los tres parámetros pueden ser una única cadena o una lista de cadenas.
    Si es lo segundo, cada elemento irá en una celda independiente.
    """
    datos = [["Observaciones", "Vencimientos", "Forma de pago"]]
    for columna, lista in ((0, observaciones),
                           (1, vencimientos),
                           (2, forma_de_pago)):
        if isinstance(lista, str):
            lista = [lista]
        fila = 1
        for elemento in lista:
            try:
                datos[fila][columna] = elemento
            except IndexError:
                datos.append(["", "", ""])
                datos[fila][columna] = elemento
            finally:
                fila += 1
    datos = sanitize(datos)
    estilo_cont_tabla = ParagraphStyle("Contenido tabla",
                                       parent=estilos["Normal"])
    estilo_cont_tabla.alignment = enums.TA_JUSTIFY
    estilo_cont_tabla.fontSize += 2
    _datos = []
    fila = []
    for celda in datos[0]:
        #fila.append(Paragraph(celda, estilos["Normal"]))
        fila.append(escribe(celda))
    _datos.append(fila)
    for fila_datos in datos[1:]:
        fila = []
        for celda in fila_datos:
             fila.append(Paragraph(escribe(celda), estilo_cont_tabla))
        _datos.append(fila)
    datos = _datos
    tabla = TablaFija(78,
                      3*cm,
                      datos,
                      colWidths = (PAGE_WIDTH * 0.9 * 0.5,
                                   PAGE_WIDTH * 0.9 * 0.25,
                                   PAGE_WIDTH * 0.9 * 0.25))
    #tabla = Table(datos,
    #              colWidths = (PAGE_WIDTH * (0.9/3),)*3)
    tabla.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey),
        ("LINEBELOW", (0, 0), (-1, 0), 1.0, colors.black),
        ("BOX", (0, 0), (-1, -1), 1.0, colors.black),
        ("LINEBEFORE", (1, 1), (1, -1), 0.5, colors.black),
        ("LINEBEFORE", (2, 1), (2, -1), 0.5, colors.black),
        #("INNERGRID", (0, 0), (-1, -1), 1.0, colors.black),
        ("ALIGN", (0, 0), (-1, 0), "CENTER"),
        ]))
    return tabla
コード例 #30
0
ファイル: presupuesto2.py プロジェクト: pacoqueen/ginn
def build_texto_riesgo(texto_riesgo):
    # a_derecha = ParagraphStyle("A derecha", 
    #                             parent = estilos["Normal"])
    # a_derecha.alignment = enums.TA_RIGHT
    # a_derecha.fontName = "Courier"
    # a_derecha.fontSize = 8
    estilo_texto = ParagraphStyle("Texto", 
                                  parent = estilos["Normal"])
    estilo_texto.alignment = enums.TA_JUSTIFY
    estilo_texto.firstLineIndent = 24
    return Paragraph(texto_riesgo, estilo_texto) # , a_derecha)     # CWT
コード例 #31
0
    def addPara(self, force=False):

        # Cleanup the trail
        for frag in reversed(self.fragList):
            frag.text = frag.text.rstrip()
            if frag.text:
                break

        if force or (self.text.strip() and self.fragList):

            # Strip trailing whitespaces
            #for f in self.fragList:
            #    f.text = f.text.lstrip()
            #    if f.text:
            #        break
            #self.fragList[-1].lineBreak = self.fragList[-1].text.rstrip()

            # Update paragraph style by style of first fragment
            first = self.fragBlock
            style = ParagraphStyle('default%d' % self.UID(),
                                   keepWithNext=first.keepWithNext)
            style.fontName = first.fontName
            style.fontSize = first.fontSize
            style.leading = max(first.leading, first.fontSize * 1.25)
            style.backColor = first.backColor
            style.spaceBefore = first.spaceBefore
            style.spaceAfter = first.spaceAfter
            style.leftIndent = first.leftIndent
            style.rightIndent = first.rightIndent
            style.firstLineIndent = first.firstLineIndent
            style.alignment = first.alignment

            style.bulletFontName = first.fontName
            style.bulletFontSize = first.fontSize
            style.bulletIndent = first.bulletIndent

            style.borderWidth = max(first.borderLeftWidth,
                                    first.borderRightWidth,
                                    first.borderTopWidth,
                                    first.borderBottomWidth)
            style.borderPadding = first.borderPadding  # + first.borderWidth
            style.borderColor = first.borderTopColor
            # borderRadius: None,

            # print repr(self.text.strip()), style.leading, "".join([repr(x.text) for x in self.fragList])

            # print first.leftIndent, first.listStyleType,repr(self.text)

            # Add paragraph to story
            para = PmlParagraph(self.text,
                                style,
                                frags=self.fragAnchor + self.fragList,
                                bulletText=copy.copy(first.bulletText))
            para.outline = frag.outline
            para.outlineLevel = frag.outlineLevel
            para.outlineOpen = frag.outlineOpen
            self.addStory(para)

            self.fragAnchor = []
            first.bulletText = None

        self.clearFrag()
コード例 #32
0
ファイル: rlcli.py プロジェクト: Record360/hexapdf-latest
                         onPage=onFirstPage,
                         pagesize=self.pagesize)
        ])
        BaseDocTemplate.build(self, flowables, canvasmaker=canvasmaker)


font = 'Times-Roman'
if len(sys.argv) == 5:
    pdfmetrics.registerFont(TTFont('font', sys.argv[4]))
    font = 'font'

ParaStyle = ParagraphStyle("default")
ParaStyle.fontName = font
ParaStyle.fontsize = 10
ParaStyle.leading = 11.16
ParaStyle.alignment = TA_LEFT
ParaStyle.allowOrphans = 1
ParaStyle.allowWidows = 1
ParaStyle.spaceBefore = 0
ParaStyle.spaceAfter = 0
ParaStyle.leftIndent = 0
ParaStyle.rightIndent = 0

height = 1000
width = int(sys.argv[2])
Elements = []


def p(txt, style=ParaStyle):
    Elements.append(Paragraph(txt, style))
コード例 #33
0
def lista_clientes_pdf(request):
    print "Genero el PDF"
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Listado-de-Proovedores.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    #response['Content-Disposition'] = 'attachment; filename=%s-%s/%s/%s.pdf'%(pdf_name, tiempo.day,tiempo.month, tiempo.year)
    buff = BytesIO()

    doc = SimpleDocTemplate(
        buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
    )
    styles = getSampleStyleSheet()
    lista = []
    lista.append(logo_pdf())
    fecha = Paragraph(
        '<b><i>Fecha: %s/%s/%s</i></b>' %
        (tiempo.day, tiempo.month, tiempo.year), styles['Normal'])

    lista.append(Spacer(0, 40))
    lista.append(fecha)

    lista.append(Spacer(0, 10))
    style = ParagraphStyle('Heading1')
    style.textColor = 'black'
    style.alignment = TA_CENTER
    style.fontSize = 18
    style.spaceAfter = 15
    style.spaceBefore = 30
    style.spaceAfter = 5
    style.leading = 20
    style.bulletIndent = 0
    style.allowOrphans = 0
    style.bulletFontSize = 10
    style.fontName = 'Helvetica'
    header = Paragraph("<b>Listado de Clientes</b>".upper(), style)
    lista.append(header)
    lista.append(Spacer(0, 10))

    #************Tabla****************************
    style_table = ParagraphStyle('Default')
    #style_table.textColor= 'black'
    #style_table.alignment= TA_CENTER
    style_table.fontSize = 10
    style_table.spaceAfter = 15
    style_table.spaceBefore = 0
    style_table.spaceAfter = 0
    style_table.leading = 20  # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName = 'Times-Roman'

    style_table.bulletAnchor = 'start',
    cont = 0
    array = []
    headings = ('N', 'CODIGO', 'NOMBRE', 'CI/RIF', 'DOMICILIO FISCAL',
                'TELEFONO', 'CELULAR')
    for p in Cliente.objects.filter(
            habilitado=True).order_by('fecha_agregado'):
        cont += 1
        array.append([
            Paragraph(str(cont), style_table),
            Paragraph(p.codigo_en_sistema(), style_table),
            Paragraph(p.nombre_o_razon_social.title(), style_table),
            Paragraph(p.documentoId.title(), style_table),
            Paragraph(p.domicilio_fiscal.title(), style_table),
            Paragraph(p.telefono, style_table),
            Paragraph(p.celular, style_table)
        ])

    t = Table([headings] + array)
    t.setStyle(
        TableStyle([
            ('GRID', (0, 0), (len(headings), -1), 2, colors.grey),
            ('LINEBELOW', (1, 0), (-1, 0), 2, colors.grey),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor(0x41a02a)),
            ('BACKGROUND', (0, 1), (len(headings), len(array)),
             colors.HexColor(0xdbf706)),
            #('BACKGROUND', (0, 0), (-3, 0), colors.yellow),

            #('BACKGROUND', (0, 0), (-1, 0), colors.palegreen)d1e82af7
        ]))
    lista.append(t)
    doc.build(lista)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #34
0
ファイル: test_issues.py プロジェクト: zlapp/reportlab-mirror
    def test_issue183(self):
        '''issue 183 raised by Marius Gedminas'''
        from reportlab.pdfgen.canvas import Canvas
        from reportlab.platypus.paragraph import Paragraph
        from reportlab.lib.styles import ParagraphStyle
        from reportlab.pdfbase.pdfmetrics import registerFont
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.lib.enums import TA_JUSTIFY
        sty = ParagraphStyle('A')
        sty.fontSize = 11
        sty.leading = sty.fontSize*1.2
        sty.fontName = 'Helvetica'
        sty.alignment = TA_JUSTIFY
        canv = Canvas(outputfile('test_issue183.pdf'))
        aW = 440
        text = u'''AAAAAAAAAAAA BBBBB C Dddd EEEEEEEE\xa0\u2014 FF GGGGGG HHHHHHHHH III JJJJJJJJJ KKK
LLLLLLLLL MMMMMM NNNNN O PPPPPP Q RRRRR SSSSSS TTTTTTTTTTT. UUUUUUU VVVVVVVV
WWWWWWWWWWWW XXX YYYYYY ABBBBB BCCCCCCCCCCC.'''
        def do1(x,y,text,sty):
            p = Paragraph(text,sty)
            w,h=p.wrap(aW,1000000)
            y -= h
            p.drawOn(canv,x,y)
            canv.saveState()
            canv.setLineWidth(0.5)
            canv.setStrokeColor((1,0,0))
            canv.rect(x,y,aW,h,stroke=1,fill=0)
            canv.restoreState()
            return y

        def do2(x,y,text,sty):
            y = do1(x,y,text,sty)
            return do1(x,y-10,text.replace(u'\xa0\u2014',u'&nbsp;&mdash;'),sty)

        fonts = set()
        fonts.add('Helvetica')
        for fontName, fontPath in (('Vera','Vera.ttf'),
                ('TTFTimes','/usr/share/fonts/TTF/times.ttf')):
            try:
                registerFont(TTFont(fontName, fontPath))
                fonts.add(fontName)
            except:
                pass

        y = canv._pagesize[1] - 72
        y = do2(72,y,text,sty)
        if 'Vera' in fonts:
            styv = sty.clone('AV',fontName='Vera')
            y = do2(72,y-10,text,styv)

        if 'TTFTimes' in fonts:
            styv = sty.clone('AV',fontName='TTFTimes')
            y = do2(72,y-10,text,styv)

        text = u'|A B C D E F G H I J K L|'
        y -= 13.1
        offs = None
        for fontName in 'Helvetica Vera TTFTimes'.split():
            if fontName not in fonts: continue
            for ws in 0, -1, 1:
                for s in (u' ',u'\xa0'):
                    canv.saveState()
                    canv.setFont('Courier',11)
                    lab = '%-9s ws=%2d %s:' % (fontName,ws,s==u' ' and 'soft' or 'hard')
                    if offs == None:
                        offs = 72+canv.stringWidth(lab)+2
                    canv.drawString(72,y,lab)
                    canv.setFont(fontName,11)
                    canv.drawString(offs,y,text.replace(u' ',s),wordSpace=ws)
                    canv.restoreState()
                    y -= 13.1

        canv.showPage()
        canv.save()
コード例 #35
0
ファイル: recepcion_pdf.py プロジェクト: jose1403/tonino
def lista_recepcion_pdf(request, lista_pk, queryset):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Factura-Recepcion.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    #response['Content-Disposition'] = 'attachment; filename=%s-%s/%s/%s.pdf'%(pdf_name, tiempo.day,tiempo.month, tiempo.year)
    buff = BytesIO()
    datos = DATOS_DE_LA_EMPRESA.objects.get(pk=1)
    doc = SimpleDocTemplate(
        buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
    )
    cambio = False
    if type(lista_pk) == int:
        lista_pk = [lista_pk]
        cambio = True
    model = queryset.filter(id__in=lista_pk)

    lista = []
    styles = getSampleStyleSheet()
    lista.append(logo_pdf())
    fecha = Paragraph(
        '<b><i>Fecha: %s/%s/%s</i></b>' %
        (tiempo.day, tiempo.month, tiempo.year), styles['Normal'])
    lista.append(Spacer(0, 40))
    lista.append(fecha)

    lista.append(Spacer(0, 10))
    style = ParagraphStyle('Heading1')
    style.textColor = 'black'
    style.alignment = TA_CENTER
    style.fontSize = 18
    style.spaceAfter = 15
    style.spaceBefore = 30
    style.spaceAfter = 5
    style.leading = 20
    style.bulletIndent = 0
    style.allowOrphans = 0
    style.bulletFontSize = 10
    style.fontName = 'Helvetica'
    header = Paragraph("<b>Listado de Recepciones</b>".upper(), style)
    lista.append(header)
    lista.append(Spacer(0, 10))

    #************Tabla****************************
    style_table = ParagraphStyle('Default')
    #style_table.textColor= 'black'
    style_table.alignment = TA_CENTER
    style_table.fontSize = 10
    style_table.spaceAfter = 15
    style_table.spaceBefore = 0
    style_table.spaceAfter = 0
    style_table.leading = 10  # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName = 'Times-Roman'

    style_table.bulletAnchor = 'start',
    cont = 0
    array = []

    headings = ('CODIGO', 'PRODUCTO', 'CICLO', 'PROOVEDOR', 'CANTIDAD(H/I)',
                'FECHA', 'TOTAL(Bs).')
    for p in model:
        pago = PagoRecepcion.objects.get(recepcion=p)
        total = TotalRecepcion.objects.get(ingreso=pago)
        cont += 1
        array.append([
            Paragraph(p.codigo_en_sistema(), style_table),
            Paragraph(
                '%s (<font size=8>%s-%s</font>)' %
                (p.producto.nombre.upper(), p.variedad.nombre.upper(),
                 p.tipo.nombre.upper()), style_table),
            Paragraph(p.ciclo_asociado.codigo_en_sistema(), style_table),
            Paragraph('%s' % p.proovedor.nombre_o_razon_social.upper(),
                      style_table),
            Paragraph('%s Kg.' % intcomma(total.cantidad_real), style_table),
            Paragraph(
                '%s/%s/%s' % (p.fecha_agregado.day, p.fecha_agregado.month,
                              p.fecha_agregado.year), style_table),
            Paragraph('%s' % (intcomma(total.total_Bs)), style_table)
        ])

    t = Table([headings] + array)
    t.setStyle(
        TableStyle([
            ('GRID', (0, 0), (len(headings), -1), 2, colors.grey),
            ('LINEBELOW', (1, 0), (-1, 0), 2, colors.grey),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor(0x41a02a)),
            ('BACKGROUND', (0, 1), (len(headings), len(array)),
             colors.HexColor(0xdbf706)),
            #('BACKGROUND', (0, 0), (-3, 0), colors.yellow),

            #('BACKGROUND', (0, 0), (-1, 0), colors.palegreen)d1e82af7
        ]))
    lista.append(t)
    #recepcion= Recepcion.objects.get(pk=pk)

    doc.build(lista)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #36
0
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, A5
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib import utils

from django.core.files.base import ContentFile
from django.conf import settings
from django.db import models

heading_style = ParagraphStyle('Heading')
heading_style.textColor = 'black'
heading_style.fontSize = 25
heading_style.alignment = TA_CENTER

sub_heading_style = ParagraphStyle('Sub-Heading')
sub_heading_style.textColor = 'black'
sub_heading_style.fontSize = 13
sub_heading_style.alignment = TA_CENTER


class PDFBuilder():
    pdf_type = 'general_pdf'
    page_size = A4
    sample_style_sheet = getSampleStyleSheet()

    def __init__(self, font_name='Roboto'):
        self.file_buffer = StringIO()
        self.doc = SimpleDocTemplate(self.file_buffer,
コード例 #37
0
    def __make_quiz(self, words, start_date, page_max = 10, filter = True):
        conn = sqlite3.connect('dict.db')
        cursor = conn.cursor()
        words_list = set()
        words_meaning = {}

        dictcn = dict_cn()
        for word in words:
            dict_word, meaning = dictcn.search(word)
            words_meaning[dict_word] = meaning
            words_list.add(dict_word)

        if filter :
            words_variant = self.words_with_tag('复数')
            words_variant = words_variant|self.words_with_tag('第三人称单数')
            words_variant = words_variant|self.words_with_tag('过去式')
            words_variant = words_variant|self.words_with_tag('过去分词')
            words_variant = words_variant|self.words_with_tag('现在分词')
            words_variant = words_variant|self.words_with_tag('比较级')
            words_variant = words_variant|self.words_with_tag('最高级')

            words_proper = self.words_with_tag('姓氏')
            words_proper = words_proper|self.words_with_tag('人名')
            words_proper = words_proper|self.words_with_tag('国名')
            words_proper = words_proper|self.words_with_tag('美国州名')
            words_proper = words_proper|self.words_with_tag('城市')
            words_proper = words_proper|self.words_with_tag('缩写')

            words_first_letter_capital = self.words_with_tag('首字母大写')

            word_count = len(words_list)

            self.__print_word_list(words_list & words_variant)
            words_list = words_list - words_variant  #去除变体的单词
            print('剔除 {} 个变体单词,剩余 {} 个单词'.format(word_count - len(words_list), len(words_list)))
            word_count = len(words_list)

            self.__print_word_list(words_list & words_proper)
            words_list = words_list - words_proper #去除专用单词,如:国名、地名、人名等
            print('剔除 {} 个国名、地名等专有单词,剩余 {} 个单词'.format(word_count - len(words_list), len(words_list)))
            word_count = len(words_list)

            self.__print_word_list(words_list & words_first_letter_capital)
            words_list = words_list - words_first_letter_capital #去除首字母大写单词
            print('剔除 {} 个首字母大写单词,剩余 {} 个单词'.format(word_count - len(words_list), len(words_list)))

        self.__print_word_list(words_list)
        print('最终输出 {} 个单词'.format(len(words_list)))

        words_dict = {}
        for word in words_list:
            words_dict[word] = words_meaning[word]

        chinese_number = ['0', '①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩']
        roman_number = ['0', 'Ⅰ.', 'Ⅱ.', 'Ⅲ.', 'Ⅳ.', 'Ⅴ.', 'Ⅵ.', 'Ⅶ.', 'Ⅷ.', 'Ⅸ.', 'Ⅹ.']
        pdfmetrics.registerFont(TTFont("SimSun", "SimSun.ttf"))

        words_per_page = 6
        quiz_words = {}
        quiz_meanings = {}
        quiz_meanings_disorder = {}
        inside_page_index = 0
        page_no = 0

        pdf_filename = ""
        txt_filename = ""
        canv = None
        for word in words_dict.keys():
            if page_no % page_max == 0:
                if round(page_no / page_max) > 0:
                    canv.save()

                #获取quiz的日期字符串,此处借用sqlite来进行计算
                sql = "select strftime('%Y%m%d', date(?, ?)) "
                #print(sql, start_date, '+{} day'.format(round(page_no / page_max)) )
                cursor.execute(sql, (start_date, '+{} day'.format(round(page_no / page_max)), ))
                row = cursor.fetchone()
                cmp_date_str = row[0] #YYYYMMDD格式的日期字符串

                pdf_filename = "words/plan/quiz-{}.pdf".format(cmp_date_str)
                txt_filename = "words/plan/quiz-{}.txt".format(cmp_date_str)
                canv = canvas.Canvas(pdf_filename)

            if inside_page_index == words_per_page:
                inside_page_index = 0
                page_no += 1

                style = ParagraphStyle(name='normal')
                style.fontSize = 20
                style.fontName = "SimSun"
                style.alignment = 1

                display_page_no = page_no % page_max
                if display_page_no == 0:
                    display_page_no = page_max

                p = Paragraph("单词练习-{}".format(display_page_no), style)
                p.wrap(210 * mm, 35 * mm)
                p.drawOn(canv, 0, 292 * mm)

                with open(txt_filename, 'a') as f:
                    f.write('##Page-{}'.format(display_page_no) + '\n')

                canv.setFont("SimSun", 18)

                quiz_mapping, reversed_quiz_mapping = self.__create_random_mapping_for_quiz(words_per_page)
                for i in range(0, words_per_page):
                    quiz_meanings_disorder[i] = quiz_meanings[quiz_mapping[i]]

                for i in range(0, words_per_page):
                    style = ParagraphStyle(name='normal')
                    style.backColor = HexColor(0xEEEEEE)
                    style.fontSize = 18
                    style.fontName = "SimSun"
                    style.leading = 18
                    p = Paragraph('{}{}'.format(roman_number[i + 1], quiz_words[i]), style)
                    word_width, word_height = p.wrap(75 * mm, 40 * mm)
                    p.drawOn(canv, 0.5 * mm, (270 - i * 45) * mm - word_height)

                    style = ParagraphStyle(name='normal')
                    style.backColor = HexColor(0xEEEEEE)
                    style.fontSize = 10
                    style.fontName = "SimSun"
                    style.leading = 18
                    p = Paragraph('Answer:<br/><br/><br/>_________________________________________', style)
                    answer_width, answer_height = p.wrap(75 * mm, 40 * mm)
                    p.drawOn(canv, 0.5 * mm, (270 - i * 45) * mm - word_height - answer_height - 10)

                    with open(txt_filename, 'a') as f:
                        f.write('{}|word={}|meaning={}|result(P/F)=\n'.format(roman_number[i + 1], quiz_words[i], chinese_number[reversed_quiz_mapping[i] + 1]))
                        #print('{}word={}|meaning={}'.format(roman_number[i + 1], quiz_words_disorder[i], chinese_number[reversed_quiz_mapping[i] + 1]))

                with open(txt_filename, 'a') as f:
                    f.write('\n')

                for i in range(0, words_per_page):
                    style = ParagraphStyle(name='normal')
                    style.backColor = HexColor(0xEEEEEE)
                    style.fontSize = 18
                    style.fontName = "SimSun"
                    style.leading = 18

                    p = Paragraph('{}{}'.format(chinese_number[i + 1], quiz_meanings_disorder[i]), style)
                    meaning_width, meaning_height = p.wrap(110 * mm, 40 * mm)
                    p.drawOn(canv, 100 * mm, (270 - i * 45) * mm - meaning_height)

                    #print('{}meaning={}'.format(chinese_number[i+1], quiz_meanings_disorder[i]))

                canv.showPage()
                canv.setFont("SimSun", 18)

            quiz_words[inside_page_index] = word
            quiz_meanings[inside_page_index] = words_dict[word]
            inside_page_index += 1

        canv.save()
コード例 #38
0
def providencia(documento):
    mes_letras = {
        1: 'Enero',
        2: 'Febrero',
        3: 'Marzo',
        4: 'Abril',
        5: 'Mayo',
        6: 'Junio',
        7: 'Julio',
        8: 'Agosto',
        9: 'Septiembre',
        10: 'Octubre',
        11: 'Noviembre',
        12: 'Diciembre',
    }

    def text_to_bold(text):
        return u'''<b><font size=12>{}</font></b> <br/>'''.format(text)

    def print_text_bold(text, x, y, pdf):
        p = ParagraphStyle('test')
        p.textColor = 'black'
        p.alignment = TA_LEFT
        p.fontSize = 8
        p.leading = 9
        para = Paragraph(text_to_bold(unicode(text)), p)
        para.wrapOn(pdf, 300, 50)
        para.drawOn(pdf, x, y)

    def get_fecha():
        from datetime import date

        d = date.today()
        fecha = "Caracas, {dia_letra} ({dia}) de {mes} de {anyo}".format(
            dia_letra=NumToWord.get_month_words(d.day),
            dia=str(d.day),
            mes=mes_letras[d.month],
            anyo=str(d.year))
        return fecha

    domicilio, gerente, supervisor, funcionarios, apoyo = documento_info(
        documento)

    texto = text_providencia(supervisor, funcionarios, apoyo)

    p = ParagraphStyle('test')
    p.textColor = 'black'
    p.alignment = TA_JUSTIFY
    p.fontSize = 10
    p.leading = 12
    para = Paragraph(text_to_bold(unicode(domicilio)), p)
    para_texto = Paragraph(unicode(texto), p)

    output = PdfFileWriter()
    input = PdfFileReader(
        file(
            os.path.join(settings.PDF_ROOT, 'verificacion', 'PROVIDENCIA.pdf'),
            'rb'))
    # create response object
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Verificacion_Providencia.pdf'

    fecha = get_fecha()
    # get number of pages
    num_pages = input.getNumPages()

    for page in xrange(num_pages - 1):
        new_page = False
        buffer = StringIO()  # create string buffer for PDF
        pdf = canvas.Canvas(buffer, pagesize=letter)
        print_text_bold(unicode(documento.pst.razon_social), 220, 768 + 2, pdf)
        print_text_bold(unicode(documento.pst.rif), 220, 750 + 2, pdf)
        # pdf.drawString(220, 768, unicode(documento.pst.razon_social))
        # pdf.drawString(220, 750, unicode(documento.pst.rif))
        if documento.pst.rtn != None:
            rtn = unicode(documento.pst.rtn)
            # pdf.drawString(220, 735, unicode(documento.pst.rtn))
        else:
            rtn = u'S/RTN'
            # pdf.drawString(220, 735, u'S/RTN')

        print_text_bold(rtn, 220, 735 + 2, pdf)
        print_text_bold(unicode(documento.codigo), 80, 835, pdf)
        print_text_bold(fecha, 295, 835, pdf)
        # pdf.drawString(80, 835, unicode(documento.codigo))

        para.wrapOn(pdf, 300, 50)
        para.drawOn(pdf, 220, 695)

        para_texto.wrapOn(pdf, 450, 300)
        para_texto.drawOn(pdf, 80, 675 - para_texto.height)

        if 675 - para_texto.height > 230:
            gaceta_end = gaceta(pdf, 675 - para_texto.height, gerente)
            notificacion(pdf, gaceta_end)
            label(pdf, gaceta_end, page)
        else:
            new_page = True

        pdf.save()
        # put on watermark from buffer
        watermark = PdfFileReader(buffer)
        tmp = input.getPage(page)

        tmp.mergePage(watermark.getPage(0))
        buffer.seek(0)

        # add processed pdf page
        output.addPage(tmp)
        if new_page:
            buffer = StringIO()  # create string buffer for PDF
            pdf = canvas.Canvas(buffer, pagesize=letter)

            gaceta_end = gaceta(pdf, 800, gerente)
            notificacion(pdf, gaceta_end)
            label(pdf, gaceta_end, page)

            pdf.save()

            # put on watermark from buffer
            watermark = PdfFileReader(buffer)
            input = PdfFileReader(
                file(
                    os.path.join(settings.PDF_ROOT, 'verificacion',
                                 'PROVIDENCIA.pdf'), 'rb'))
            tmp = input.getPage(3)

            tmp.mergePage(watermark.getPage(0))
            buffer.seek(0)

            # add processed pdf page
            output.addPage(tmp)

    output.write(response)
    return response
コード例 #39
0
def constancia(documento):
    new_page = False
    domicilio, gerente, supervisor, funcionarios, apoyo = documento_info(
        documento)

    texto = text_constancia(documento, supervisor, funcionarios)

    p = ParagraphStyle('test')
    p.textColor = 'black'
    p.alignment = TA_JUSTIFY
    p.fontSize = 10
    p.leading = 12
    if domicilio:
        para = Paragraph(unicode(domicilio), p)
    else:
        para = Paragraph(unicode("No tiene registro de domicilio"), p)
    para_texto = Paragraph(unicode(texto), p)

    output = PdfFileWriter()
    input = PdfFileReader(
        file(os.path.join(settings.PDF_ROOT, 'verificacion', 'CONSTANCIA.pdf'),
             'rb'))
    # create response object
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Verificacion_Constancia.pdf'

    # get number of pages
    num_pages = input.getNumPages()

    buffer = StringIO()  # create string buffer for PDF
    pdf = canvas.Canvas(buffer, pagesize=letter)
    pdf.drawString(220, 793, unicode(documento.pst.razon_social))
    pdf.drawString(220, 779, unicode(documento.pst.rif))
    if documento.pst.rtn != None:
        pdf.drawString(220, 766, unicode(documento.pst.rtn))
    else:
        pdf.drawString(220, 766, u'S/RTN')
    pdf.drawString(80, 850, unicode(documento.codigo))

    para.wrapOn(pdf, 300, 50)
    para.drawOn(pdf, 220, 762 - para.height)

    para_texto.wrapOn(pdf, 450, 300)
    para_texto.drawOn(pdf, 80, 730 - para_texto.height)

    pasivo(pdf, 730 - para_texto.height)
    supervisor_end = supervisor_firma(pdf, 730 - para_texto.height, supervisor)
    for funcionario in xrange(len(funcionarios)):
        supervisor_end = funcionario_firma(pdf, supervisor_end,
                                           funcionarios[funcionario])
        if supervisor_end <= 114 and funcionario != len(funcionarios) - 1:
            new_page = True
            start_funcionario = funcionario + 1
            break

    pdf.save()
    # put on watermark from buffer
    watermark = PdfFileReader(buffer)
    tmp = input.getPage(0)

    tmp.mergePage(watermark.getPage(0))
    buffer.seek(0)

    # add processed pdf page
    output.addPage(tmp)
    if new_page:
        buffer = StringIO()  # create string buffer for PDF
        pdf = canvas.Canvas(buffer, pagesize=letter)
        supervisor_end = 850
        for funcionario in xrange(start_funcionario, len(funcionarios)):
            supervisor_end = funcionario_firma(pdf, supervisor_end,
                                               funcionarios[funcionario])

        pdf.save()

        # put on watermark from buffer
        watermark = PdfFileReader(buffer)
        input = PdfFileReader(
            file(
                os.path.join(settings.PDF_ROOT, 'verificacion',
                             'PROVIDENCIA.pdf'), 'rb'))
        tmp = input.getPage(3)

        tmp.mergePage(watermark.getPage(0))
        buffer.seek(0)

        # add processed pdf page
        output.addPage(tmp)

    output.write(response)
    return response
コード例 #40
0
def main_data(learning_unit_year, program, nb_students, styles, content):

    # We add first a blank line
    content.append(
        Paragraph(
            '''
        <para spaceb=20>
            &nbsp;
        </para>
        ''', ParagraphStyle('normal')))

    text_left_style = ParagraphStyle('structure_header')
    text_left_style.alignment = TA_LEFT
    text_left_style.fontSize = 10
    struct_address = program['address']
    p_struct_name = Paragraph(
        '%s' % struct_address.get('recipient')
        if struct_address.get('recipient') else '', styles["Normal"])

    p_struct_location = Paragraph(
        '%s' % struct_address.get('location')
        if struct_address.get('location') else '', styles["Normal"])
    p_struct_address = Paragraph(
        '%s %s' %
        (struct_address.get('postal_code')
         if struct_address.get('postal_code') else '',
         struct_address.get('city') if struct_address.get('city') else ''),
        styles["Normal"])
    phone_fax_data = ""
    if struct_address.get('phone'):
        phone_fax_data += "%s : %s" % (_('phone'), struct_address.get('phone'))
    if struct_address.get('fax'):
        if struct_address.get('phone'):
            phone_fax_data += " - "
        phone_fax_data += "%s : %s" % (_('fax'), struct_address.get('fax'))
    p_phone_fax_data = Paragraph('%s' % phone_fax_data, styles["Normal"])

    data_structure = [[p_struct_name], [p_struct_location], [p_struct_address],
                      [p_phone_fax_data]]

    header_coordinator_structure = [[
        get_data_coordinator(learning_unit_year, styles), data_structure
    ]]
    table_header = Table(header_coordinator_structure, colWidths='*')
    table_header.setStyle(
        TableStyle([('LEFTPADDING', (0, 0), (-1, -1), 0),
                    ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                    ('VALIGN', (0, 0), (-1, -1), 'TOP')]))

    content.append(table_header)

    p = ParagraphStyle('right_page_header')
    p.alignment = TA_RIGHT
    p.fontSize = 10

    deliberation_date = program['deliberation_date']

    content.append(
        Paragraph('%s : %s' % (_('deliberation_date'), deliberation_date),
                  styles["Normal"]))
    content.append(
        Paragraph(
            '%s : %s  - Session : %s' %
            (_('academic_year'), learning_unit_year['academic_year'],
             learning_unit_year['session_number']), text_left_style))
    # content.append(Paragraph('Session : %d' % session_exam.number_session, text_left_style))
    content.append(
        Paragraph(
            "<strong>%s : %s</strong>" %
            (learning_unit_year['acronym'], learning_unit_year['title']),
            styles["Normal"]))
    content.append(
        Paragraph(
            '''<b>%s : %s </b>(%s %s)''' %
            (_('program'), program['acronym'], nb_students, _('students')),
            styles["Normal"]))
    content.append(
        Paragraph(
            '''
        <para spaceb=2>
            &nbsp;
        </para>
        ''', ParagraphStyle('normal')))
コード例 #41
0
ファイル: views.py プロジェクト: rudith/hospital-backend
def HistoriaPDF(request,dni):
    global c,dy
    historia=Historia.objects.filter(numeroHistoria=dni)
    width,height =A4
    
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=Historial_'+""+historia[0].numeroHistoria.__str__()+""+'.pdf'
    buffer = BytesIO()
    c = canvas.Canvas(buffer,pagesize=A4)

    #Cabecera__________________________________________
    c.setLineWidth(.3)
    c.setFont('Helvetica',20)
    c.drawString(185,750,'HISTORIA CLÍNICA')
    c.setFont('Helvetica',15)
    c.drawString(425, 765, 'N° HISTORIA')
    c.setFont('Helvetica',28)
    c.drawString(402,710,historia[0].numeroHistoria.__str__())
    c.drawImage("apps/Laboratorio/static/Unsa.png",60,700,width=85, height=110, mask='auto')
    c.line(40,695,550,695)
    c.line(40,820,550,820)
    c.line(40,695,40,820)
    c.line(165,695,165,820)
    c.line(395,695,395,820)
    c.line(550,695,550,820)
    c.line(395,750,550,750)
    #Cabecera_____________________________________________
    #nombre
    c.setFont('Helvetica', 13)
    c.drawString(60,650,'Apellidos y Nombres')
    c.setFont('Helvetica', 13)
    c.drawString(230,650,historia[0].nombres.__str__()+" "+historia[0].apellido_paterno.__str__()+" "+historia[0].apellido_materno.__str__())
    c.line(40,665,550,665)
    c.line(40,645,550,645)

    c.line(220,645,220,665)
    c.line(40,645,40,665)
    c.line(550,645,550,665)
    #nombre
    #fecha
    c.drawString(70,610,'Fecha de  Nacimiento')
    c.drawString(90,590,historia[0].fechaNac.__str__())

    c.drawString(340,610,'Lugar de Nacimiento')
    c.drawString(350,590,historia[0].lugarNac.__str__())

    c.line(40,625,550,625)
    c.line(40,605,550,605)
    c.line(40,585,550,585)

    c.line(40,585,40,625)
    c.line(265,585,265,625)
    c.line(550,585,550,625)

    #fecha
    #DNI
    c.drawString(125,550,'DNI')
    c.drawString(105,530,historia[0].dni.__str__())

    c.drawString(270,550,'Edad')
    c.drawString(275,530,str(historia[0].edad()))

    c.drawString(425,550,'Distrito')
    c.drawString(410,530,historia[0].distrito.__str__())

    c.line(40,565,550,565)
    c.line(40,545,550,545)
    c.line(40,525,550,525)

    c.line(40,525,40,565)
    c.line(220,525,220,565)
    c.line(350,525,350,565)
    c.line(550,525,550,565)

    

    #Direccion-Distrito
    c.drawString(250,490,'Dirección')
    c.drawString(50,470,historia[0].direccion.__str__())

    c.line(40,505,550,505)
    c.line(40,485,550,485)
    c.line(40,465,550,465)

    c.line(40,465,40,505)
    c.line(550,465,550,505)

    c.setFont('Helvetica',12)
    #Sexo EstadoCivil Profesión/Ocupación Teléfono

    c.drawString(50,430,'Sexo')
    c.drawString(50,410,historia[0].sexo.__str__())

    c.drawString(140,430,'Estado Civil')
    c.drawString(140,410,historia[0].estadoCivil.__str__())

    c.drawString(260,430,'Profesión/Ocupación ')
    c.drawString(260,410,historia[0].ocupacion.__str__())

    c.drawString(425,430,'Teléfono')
    if historia[0].celular == None:
        c.drawString(425,410,historia[0].telefono.__str__())
    else :
        c.drawString(425,410,historia[0].celular.__str__())
    



    c.line(40,445,550,445)
    c.line(40,425,550,425)
    c.line(40,405,550,405)

    c.line(40,405,40,445)
    c.line(135,405,135,445)
    c.line(255,405,255,445)
    c.line(415,405,415,445)    
    c.line(550,405,550,445)

    #GRADO de institucion Procedencia
    c.drawString(70,370,'Grado de Instrucción')
    c.drawString(50,350,historia[0].gradoInstruccion.__str__())

    c.drawString(350,370,'Procedencia')
    c.drawString(335,350,historia[0].procedencia.__str__())

    c.line(40,385,550,385)
    c.line(40,365,550,365)
    c.line(40,345,550,345)

    c.line(40,345,40,385)
    c.line(265,345,265,385)
    c.line(550,345,550,385)

     #Edad y Fecha de Apertura
    c.drawString(250,310,'Fecha de Apertura')
    c.drawString(260,290,historia[0].fechaReg.__str__())

    c.line(40,325,550,325)
    c.line(40,305,550,305)
    c.line(40,285,550,285)

    c.line(40,285,40,325)
    c.line(550,285,550,325)
     # Close the PDF object cleanly.
    c.showPage()
    
    cita = Cita.objects.filter(numeroHistoria=historia[0].id)

    p = ParagraphStyle('test')
    p.textColor = 'black'
    p.borderColor = 'white'
    p.alignment = TA_CENTER
    p.borderWidth = 1
    p.fontSize = 9
    dy=800
    count=0
    if (cita!=None):
                
        for citas in cita:
            triaje=Triaje.objects.filter(cita=citas.id)
            if triaje.count()>0:
                consulta=Consulta.objects.filter(pk=triaje[0].id.__str__())#Filtro de consultas por el id de triaje
                      
            if  triaje.count()>0 and consulta.count()>0: 
                imprimirTriaje(p,triaje[0])
                imprimirConsulta(p,consulta[0])    
                dibujarBorde()
                count=count+1
            if count==4:
                c.showPage()
                dy=800

            dy=dy-23 

    c.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)

    return response
コード例 #42
0
def pdf(comprobante, total, emisor, receptor, conceptos, timbrado, nomina):
    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas
    from reportlab.lib.units import cm
    from reportlab.platypus import Table, TableStyle, Spacer
    from reportlab.lib import colors
    from reportlab.platypus.flowables import Image
    from reportlab.lib.styles import ParagraphStyle
    from reportlab.platypus import Paragraph
    from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT
    from cStringIO import StringIO
    from reportlab.platypus import SimpleDocTemplate
    from reportlab.graphics.charts.textlabels import Label
    from reportlab.graphics.shapes import Drawing
    from reportlab.lib.colors import Color
    from reportlab.lib.utils import ImageReader


    def AllPageSetup(canvas, doc):

        canvas.saveState()
        logo_marca_agua = ImageReader('http://www.inmegen.gob.mx/tema/photologue/photos/logo_20_transparente.png')
        canvas.drawImage(logo_marca_agua, 130, 250, width=350, height=380, mask='auto')

        logo_header = ImageReader('http://www.inmegen.gob.mx/tema/photologue/photos/inmegen_logo_color01.png')
        canvas.drawImage(logo_header, 30, 717, width=151, height=70, mask='auto')
#        canvas.setFillGray(gray) 
        canvas.restoreState()


    def PrimerPaginaSetup(canvas, doc):

        diferencia = 45            
        extra = 15

        logo_marca_agua = ImageReader('http://www.inmegen.gob.mx/tema/photologue/photos/logo_20_transparente.png')
        canvas.drawImage(logo_marca_agua, 130, 250, width=350, height=380, mask='auto')

        logo_header = ImageReader('http://www.inmegen.gob.mx/tema/photologue/photos/inmegen_logo_color01.png')
        canvas.drawImage(logo_header, 30, 717, width=151, height=70, mask='auto')


        canvas.saveState()
        canvas.drawString(370, 780-diferencia+extra, "Periodo de pago "+nomina["@FechaInicialPago"]+"   "+nomina["@FechaFinalPago"])

        canvas.drawString(30, 750-diferencia, emisor["@nombre"])
        canvas.drawString(30, 735-diferencia, emisor["@rfc"])
        canvas.drawString(445, 756-diferencia+extra, conceptos["cfdi:Concepto"]["@descripcion"])

        canvas.drawString(435, 725-diferencia+extra, 'Total Neto:')
        canvas.drawString(500, 725-diferencia+extra, "${:,.2f}".format(float(total)))
        canvas.line(495, 723-diferencia+extra, 580, 723-diferencia+extra)
             
        canvas.drawString(30, 703-diferencia+extra, 'Nombre del empleado:')
        canvas.drawString(160, 703-diferencia+extra, receptor["@nombre"])
        canvas.line(160, 700-diferencia+extra, 580, 700-diferencia+extra)    

        canvas.drawString(30, 680-diferencia+extra, 'R.F.C:')
        canvas.drawString(160, 680-diferencia+extra, receptor["@rfc"])
        canvas.line(160, 677-diferencia+extra, 270, 677-diferencia+extra)

        canvas.drawString(280, 680-diferencia+extra, 'C.U.R.P:')
        canvas.drawString(330, 680-diferencia+extra, nomina["@CURP"])
        canvas.line(330, 677-diferencia+extra, 580, 677-diferencia+extra)

        canvas.drawString(30, 660-diferencia+extra, "CLABE:")
        canvas.drawString(160, 660-diferencia+extra, nomina.get("@CLABE", "SIN CLABE"))
        canvas.line(160, 657-diferencia+extra, 580, 657-diferencia+extra)

        canvas.drawString(30, 640-diferencia+extra, "Denominación del puesto:")
        canvas.drawString(170, 640-diferencia+extra, nomina["@Puesto"])
        canvas.line(170, 637-diferencia+extra, 580, 637-diferencia+extra)

        canvas.drawString(30, 620-diferencia+extra, "Adscripción:")
        canvas.drawString(160, 620-diferencia+extra, nomina["@Departamento"])
        canvas.line(160, 617-diferencia+extra, 580, 617-diferencia+extra)

        canvas.drawString(30, 600-diferencia+extra, "Folio Fiscal:")
        canvas.drawString(150, 600-diferencia+extra, timbrado["@UUID"])
        canvas.line(150, 597-diferencia+extra, 390, 597-diferencia+extra)

        canvas.drawString(400, 600-diferencia+extra, "Timbrado:")
        canvas.drawString(460, 600-diferencia+extra, timbrado["@FechaTimbrado"])
        canvas.line(455, 597-diferencia+extra, 580, 597-diferencia+extra)

        if False:
            canvas.drawString(30, 580-diferencia+extra, "Tipo de Contrato:")
            canvas.drawString(160, 580-diferencia+extra, nomina["@TipoContrato"])
            canvas.line(160, 577-diferencia+extra, 390, 577-diferencia+extra)

        canvas.drawString(400, 580-diferencia+extra, u"Número de días pagados:")
        canvas.drawString(540, 580-diferencia+extra, 
            "{:,d}".format(int(float(nomina["@NumDiasPagados"]))))
        canvas.line(540, 577-diferencia+extra, 580, 577-diferencia+extra)
       

        canvas.restoreState()


    class InfoCanvas(canvas.Canvas):
        def __init__(self, *args, **kwargs):
            canvas.Canvas.__init__(self, *args, **kwargs)
            self._saved_page_states = []
     
        def showPage(self):
            self.basic_data()
            self._saved_page_states.append(dict(self.__dict__))
            self._startPage()
            
     
        def basic_data(self):
            canvas = self
            canvas.setLineWidth(.3)
            canvas.setFont('Helvetica', 11)

            diferencia = 45            
            extra = 15

        def save(self):
            """add page info to each page (page x of y)"""
            num_pages = len(self._saved_page_states)
            for state in self._saved_page_states:
                self.__dict__.update(state)
                #self.draw_page_number(num_pages)
                canvas.Canvas.showPage(self)
            canvas.Canvas.save(self)
 
    buffer_ = StringIO()
    doc = SimpleDocTemplate(buffer_, pagesize=letter)
    elements = [Spacer(0, 6.1*cm)]# esto baja o sube la tabla de percepciones y deducciones

    pg = ParagraphStyle('table_title')
    pg.alignment = TA_CENTER

    percepciones = nomina["nomina:Percepciones"]
    deducciones = nomina["nomina:Deducciones"]
    table = Table([[Paragraph("Percepciones", pg), Paragraph("Deducciones", pg)]], 
        colWidths=275, rowHeights=15)
    table.setStyle(TableStyle([
                           ('INNERGRID', (0,0), (0,0), 0.25, colors.black),
                           ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                     #      ('BACKGROUND',(0,0),(-1,2), colors.white)
                           ]))
    elements.append(table)
    
    p_text = ParagraphStyle('text')
    p_text.alignment = TA_LEFT
    p_text.fontSize = 7
    p_text.borderColor = 'black'
    p_text.borderWidth = 0
    p_text.textColor = 'black'

    p_money = ParagraphStyle('money')
    p_money.alignment = TA_RIGHT
    p_money.fontSize = 7
    p_money.borderColor = 'black'
    p_money.borderWidth = 0
    p_money.textColor = 'black'

    percepciones_data = []
    if not isinstance(percepciones["nomina:Percepcion"], list):
        percepciones["nomina:Percepcion"] = [percepciones["nomina:Percepcion"]]

    #print(percepciones["nomina:Percepcion"])
    for p in percepciones["nomina:Percepcion"]:
        percepciones_data.append([
            Paragraph(p["@Clave"]+"  "+p["@Concepto"], p_text),
            Paragraph("${:,.2f}".format(float(p["@ImporteGravado"])), p_money)])

    deducciones_data = []
    if not isinstance(deducciones["nomina:Deduccion"], list):
        deducciones["nomina:Deduccion"] = [deducciones["nomina:Deduccion"]]

    #print(deducciones["nomina:Deduccion"])
    for p in deducciones["nomina:Deduccion"]:
        importe_exento = float(p["@ImporteExento"])
        importe_gravado = float(p["@ImporteGravado"])
        importe = importe_gravado if importe_gravado > 0 else importe_exento
        deducciones_data.append([
            Paragraph(p["@Clave"]+"  "+p["@Concepto"], p_text),
            Paragraph("${:,.2f}".format(importe), p_money)])

    if len(percepciones_data) < len(deducciones_data):
        for e in range(len(deducciones_data) - len(percepciones_data)):
            percepciones_data.append([
                Paragraph("", p_text),
                Paragraph("", p_text)])
    elif len(deducciones_data) < len(percepciones_data):
        for e in range(len(percepciones_data) - len(deducciones_data)):
            deducciones_data.append([
                Paragraph("", p_text),
                Paragraph("", p_text)])

    data = []
    total_deducciones_exento = float(deducciones["@TotalExento"])
    total_deducciones_gravado = float(deducciones["@TotalGravado"])
    total_importe_deducciones = total_deducciones_gravado\
        if total_deducciones_gravado > 0 else total_deducciones_exento 
    data.append([
        Paragraph("Total:", p_text),
        Paragraph("<b>${:,.2f}</b>".format(float(percepciones["@TotalGravado"])), p_money), 
        Paragraph("Total:", p_text),
        Paragraph("<b>${:,.2f}</b>".format(total_importe_deducciones), p_money)])

    for row1, row2 in zip(percepciones_data, deducciones_data):
        data.append(row1 + row2)

    table = Table(data, colWidths=(220, 50, 220, 50), rowHeights=15)
    table.setStyle(TableStyle([
                           ('INNERGRID', (0,0), (0,0), 0.5, colors.white),
                       #    ('BOX', (0,0), (-1,-1), 0.5, colors.white),
                        #   ('BACKGROUND',(0,0),(-1,2), colors.white)
                           ]))
    elements.append(Spacer(0, 0.5*cm))
    elements.append(table)
    
    qr_data = "?re={rfc_emisor}&rr={rfc_receptor}&tt={total}&id={folio_fiscal}".format(
        rfc_emisor=emisor["@rfc"],
        rfc_receptor=receptor["@rfc"],
        total=total,
        folio_fiscal=timbrado["@UUID"]
    )

    io = StringIO()
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=3,
        border=1,
    )
    qr.add_data(qr_data)
    qr.make(fit=True)

    p_text_g = ParagraphStyle('text')
    p_text_g.alignment = TA_LEFT
    p_text_g.fontSize = 10
    p_text_g.borderColor = 'black'
    p_text_g.borderWidth = 0
    p_text_g.textColor = 'black'

    img = qr.make_image()
    img.save(io)

    data = [
        [Paragraph("<b>Sello digital CFDI</b>", p_text_g), Image(io)],
        [Paragraph(timbrado["@selloCFD"], p_text_g)],
        [Paragraph("<b>Sello del SAT</b>", p_text_g)],
        [Paragraph(timbrado["@selloSAT"], p_text_g)]]
    
    table = Table(data, colWidths=(400, 150), rowHeights=(20, 50, 20, 80))
    table.setStyle(TableStyle([
         #                  ('INNERGRID', (0,0), (-1,-1), 0.5, colors.black),
          #                 ('BOX', (0,0), (-1,-1), 0.5, colors.black),
                           ('SPAN',(1,0),(-1,-1)),
                          # ('BACKGROUND',(0,0),(-1,2), colors.white),
                           ('ALIGN', (1,0), (-1,-1), 'RIGHT')
                           ]))
    elements.append(Spacer(0, .5*cm))
    elements.append(table)
    
    data = [[Paragraph("<b>Metodo de pago</b>", p_text),            
            Paragraph(comprobante["cfdi:Comprobante"]["@metodoDePago"], p_text),
            Paragraph("<b>Condiciones de pago</b>", p_text),
            Paragraph(comprobante["cfdi:Comprobante"]["@formaDePago"], p_text)]]
    table = Table(data)#, colWidths=550, rowHeights=40)

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

    elements.append(Spacer(0, .5*cm))
    elements.append(table)
    #lab = Label()
    #lab.setOrigin(300, 400)
    #lab.boxAnchor = 'ne'
    #lab.angle = 45
    #lab.dx = 0
    #lab.dy = -20
    #lab.fontSize = 60
    #lab.fillColor = Color(red=0, green=0, blue=0, alpha=.5)
    #lab.setText(u'Este recibo está\nen proceso de revisión')
    #d = Drawing(200, 10)
    #d.add(lab)
    #elements.append(d)
    doc.build(elements, canvasmaker=InfoCanvas, onFirstPage=PrimerPaginaSetup, onLaterPages=AllPageSetup)
    pdf = buffer_.getvalue()
    buffer_.close()
    return pdf
コード例 #43
0
ファイル: results.py プロジェクト: Hovercross/rectory-apps
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch

from courseevaluations.models import QuestionSet, MultipleChoiceQuestionAnswer, FreeformQuestionAnswer

title_style = ParagraphStyle(getSampleStyleSheet()["Normal"])
question_set_style = ParagraphStyle(getSampleStyleSheet()["Normal"])
question_style = ParagraphStyle(getSampleStyleSheet()["Normal"])
multiple_choice_option_style = ParagraphStyle(getSampleStyleSheet()["Normal"])
multiple_choice_count_style = ParagraphStyle(getSampleStyleSheet()["Normal"])
freeform_answer_style = ParagraphStyle(getSampleStyleSheet()["Normal"])

title_style.fontSize = 20
title_style.leading = 24
title_style.alignment = enums.TA_RIGHT
title_style.fontName = 'Times-BoldItalic'

question_style.spaceBefore = 10
question_style.fontName = 'Times-Bold'
question_style.fontSize = 12

multiple_choice_option_style.alignment = enums.TA_CENTER
multiple_choice_count_style.alignment = enums.TA_CENTER

freeform_answer_style.fontSize = 8

def build_report(output, evaluables, title=None, comments=True, unmask_comments=False):
    doc_args = {
        'author': 'Rectory School Evaluation System',
        'pagesize': letter,
コード例 #44
0
def generate_recript(email, date, amount, name, is_donation, editor_name):
    """This function generates PDF file with a receipt.

    Returns:
        Temporary file that needs to be closed after all operations on it are complete.
    """
    story = [Spacer(0, 20)]

    address_style = ParagraphStyle("address")
    address_style.fontName = _PRIMARY_FONT
    address_style.fontSize = 12
    address_style.alignment = TA_RIGHT
    if is_donation:
        from_email = "*****@*****.**"
    else:
        from_email = "*****@*****.**"
    address_par = Paragraph(
        "3565 South Higuera St., Suite B<br/>"
        "San Luis Obispo, CA 93401<br/><br/>"
        "%s<br/>"
        "https://metabrainz.org" % from_email, address_style)
    story.append(address_par)

    story.append(Spacer(0, 30))

    note_style = ParagraphStyle("note")
    note_style.fontName = _PRIMARY_FONT
    note_style.fontSize = 12
    note_style.alignment = TA_LEFT
    if is_donation:
        note_par = Paragraph(
            "%s<br/><br/><br/>"
            "Dear %s:<br/><br/>"
            "Thank you very much for your donation to the MetaBrainz Foundation!<br/><br/>"
            "Your donation will allow the MetaBrainz Foundation to continue operating "
            "and improving the MusicBrainz project and its related projects. The "
            "foundation depends on donations from the community and therefore deeply "
            "appreciates your support.<br/><br/>"
            "The MetaBrainz Foundation is a United States 501(c)(3) tax-exempt public charity. This "
            "allows US taxpayers to deduct this donation from their taxes under section 170 of the "
            "Internal Revenue Service code.<br/><br/>"
            "<b>Please save a printed copy of this receipt for your records.</b>"
            % (email, name), note_style)
    else:
        note_par = Paragraph(
            "%s<br/><br/><br/>"
            "Dear %s:<br/><br/>"
            "Thank you very much for your payment to the MetaBrainz Foundation!<br/><br/>"
            "Your payment will allow the MetaBrainz Foundation to continue operating "
            "and improving the MusicBrainz project and its related projects. The "
            "foundation depends on these payments and therefore deeply appreciates your "
            "support.<br/><br/>"
            "<b>Please save a printed copy of this receipt for your records.</b>"
            % (email, name), note_style)
    story.append(note_par)

    details_style = ParagraphStyle("details")
    details_style.fontName = _PRIMARY_FONT
    details_style.fontSize = 12
    details_style.alignment = TA_CENTER
    if is_donation:
        details_par = Paragraph(
            "<br/><br/><br/><b>"
            "Donation date: %s<br/>"
            "Donation amount: %s<br/>"
            "Donation editor: %s"
            "</b>" % (date, amount, editor_name), details_style)
    else:
        details_par = Paragraph(
            "<br/><br/><br/><b>"
            "Payment date: %s<br/>"
            "Amount: %s"
            "</b>" % (date, amount), details_style)
    story.append(details_par)

    story.append(Spacer(0, 40))

    thanks_style = ParagraphStyle("thanks")
    thanks_style.fontName = _PRIMARY_FONT_BOLD
    thanks_style.fontSize = 20
    thanks_style.alignment = TA_CENTER
    thanks_par = Paragraph("Thank you for your support!", thanks_style)
    story.append(thanks_par)

    f = tempfile.NamedTemporaryFile()
    doc = SimpleDocTemplate(f.name,
                            pagesize=(595, 792),
                            leftMargin=52,
                            rightMargin=44)
    if is_donation:
        doc.build(story, onFirstPage=_create_header_donation)
    else:
        doc.build(story, onFirstPage=_create_header_payment)
    return f
コード例 #45
0
def style_options():
    styles = getSampleStyleSheet()
    options = {'paragraph': {}}

    colors = {'black':'#000000', 'dark_blue':'#01429a', 'grey':'#e8e8e8',
        'red':'#c11e2e'}

    normalFontSize = 8
    subheadingFontSize = 13
    headingFontSize = 20
    options.update({'normalFontSize':normalFontSize,
        'subheadingFontSize':subheadingFontSize,
        'headingFontSize':headingFontSize,
        'color_swatch':ColorSwatch(**colors)})


    #Add T-Account style
    style_config = [
        ('ALIGN',(0,0),(-1,-1),'CENTER'),
        ('BACKGROUND', (2,0),(2,-1), colors['grey']),
        ('BACKGROUND', (-1,0),(-1,-1), colors['grey']),    

        ('FONTSIZE', (0, 0), (-1, -1), normalFontSize),

        ('LINEBELOW', (0, 0), (-1, 0), 1, colors['black']),
        ('LINEABOVE', (0, 0), (-1, 0), 1, colors['black']),
        ('LINEAFTER', (2, 0), (2, -1), 1, colors['black'])
    ]

    t_acc_option = PDFTableStyle('t_account',OPEXATableStyle(style_config))
    options.update({t_acc_option.name:t_acc_option})

    #Add Trial Balance style
    trial_bal_config = [
        ('ALIGN',(1,0),(-1,-1),'RIGHT'),

        # Grid
        ('LINEAFTER', (0, 0), (-1, -1), 1, colors['black']),
        ('LINEBEFORE', (0, 0), (-1, -1), 1, colors['black']),
        ('LINEABOVE', (0, 0), (-1, 0), 1, colors['black']),
        ('LINEBELOW', (0, -1), (-1, -1), 1, colors['black']),

    ]

    trial_bal_option = PDFTableStyle('trial_balance',OPEXATableStyle(trial_bal_config))
    options.update({trial_bal_option.name:trial_bal_option})

    #Add Trial Balance style
    pl_option = [
        ('ALIGN',(1,0),(-1,-1),'CENTER'),
        # Grid
        ('LINEAFTER', (0, 0), (-1, -1), 1, colors['black']),
        ('LINEBEFORE', (0, 0), (-1, -1), 1, colors['black']),
        ('LINEABOVE', (0, 0), (-1, 0), 1, colors['black']),
        ('LINEBELOW', (0, -1), (-1, -1), 1, colors['black'])
    ]

    pl_option = PDFTableStyle('profit_and_loss',OPEXATableStyle(trial_bal_config))
    options.update({pl_option.name:pl_option})


    #Paragraph Styles
    sub_heading_style = ParagraphStyle('Sub-Heading')
    sub_heading_style.textColor = 'black'
    sub_heading_style.fontSize = subheadingFontSize
    sub_heading_style.alignment = TA_CENTER
    options['paragraph'].update({'sub_heading':sub_heading_style})

    heading_style = ParagraphStyle('Heading')
    heading_style.textColor = 'black'
    heading_style.fontSize = headingFontSize
    heading_style.alignment = TA_CENTER
    options['paragraph'].update({'heading':heading_style})


    default_style = copy.copy(styles["Normal"])
    options['paragraph'].update({'default':default_style})

    centered = copy.copy(styles["Normal"])
    centered.alignment = TA_CENTER
    options['paragraph'].update({'centered':centered})

    centered_sub_heading = copy.copy(centered)
    centered_sub_heading.fontSize = subheadingFontSize
    options['paragraph'].update({'centered_sub_heading':centered_sub_heading})

    return options
コード例 #46
0
ファイル: reportes.py プロジェクト: genesis80013/unemi
def est_reportbateria(reactivos, nombre, carrera, facultad):
    nombre2 = nombre
    nombre = nombre.replace(" ", "")
    reactivos = reactivos
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'filename=' + nombre + "-report-estudiante.pdf"
    buff = BytesIO()
    doc = BaseDocTemplate(buff, pagesize=A4)
    story = []
    #crear en el encabezado
    frame0 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height,
                   showBoundary=0,
                   id='normalBorde')
    frame1 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height,
                   showBoundary=0,
                   id='normalBorde')
    doc.addPageTemplates([
        PageTemplate(id='header',
                     frames=frame0,
                     onPage=encabezado,
                     onPageEnd=piePagina),
        PageTemplate(id='contenido', frames=frame1, onPageEnd=piePagina),
    ])
    story.append(NextPageTemplate('contenido'))
    #HEADER2
    h1 = ParagraphStyle('texto')
    h1.textColor = 'black'
    h1.fontName = 'Helvetica-Bold'
    h1.borderPadding = 1
    h1.fontSize = 12
    h1.alignment = TA_CENTER
    facultad = Paragraph(facultad, h1)
    carrera = Paragraph(carrera + " - REACTIVOS", h1)
    story.append(Spacer(1, 30))
    story.append(facultad)
    story.append(Spacer(1, 10))
    story.append(carrera)
    story.append(Spacer(1, 30))
    #HEADER3
    tabla = []
    h2 = ParagraphStyle('texto')
    h2.alignment = TA_LEFT
    h2.fontSize = 10
    h2.textColor = 'black'
    h2.fontName = 'Helvetica-Bold'
    h3 = ParagraphStyle('texto')
    h3.alignment = TA_LEFT
    h3.fontSize = 8
    h3.textColor = 'black'
    h3.fontName = 'Helvetica'
    h4 = h3
    h4.fontSize = 10
    h5 = ParagraphStyle('texto')
    h5.fontSize = 10
    h5.textColor = 'black'
    h5.fontName = 'Helvetica'
    h5.alignment = TA_CENTER
    tb1 = [[Paragraph('Materia/área: ', h2),
            Paragraph(nombre2, h4)],
           [
               Paragraph('Cantidad: ', h2),
               Paragraph(len(reactivos).__str__(), h4)
           ]]
    tb1 = Table(tb1, colWidths=[1.2 * inch, 6 * inch])
    story.append(tb1)
    story.append(Spacer(1, 30))
    #reactivos
    index = 1
    for i in reactivos:
        tb2 = []
        tb2.append(
            [Paragraph('<b>N°: </b>', h3),
             Paragraph(index.__str__(), h3)])
        tb2.append(
            [Paragraph('<b>PREGUNTA: </b>', h3),
             Paragraph(i['tipo'], h3)])
        tb2.append([
            Paragraph('<b>NOTA: </b>', h3),
            Paragraph(i['nota'].__str__() + " puntos", h3)
        ])
        # atributos
        for a in i['atributos']:
            if a['archivo']:
                tb2.append([
                    Paragraph("<b>" + a['atributo__nombre'] + ": </b>", h3),
                    [
                        Paragraph(a['texto'], h3),
                        Image(this_path + '/media/' + a['archivo'], 200, 200)
                    ]
                ])
            else:
                tb2.append([
                    Paragraph("<b>" + a['atributo__nombre'] + ": </b>", h3),
                    [Paragraph(a['texto'], h3)]
                ])
        filas = len(tb2)
        if i['tipo'] != "EMPAREJAMIENTO":
            tb2.append([Paragraph('<b>OPCIONES: </b>', h3), ''])
        else:
            tab = [[[Paragraph('<b>A </b>', h5)], [Paragraph('<b>B </b>',
                                                             h5)]]]
            tab = Table(tab)
            tb2.append([Paragraph('<b>OPCIONES: </b>', h3), tab])
        index2 = 1
        for a in i['opciones']:
            if i['tipo'] != "EMPAREJAMIENTO":
                texto = a['texto'].replace("br", "")
                texto = texto.replace("<?php", "< ?php")
                if a['archivo']:
                    tb2.append([
                        Paragraph("<b>" + index2.__str__() + ": </b>", h3),
                        [[Paragraph(a['texto'], h3)],
                         [Image(this_path + '/media/' + a['archivo'])]]
                    ])
                else:
                    tb2.append([
                        Paragraph("<b>" + index2.__str__() + ": </b>", h3),
                        [Paragraph(texto, h3)]
                    ])
            else:
                tab = [[[Paragraph(a['texto'], h3)],
                        [Paragraph(a['texto2'], h3)]]]
                tab = Table(tab)
                tb2.append([
                    Paragraph("<b>" + index2.__str__() + ": </b>", h3), [tab]
                ])
            index2 += 1
        index += 1
        if i['tipo'] != "EMPAREJAMIENTO":
            styles = TableStyle([
                ('GRID', (0, 0), (-1, -1), 0.05, colors.gray),
                ('BACKGROUND', (0, 0), (0, filas - 1), colors.lavender),
                ('GRID', (0, filas), (filas, -1), 1, colors.gray),
                ('BOX', (0, 0), (1, -1), 0.1, colors.black),
                ('SPAN', (0, filas), (1, filas)),
            ])
        else:
            styles = TableStyle([
                ('GRID', (0, 0), (-1, -1), 0.05, colors.gray),
                ('BACKGROUND', (0, 0), (0, filas - 1), colors.lavender),
                ('GRID', (0, filas), (filas, -1), 1, colors.gray),
                ('BOX', (0, 0), (1, -1), 0.1, colors.black),
            ])
        tb2 = Table(tb2, colWidths=[2 * inch, doc.width - inch], style=styles)
        story.append(tb2)
        story.append(Spacer(1, 30))
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #47
0
ファイル: reportes.py プロジェクト: genesis80013/unemi
def cord_reportrevision(tipo, facultad, carrera, lista):
    nombre = carrera.replace(" ", "")
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'filename=' + nombre + "-report-examen.pdf"
    buff = BytesIO()
    doc = BaseDocTemplate(buff, pagesize=A4)
    story = []
    # crear en el encabezado
    frame0 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height,
                   showBoundary=0,
                   id='normalBorde')
    frame1 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height,
                   showBoundary=0,
                   id='normalBorde')
    doc.addPageTemplates([
        PageTemplate(id='header',
                     frames=frame0,
                     onPage=encabezado,
                     onPageEnd=piePagina),
        PageTemplate(id='contenido', frames=frame1, onPageEnd=piePagina),
    ])
    story.append(NextPageTemplate('contenido'))
    if tipo == "area":
        h1 = ParagraphStyle('texto')
        h1.textColor = 'black'
        h1.fontName = 'Helvetica-Bold'
        h1.borderPadding = 1
        h1.fontSize = 12
        h1.alignment = TA_CENTER
        nota = Paragraph('Asignación de reactivos generales', h1)
        story.append(Spacer(1, 30))
        story.append(nota)
        story.append(Spacer(1, 5))
    else:
        h1 = ParagraphStyle('texto')
        h1.textColor = 'black'
        h1.fontName = 'Helvetica-Bold'
        h1.borderPadding = 1
        h1.fontSize = 12
        h1.alignment = TA_CENTER
        facultad = Paragraph(facultad, h1)
        carrera = Paragraph(carrera, h1)
        nota = Paragraph('Asignación de reactivos específicos', h1)
        story.append(Spacer(1, 30))
        story.append(facultad)
        story.append(Spacer(1, 10))
        story.append(carrera)
        story.append(Spacer(1, 30))
        story.append(nota)
        story.append(Spacer(1, 5))
    #tabla
    h2 = ParagraphStyle('texto')
    h2.textColor = 'black'
    h2.fontName = 'Helvetica-Bold'
    h2.borderPadding = 1
    h2.fontSize = 10
    h2.alignment = TA_LEFT
    h3 = ParagraphStyle(name='Justify',
                        alignment=TA_JUSTIFY,
                        fontName='Helvetica',
                        textColor='black',
                        fontSize=10)
    header = []
    if tipo == "area":
        header.append([
            Paragraph('<b>Docente</b>', h2),
            Paragraph('<b>Área</b>', h2),
            Paragraph('<b>Cantidad de reactivos</b>', h2),
            Paragraph('<b>Revisión</b>', h2)
        ])
    else:
        header.append([
            Paragraph('<b>Docente</b>', h2),
            Paragraph('<b>Asignatura</b>', h2),
            Paragraph('<b>Cantidad de reactivos</b>', h2),
            Paragraph('<b>Revisión</b>', h2)
        ])
    for i in lista:
        if tipo == "area":
            nombre = i['asignacion'].persona.apellido1 + " " + i[
                'asignacion'].persona.apellido2 + " " + i[
                    'asignacion'].persona.nombres
            seccion = i['asignacion'].area.nombre
        else:
            nombre = i['asignacion'].docente.persona.apellido1 + " " + i[
                'asignacion'].docente.persona.apellido2 + " " + i[
                    'asignacion'].docente.persona.nombres
            seccion = i['asignacion'].asignatura.asignatura.nombre
        count = str(i['count']) + " de " + str(i['asignacion'].cantidad)
        if i['asignacion'].revision:
            revision = "REVISADO"
        else:
            revision = ""
        header.append([
            Paragraph(nombre, h3),
            Paragraph(seccion, h3),
            Paragraph(count, h3),
            Paragraph(revision, h3)
        ])
    styles = TableStyle([
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
    ])
    tb2 = Table(header, style=styles)
    tb2._argW[0] = 2 * inch
    tb2._argW[1] = 2 * inch
    story.append(tb2)
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #48
0
ファイル: reportes.py プロジェクト: genesis80013/unemi
def adm_pdfreportexamen(facultad, carrera, lista):
    nombre = carrera.replace(" ", "")
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'filename=' + nombre + "-report-examen.pdf"
    buff = BytesIO()
    doc = BaseDocTemplate(buff, pagesize=A4)
    story = []
    # crear en el encabezado
    frame0 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height,
                   showBoundary=0,
                   id='normalBorde')
    frame1 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height,
                   showBoundary=0,
                   id='normalBorde')
    doc.addPageTemplates([
        PageTemplate(id='header',
                     frames=frame0,
                     onPage=encabezado,
                     onPageEnd=piePagina),
        PageTemplate(id='contenido', frames=frame1, onPageEnd=piePagina),
    ])
    story.append(NextPageTemplate('contenido'))
    #header2
    h1 = ParagraphStyle('texto')
    h1.textColor = 'black'
    h1.fontName = 'Helvetica-Bold'
    h1.borderPadding = 1
    h1.fontSize = 12
    h1.alignment = TA_CENTER
    facultad = Paragraph(facultad, h1)
    carrera = Paragraph(carrera, h1)
    nota = Paragraph('Calificaciones de Examen Complexivo', h1)
    story.append(Spacer(1, 30))
    story.append(facultad)
    story.append(Spacer(1, 10))
    story.append(carrera)
    story.append(Spacer(1, 30))
    story.append(nota)
    story.append(Spacer(1, 5))
    #tbla de datos
    h2 = ParagraphStyle('texto')
    h2.textColor = 'black'
    h2.fontName = 'Helvetica-Bold'
    h2.borderPadding = 1
    h2.fontSize = 10
    h2.alignment = TA_LEFT
    h3 = ParagraphStyle(name='Justify',
                        alignment=TA_JUSTIFY,
                        fontName='Helvetica',
                        textColor='black',
                        fontSize=10)
    header = []
    header.append([
        Paragraph('<b>Cédula</b>', h2),
        Paragraph('<b>Apellidos y nombres</b>', h2),
        Paragraph('<b>Compe. Generales</b>', h2),
        Paragraph('<b>Compe. Específicas</b>', h2),
        Paragraph('<b>Calificación final</b>', h2),
        Paragraph('<b>Resultado</b>', h2)
    ])
    for i in lista:
        header.append([
            Paragraph(i['cedula'], h3),
            Paragraph(i['nombre'], h3),
            Paragraph(i['compgeneral'], h3),
            Paragraph(i['compespecifica'], h3),
            Paragraph(i['calificacion'], h3),
            Paragraph(i['resultado'], h3)
        ])
    styles = TableStyle([
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
    ])
    tb2 = Table(header, style=styles)
    tb2._argW[1] = 2 * inch
    story.append(tb2)
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #49
0
ファイル: recepcion_pdf.py プロジェクト: jose1403/tonino
def factura_recepcion_pdf(request, pk):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Factura-Recepcion.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    #response['Content-Disposition'] = 'attachment; filename=%s-%s/%s/%s.pdf'%(pdf_name, tiempo.day,tiempo.month, tiempo.year)
    buff = BytesIO()
    datos = DATOS_DE_LA_EMPRESA.objects.get(pk=1)
    recepcion = Recepcion.objects.get(pk=pk)
    pago = PagoRecepcion.objects.get(recepcion=recepcion)
    total = TotalRecepcion.objects.get(ingreso=pago)

    doc = SimpleDocTemplate(
        buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
    )
    styles = getSampleStyleSheet()
    lista = []
    stylefac = ParagraphStyle('Heading1')
    stylefac.textColor = ('red')
    stylefac.alignment = TA_RIGHT
    stylefac.fontSize = 20
    stylefac.spaceBefore = 5
    stylefac.spaceAfter = 5
    stylefac.leading = -20
    stylefac.bulletIndent = 0
    stylefac.allowOrphans = 0
    stylefac.bulletFontSize = 10

    stylefac.borderWidth = 0
    #stylemenbrete.bulletAnchor = start
    stylefac.borderPadding = 0
    stylefac.endDots = None

    lista.append(Paragraph('%s' % recepcion.codigo_en_sistema(), stylefac))
    lista.append(
        Paragraph('<font size=10 color=black><b>NO. Control</b></font>',
                  stylefac))
    lista.append(logo_pdf())
    lista.append(Spacer(0, 10))
    stylemenbrete = ParagraphStyle('Heading1')
    stylemenbrete.textColor = ('black')
    stylemenbrete.alignment = TA_CENTER
    stylemenbrete.fontSize = 12

    stylemenbrete.spaceBefore = 5
    stylemenbrete.spaceAfter = 5
    stylemenbrete.leading = 10
    stylemenbrete.bulletIndent = 0
    stylemenbrete.allowOrphans = 0
    stylemenbrete.bulletFontSize = 10

    stylemenbrete.borderWidth = 0
    #stylemenbrete.bulletAnchor = start
    stylemenbrete.borderPadding = 0
    stylemenbrete.endDots = None
    #stylemenbrete.textColor = Color(0,0,0,1)
    """MEMBRETE"""
    nombre = Paragraph('<b>%s</b>' % datos.NOMBRE.upper(), stylemenbrete)
    #fin **********************************
    rif = Paragraph('<b> RIF: %s</b>' % (datos.RIF.upper()), stylemenbrete)
    direccion = Paragraph('<b> %s</b>' % (datos.DIRECCION.upper()),
                          stylemenbrete)
    telefonos = Paragraph('<b> %s / %s</b>' % (datos.TELEFONO, datos.CELULAR),
                          stylemenbrete)
    codigo_postal = Paragraph(
        '<b> CODIGO POSTAL: %s</b>' % (datos.CODIGO_POSTAL), stylemenbrete)
    lista.append(nombre)  #+rif+direccion+telefonos+codigo_postal)
    lista.append(rif)  #+rif+direccion+telefonos+codigo_postal)
    lista.append(direccion)
    lista.append(telefonos)
    lista.append(codigo_postal)
    lista.append(Spacer(0, 30))
    #############################
    fecha = Paragraph(
        '<b>Fecha de Emision: %s/%s/%s - %s:%s</b>' %
        (recepcion.fecha_agregado.day, recepcion.fecha_agregado.month,
         recepcion.fecha_agregado.year, recepcion.fecha_agregado.hour,
         recepcion.fecha_agregado.minute), styles['Normal'])
    lista.append(fecha)
    lista.append(Spacer(0, 10))
    lista.append(
        Paragraph(
            '<para alignment=left><b>CICLO: %s </b></font>' %
            str(recepcion.ciclo_asociado).upper(), styles['Normal'])),

    lista.append(
        Paragraph('<font size=10 color=black ><b>-</b></font>' * 156,
                  styles['Normal']))
    lista.append(
        Paragraph('<font color=red><b>DATOS DEL PROOVEDOR</b><font> ',
                  styles['Normal']))

    #datos De Proovedor
    style_table = ParagraphStyle('Default')
    #style_table.textColor= 'black'
    style_table.alignment = TA_LEFT
    style_table.fontSize = 10
    style_table.spaceAfter = 15
    style_table.spaceBefore = 0
    style_table.spaceAfter = 0
    style_table.leading = 10  # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName = 'Helvetica'

    style_table.bulletAnchor = 'start',
    array1 = []
    array1.append([
        Paragraph(
            '<font color=black><b>NOMBRE O RAZON SOCIAL: %s</b>  </font>' %
            recepcion.proovedor.nombre_o_razon_social.upper(), style_table),
        Paragraph(
            '<para alignment=left><font><b>CI/RIF: %s</b></font>' %
            recepcion.proovedor.documentoId.upper(), style_table)
    ])
    array2 = []
    array2.append([
        Paragraph(
            '<font><b>DOMICILIO: </b></font><font size=8><b>%s</b></font>' %
            recepcion.proovedor.domicilio_fiscal.upper(), style_table),
        Paragraph(
            '<para alignment=left><font><b>TELEF: %s/%s</b></font>' %
            (recepcion.proovedor.telefono, recepcion.proovedor.celular),
            style_table)
    ])
    array3 = []
    array3.append([
        Paragraph(
            '<font><b>CODIGO: %s</b></font>' %
            recepcion.proovedor.codigo_en_sistema(), style_table),
        Paragraph(
            '<font ><b>ZONA: %s</b></font>' %
            recepcion.zona_de_cosecha.zona.upper(), style_table)
    ])
    t = Table(array1 + array2 + array3)

    lista.append(t)
    lista.append(
        Paragraph('<font size=10 color=black ><b>-<b></font>' * 156,
                  styles['Normal']))

    descripcion = []

    headingsDes = []
    headingsDes.append([
        Paragraph('<font color=black><b>RUBRO <b>  </font>', style_table),
        Paragraph('<para alignment=left><font><b>PRESIO </b></font>',
                  style_table),
        Paragraph('<para alignment=left><font><b>CANTIDAD</b></font>',
                  style_table),
        Paragraph('<para alignment=left><font><b>MERMA H/I</b></font>',
                  style_table),
        Paragraph('<para alignment=left><font><b>CANTIDAD REAL</b></font>',
                  style_table),
        Paragraph('<para alignment=left><font><b>TOTAL NETO. </b></font>',
                  style_table),
    ])
    descripcion.append([
        Paragraph(
            '<font color=black><b>%s<b>  </font>' %
            (recepcion.producto_total()), style_table),
        Paragraph(
            '<para alignment=left><font><b> %s Bs.</b></font>' %
            intcomma(pago.precio.precio_por_Kg), style_table),
        Paragraph(
            '<para alignment=left><font><b> %s Kg.</b></font>' %
            intcomma(recepcion.cantidad_en_Kg), style_table),
        Paragraph(
            '<para alignment=left><font><b> %s %%</b></font>' %
            intcomma(total.descuentoTotal), style_table),
        Paragraph(
            '<para alignment=left><font><b> %s Kg.</b></font>' %
            intcomma(total.cantidad_real), style_table),
        Paragraph(
            '<para alignment=left><font><b> %s Bs.</b></font>' %
            intcomma(total.total_neto), style_table),
    ])
    separator = ('', '', '', '')
    #headingsDes=('Rubro', 'precio','Cantidad Recibida', 'Total Neto')
    imptable = []
    impuesto1 = []
    print total.impuestos()
    for i, k in total.impuestos().items():
        impuesto1.append([
            Paragraph('<font color=black><b> <b>  </font>', style_table),
            Paragraph('<para alignment=left><font><b> </b></font>',
                      style_table),
            Paragraph('<para alignment=left><font><b> </b></font>',
                      style_table),
            Paragraph('<para alignment=left><font><b> </b></font>',
                      style_table),
            Paragraph('<para alignment=left><font><b>%s </b></font>' % i,
                      style_table),
            Paragraph(
                '<para alignment=left><font><b>%s Bs.</b></font>' %
                intcomma(k), style_table),
        ])
    precio_total = []
    precio_total.append([
        Paragraph('<font color=black><b> <b>  </font>', style_table),
        Paragraph('<para alignment=left><font><b> </b></font>', style_table),
        Paragraph('<para alignment=left><font><b> </b></font>', style_table),
        Paragraph('<para alignment=left><font><b> </b></font>', style_table),
        Paragraph('<para alignment=left><font><b>TOTAL </b></font>',
                  style_table),
        Paragraph(
            '<para alignment=left><font><b>%s Bs. </b></font>' %
            intcomma(total.total_Bs), style_table),
    ])
    tdescripcion = Table(headingsDes + descripcion + [separator] + impuesto1 +
                         precio_total)
    lista.append(tdescripcion)
    lista.append(Spacer(0, 40))
    style_analisis = ParagraphStyle('Default')
    #style_table.textColor= 'black'
    #style_table.alignment= TA_CENTER
    style_analisis.fontSize = 10
    style_analisis.spaceAfter = 15
    style_analisis.spaceBefore = 0
    style_analisis.spaceAfter = 0
    style_analisis.leading = 20  # anchor de tabla
    style_analisis.bulletIndent = 0
    style_analisis.allowOrphans = 0
    style_analisis.bulletFontSize = 5
    style_analisis.fontName = 'Times-Roman'
    lista.append(
        Paragraph(
            '<para alignment=left><font size=10><b> DESCUENTO POR IMPURESA: %s%%</b> </font>'
            % total.descuentoI, style_analisis))
    lista.append(
        Paragraph(
            '<para alignment=left><font size=10><b>MERMA POR HUMEDAD:%s%% </b> </font>'
            % total.descuentoH, style_analisis))
    lista.append(
        Paragraph(
            '<para alignment=left><font size=10><b>DESCUENTO POR MANIPULEO: %s%%</b> <i> </i> </font>'
            % total.descuentoM, style_analisis))

    lista.append(
        Paragraph(
            '<para alignment=left><font size=12 color=grey><b>RESULTADOS DEL ANALISIS</b></font>',
            style_analisis))
    lista.append(
        Paragraph(
            '<para alignment=left><font size=10><b> HUMEDAD:%s%%</b></font>' %
            recepcion.humedad, style_analisis))
    lista.append(
        Paragraph(
            '<para alignment=left><font size=10><b> IMPUREZA:%s%%</b></font>' %
            recepcion.impureza, style_analisis))
    #lista.append(Paragraph('<para alignment=left><font size=10><b>GRANOS DAÑADOS: %s%%</b></font>'%recepcion.granos_danados_totales, style_analisis))
    #lista.append(Paragraph('<para alignment=left><font size=10><b>GRANOS PARTIDOS: %s%%</b> </font>'%recepcion.granos_partidos, style_analisis))
    #lista.append(Paragraph('<para alignment=left><font size=10><b>TEMPERATURA PROMEDIO: %s°C</b></font>'%recepcion.temperatura_promedio, style_analisis))
    #lista.append(Paragraph('<para alignment=left><font size=10><b>OTROS:</b> <i>%s%% </i> </font>'%recepcion.otros, style_analisis))

    doc.build(lista)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #50
0
	def generarGraficoProductos(self):
		nombres = []
		precios = []
	 
		self.iniciar_conexion()
		cursor = self.__conexion.cursor()
		sql = "SELECT prod.nombre,SUM(prod.precio) AS precio_final FROM productos prod,proveedores prov WHERE prod.id_proveedor=prov.id GROUP BY prod.nombre"
		cursor.execute(sql)
		rows = cursor.fetchall()

		for row in rows:
			nombre_producto = row[0]
			precio = row[1]
			nombres.append(nombre_producto)
			precios.append(precio)

		self.cerrar_conexion()

		reporte = SimpleDocTemplate("graficoProductos.pdf")
		partes = []

		font_text = ParagraphStyle("test")
		font_text.textColor = "black"
		font_text.alignment = TA_CENTER
		font_text.fontSize = 20

		text = Paragraph("Reporte gráfico de productos y sus precios",font_text)
		partes.append(text)
		draw = Drawing()
		pie = Pie()
		pie.width = 300
		pie.height = 200
		pie.x = 50
		pie.y = -100
		pie.data = precios
		pie.labels = nombres
		pie.slices.strokeWidth = 0.5

		legend = Legend() 
		legend.x               = 250
		legend.y               = -200 
		legend.dx              = 8  
		legend.dy              = 8  
		legend.fontName        = "Helvetica"  
		legend.fontSize        = 7  
		legend.boxAnchor       = "n"  
		legend.columnMaximum   = 10  
		legend.strokeWidth     = 1  
		legend.strokeColor     = colors.black  
		legend.deltax          = 75  
		legend.deltay          = 10  
		legend.autoXPadding    = 5  
		legend.yGap            = 0  
		legend.dxTextSpace     = 5  
		legend.alignment       = "right"  
		legend.dividerLines    = 1|2|4  
		legend.dividerOffsY    = 4.5  
		legend.subCols.rpad    = 30  
    
		legend.colorNamePairs  = [(
                            pie.slices[i].fillColor, 
                            (pie.labels[i][0:20], "$"+"%0.2f" % pie.data[i])
                           ) for i in xrange(len(pie.data))]
                           
		draw.add(legend)

		draw.add(pie)

		partes.append(draw)
		reporte.build(partes)
		
		if(os.path.isfile("graficoProductos.pdf")):
			return True
		else:
			return False
コード例 #51
0
ファイル: views.py プロジェクト: nadtorres/MiiPucv
def acta_interna(request):

    #GET Para obtener los datos de Alumno
    objeto1 = Alumno.objects.get(id=1)
    nombre_Alumno = str(objeto1.nombre) + ' ' + str(
        objeto1.apellido_pat) + ' ' + str(objeto1.apellido_mat)

    objeto2 = Profesor.objects.get(id=1)
    nombre_Profesor = str(objeto2.nombre) + ' ' + str(
        objeto2.apellido_pat) + ' ' + str(objeto2.apellido_mat)

    objeto3 = Profesor.objects.get(id=2)
    nombre_Pro_Cotutor = str(objeto3.nombre) + ' ' + str(
        objeto3.apellido_pat) + ' ' + str(objeto3.apellido_mat)

    response = HttpResponse(content_type='application/pdf')
    response['content-Disposition'] = 'attachment; filename=actaInterna.pdf'
    buffer = BytesIO()
    c = canvas.Canvas(buffer, pagesize=letter)

    #Header
    fecha = datetime.date.today().strftime("%d/%m/%Y")

    c.setLineWidth(.3)
    c.setFont('Helvetica', 20)
    c.drawString(30, 750, 'Doctorado en Ingeniería Informática')

    c.setFont('Helvetica-Bold', 12)
    c.drawString(480, 730, fecha)

    c.setFont('Helvetica-Bold', 14)
    c.drawString(250, 700, 'ACTA INTERNA')
    c.line(250, 698, 355, 698)

    c.setFont('Helvetica-Bold', 14)
    c.drawString(220, 685, 'EVALUACION DE AVANCE')
    c.line(220, 683, 400, 683)

    c.setFont('Helvetica-Bold', 14)
    c.drawString(216, 670, 'ASIGNATURA DII 795 TESIS')
    c.line(216, 668, 400, 668)

    c.setFont('Helvetica', 12)
    c.drawString(30, 615, 'ALUMNO:')
    c.drawString(90, 615, nombre_Alumno)

    c.setFont('Helvetica', 12)
    c.drawString(30, 595, 'PROF. GUIA:')
    c.drawString(105, 595, nombre_Profesor)

    c.setFont('Helvetica', 12)
    c.drawString(30, 575, 'PROF. COTUTOR o INVITADO:')
    c.drawString(205, 575, nombre_Pro_Cotutor)

    c.setFont('Helvetica', 12)
    c.drawString(30, 560, 'TEMA:')
    c.drawString(70, 560, 'Software Programa Magister')

    #PIE DE FIRMA
    c.setFont('Helvetica', 12)
    c.drawString(105, 159, nombre_Profesor)
    c.line(90, 175, 250, 175)

    c.setFont('Helvetica', 12)
    c.drawString(360, 159, nombre_Pro_Cotutor)
    c.line(350, 175, 510, 175)

    students = [
        {
            'Tipo Evaluacion': 'Avance 1 2 ó 3',
            'Fecha': fecha,
            'Nota': ' '
        },
    ]

    # Table Header
    style = getSampleStyleSheet()
    styleBH = style["Normal"]
    styleBH.alignment = TA_CENTER
    styleBH.fontSize = 10

    style = getSampleStyleSheet()
    styleBH2 = style["Normal"]
    styleBH2.alignment = TA_LEFT
    styleBH2.fontSize = 10

    tipo_evaluacion = Paragraph(
        '''Tipo Evaluacion <br /> (Avance 1, 2 ó 3 )''', styleBH2)
    Fecha = Paragraph('''Fecha''', styleBH)
    Nota = Paragraph('''Nota''', styleBH)

    data = []
    data.append([tipo_evaluacion, Fecha, Nota])

    #Table
    # styles = getSampleStyleSheet()
    styleN = style["BodyText"]
    styleN.alignment = TA_CENTER
    styleN.fontSize = 7

    width, height = letter
    high = 500
    for student in students:
        this_student = [
            student['Tipo Evaluacion'], student['Fecha'], student['Nota']
        ]
        data.append(this_student)
        high = high - 18

    #table size
    table = Table(data,
                  colWidths=[9.0 * cm, 4.0 * cm, 5.0 * cm],
                  rowHeights=1 * cm)
    table.setStyle(
        TableStyle([  #estilo de la tabla
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('GRID', (0, 0), (-1, -1), 1.5, colors.black),
        ]))

    p = ParagraphStyle('parrafos')
    p.alignment = TA_JUSTIFY
    p.fontSize = 10
    p.fontName = "Times-Roman"
    obs = Paragraph("OBSERVACIONES Y RECOMENDACIONES: ", p)
    observaciones = [[obs]]
    tabla_observaciones = Table(observaciones,
                                colWidths=[18 * cm],
                                rowHeights=8.6 * cm)
    tabla_observaciones.setStyle(
        TableStyle([
            ('GRID', (0, 0), (0, 2), 1.5, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))
    obs = Paragraph("OBSERVACIONES;", p)
    #PDF size
    table.wrapOn(c, width, height)
    table.drawOn(c, 30, high)
    tabla_observaciones.wrapOn(c, width, height)
    tabla_observaciones.drawOn(c, 30, 237)
    c.showPage()  #save page

    #save PDF
    c.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    # c.showPage()
    # c.save()
    return response
コード例 #52
0
    def toParagraphStyle(self, first):
        style = ParagraphStyle('default%d' % self.UID(), keepWithNext=first.keepWithNext)
        style.fontName = first.fontName
        style.fontSize = first.fontSize
        style.leading = max(first.leading + first.leadingSpace, first.fontSize * 1.25)
        style.backColor = first.backColor
        style.spaceBefore = first.spaceBefore
        style.spaceAfter = first.spaceAfter
        style.leftIndent = first.leftIndent
        style.rightIndent = first.rightIndent
        style.firstLineIndent = first.firstLineIndent
        style.textColor = first.textColor
        style.alignment = first.alignment
        style.bulletFontName = first.bulletFontName or first.fontName 
        style.bulletFontSize = first.fontSize
        style.bulletIndent = first.bulletIndent
        
        # Border handling for Paragraph

        # Transfer the styles for each side of the border, *not* the whole
        # border values that reportlab supports. We'll draw them ourselves in
        # PmlParagraph.
        style.borderTopStyle = first.borderTopStyle
        style.borderTopWidth = first.borderTopWidth
        style.borderTopColor = first.borderTopColor
        style.borderBottomStyle = first.borderBottomStyle
        style.borderBottomWidth = first.borderBottomWidth
        style.borderBottomColor = first.borderBottomColor
        style.borderLeftStyle = first.borderLeftStyle
        style.borderLeftWidth = first.borderLeftWidth
        style.borderLeftColor = first.borderLeftColor
        style.borderRightStyle = first.borderRightStyle
        style.borderRightWidth = first.borderRightWidth
        style.borderRightColor = first.borderRightColor

        # If no border color is given, the text color is used (XXX Tables!)
        if (style.borderTopColor is None) and style.borderTopWidth:
            style.borderTopColor = first.textColor      
        if (style.borderBottomColor is None) and style.borderBottomWidth:
            style.borderBottomColor = first.textColor      
        if (style.borderLeftColor is None) and style.borderLeftWidth:
            style.borderLeftColor = first.textColor      
        if (style.borderRightColor is None) and style.borderRightWidth:
            style.borderRightColor = first.textColor      

        style.borderPadding = first.borderPadding

        style.paddingTop = first.paddingTop
        style.paddingBottom = first.paddingBottom
        style.paddingLeft = first.paddingLeft
        style.paddingRight = first.paddingRight
        
        # This is the old code replaced by the above, kept for reference
        #style.borderWidth = 0
        #if getBorderStyle(first.borderTopStyle):
        #    style.borderWidth = max(first.borderLeftWidth, first.borderRightWidth, first.borderTopWidth, first.borderBottomWidth)
        #    style.borderPadding = first.borderPadding # + first.borderWidth
        #    style.borderColor = first.borderTopColor
        #    # If no border color is given, the text color is used (XXX Tables!)
        #    if (style.borderColor is None) and style.borderWidth:
        #        style.borderColor = first.textColor      

        style.fontName = tt2ps(first.fontName, first.bold, first.italic)
        return style       
コード例 #53
0
def info_productor_pdf(request, pk):

    response = HttpResponse(content_type='application/pdf')
    pdf_name = "info-de-Productor.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    print inch
    #response['Content-Disposition'] = 'attachment; filename=%s-%s/%s/%s.pdf'%(pdf_name, tiempo.day,tiempo.month, tiempo.year)
    #response['Content-Disposition'] = 'filename="archivo.pdf"'

    buff = BytesIO()

    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            showBoundary=0,
                            title='Info-Productores',
                            onPage='doNothing',
                            onPageEnd='doNothing')

    lista = []
    styles = getSampleStyleSheet()
    #menbrete ************************
    lista.append(logo_pdf())
    fecha = Paragraph(
        '<b><i>Fecha: %s/%s/%s</i></b>' %
        (tiempo.day, tiempo.month, tiempo.year), styles['Normal'])
    lista.append(Spacer(0, 25))
    lista.append(fecha)
    lista.append(Spacer(0, 20))
    style = ParagraphStyle('Heading1')
    style.textColor = 'black'
    style.alignment = TA_CENTER
    style.fontSize = 16
    style.spaceAfter = 15
    style.spaceBefore = 15
    style.spaceAfter = 5
    style.leading = 20
    style.bulletIndent = 0
    style.allowOrphans = 0
    style.bulletFontSize = 10
    header = Paragraph("<b>Informacion del Proovedor</b>".upper(), style)

    #******Modelos********
    lista.append(header)
    lista.append(Spacer(0, 25))

    p = Productor.objects.get(pk=pk, habilitado=True, null=False)
    zona = Productor.zona.contar_zonas(pk=pk, null=False)

    #******Modelos********

    #
    style_C = ParagraphStyle('Normal')
    style_C.alignment = TA_RIGHT
    style_C.fontSize = 14
    style_C.textColor = 'black'

    style_N = ParagraphStyle('Normal')
    style_N.alignment = TA_LEFT
    style_N.fontSize = 12
    style_N.textColor = 'black'

    style_table = ParagraphStyle('Default')
    #style_table.textColor= 'black'
    #style_table.alignment= TA_CENTER
    style_table.fontSize = 10
    style_table.spaceAfter = 15
    style_table.spaceBefore = 0
    style_table.spaceAfter = 0
    style_table.leading = 20  # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName = 'Times-Roman'

    style_table.bulletAnchor = 'start',
    codigo_en_sistema = Paragraph(
        '<font ><b>CODIGO EN SISTEMA:</b> %s</font>' % p.codigo_en_sistema(),
        style_C)
    lista.append(codigo_en_sistema)
    lista.append(Spacer(0, 5))
    lista.append(
        Paragraph('<b>NUMERO DE ZONAS:</b>%s' % zona['CantZonas'], style_N))
    lista.append(Spacer(0, 10))

    lista.append(
        Paragraph(
            '<b> CANTIDAD DE HECTAREAS:</b> %s Hect.' % zona['CantHectareas'],
            style_N))
    lista.append(Spacer(0, 20))
    array_datos = []

    lista.append(Paragraph('<font><b>INFORMACION BASICA</b></font>', style_N))
    lista.append(Spacer(0, 20))

    title_datos = ('Nombre o Razon Social', 'CI/RIF', 'Domicilio Fiscal')
    array_datos.append([
        Paragraph(p.nombre_o_razon_social.title(), style_table),
        Paragraph(p.documentoId.title(), style_table),
        Paragraph(p.domicilio_fiscal.title(), style_table)
    ])
    t_datos = Table([title_datos] + array_datos)
    tupla_tabla = [
        ('GRID', (0, 1), (len(title_datos), -1), 1, colors.black),
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('LINEBELOW', (1, 0), (-1, 0), 1, colors.black),
        ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
        ('BACKGROUND', (0, 1), (len(title_datos), len(array_datos)),
         colors.white)  #HexColor(0x979494)),
        #('BACKGROUND', (0, 0), (-3, 0), colors.yellow),

        #('BACKGROUND', (0, 0), (-1, 0), colors.palegreen)d1e82af7
    ]
    t_datos.setStyle(TableStyle(tupla_tabla))  #414141
    lista.append(t_datos)
    array_referencia = []
    title_referencia = ('TELEFONO', 'CELULAR', 'E-MAIL')
    array_referencia.append([
        Paragraph(p.telefono, style_table),
        Paragraph(p.celular, style_table),
        Paragraph(p.e_mail, style_table)
    ])
    t_referencia = Table([title_referencia] + array_referencia)
    t_referencia.setStyle(TableStyle(tupla_tabla))
    lista.append(t_referencia)

    array_banco = []
    encabesado_banco = ('', 'CUENTA PRINCIPAL', '')
    title_banco = ('CUENTA', 'BANCO', 'TIPO')
    array_banco.append([
        Paragraph(p.cuenta_bancaria, style_table),
        Paragraph(p.banco.nombre.title(), style_table),
        Paragraph(p.tipo_cuenta.nombre.title(), style_table),
    ])
    t_banco = Table([title_banco] + array_banco)
    t_banco.setStyle(TableStyle(tupla_tabla))
    lista.append(t_banco)

    array_afiliacion = []
    title_afiliacion = ('FECHA DE AGREGADO', 'REFENCIA', 'OBSERVACION')
    array_afiliacion.append([
        Paragraph(
            '%s/%s/%s' % (p.fecha_agregado.day, p.fecha_agregado.month,
                          p.fecha_agregado.year), style_table),
        Paragraph(p.referencia_folder, style_table),
        Paragraph(p.observacion, style_table)
    ])
    t_afiliacion = Table([title_afiliacion] + array_afiliacion)
    t_afiliacion.setStyle(TableStyle(tupla_tabla))
    lista.append(t_afiliacion)

    doc.build(
        lista
    )  #, onFirstPage = myFirstPage, onLaterPages = myLaterPages)#doc.build(story, onFirstPage = myFirstPage, onLaterPages = myLaterPages)

    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #54
0
ファイル: reportes.py プロジェクト: genesis80013/unemi
def cord_reportbateriaexamen(count, reactivos, nombre, carrera, malla,
                             cronograma, periodo, coordinador):
    reactivos = reactivos
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'filename=' + nombre + "-report-coordinador.pdf"
    buff = BytesIO()
    doc = BaseDocTemplate(buff, pagesize=A4)
    story = []
    # crear en el encabezado
    frame0 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height,
                   showBoundary=0,
                   id='normalBorde')
    frame1 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width,
                   doc.height,
                   showBoundary=0,
                   id='normalBorde')
    doc.addPageTemplates([
        PageTemplate(id='header',
                     frames=frame0,
                     onPage=encabezado,
                     onPageEnd=piePagina),
        PageTemplate(id='contenido', frames=frame1, onPageEnd=piePagina),
    ])
    story.append(NextPageTemplate('contenido'))
    # HEADER2
    h1 = ParagraphStyle('texto')
    h1.textColor = 'black'
    h1.fontName = 'Helvetica-Bold'
    h1.borderPadding = 1
    h1.fontSize = 10
    h1.alignment = TA_LEFT
    cronograma = Paragraph("CRONOGRAMA: " + cronograma, h1)
    carrera = Paragraph("CARRERA: " + carrera, h1)
    if malla:
        malla = Paragraph("MALLA: " + malla, h1)
    periodo = Paragraph("PERIODO: " + periodo, h1)
    coordinador = Paragraph("COORDINADOR: " + coordinador, h1)
    count = Paragraph("TOTAL DE REACTIVOS: " + str(count), h1)
    story.append(Spacer(1, 30))
    story.append(cronograma)
    story.append(Spacer(1, 10))
    story.append(carrera)
    story.append(Spacer(1, 10))
    if malla:
        story.append(malla)
        story.append(Spacer(1, 10))
    story.append(periodo)
    story.append(Spacer(1, 10))
    story.append(coordinador)
    story.append(Spacer(1, 10))
    story.append(count)
    story.append(Spacer(1, 30))
    #resumen
    h3 = ParagraphStyle('texto')
    h3.alignment = TA_LEFT
    h3.fontSize = 8
    h3.textColor = 'black'
    h3.fontName = 'Helvetica'
    tb1 = []
    for i in reactivos:
        tb1.append([
            Paragraph(i['asignatura'], h3),
            Paragraph(str(i['reactivos']), h3)
        ])
    styles = TableStyle([
        ('GRID', (0, 0), (-1, -1), 0.05, colors.gray),
        ('GRID', (0, len(reactivos)), (len(reactivos), -1), 1, colors.gray),
        ('BOX', (0, 0), (1, -1), 0.1, colors.black),
        ('SPAN', (0, len(reactivos)), (1, len(reactivos))),
    ])
    tb2 = Table(tb1, colWidths=[270, 100], style=styles)
    story.append(tb2)
    story.append(Spacer(1, 30))
    #reactivos a detalle
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #55
0
def rubro_pdf(request):
    print "Genero el PDF"
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Listado-de-rubros.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    #response['Content-Disposition'] = 'attachment; filename=Listado_de_rubros-%s/%s/%s.pdf'%(tiempo.day,tiempo.month, tiempo.year)
    buff = BytesIO()
    doc = SimpleDocTemplate(
        buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
    )
    lista = []
    styles = getSampleStyleSheet()
    lista.append(logo_pdf())
    #<<<<<<< HEAD
    style = ParagraphStyle('Heading1')
    style.textColor = 'black'
    style.alignment = TA_CENTER
    style.fontSize = 18
    style.spaceAfter = 15
    style.spaceBefore = 30
    style.spaceAfter = 5
    style.leading = 20
    style.bulletIndent = 0
    style.allowOrphans = 0
    style.bulletFontSize = 10
    style.fontName = 'Helvetica'
    fecha = Paragraph(
        '<font><b><i>Fecha: %s/%s/%s</i><b></font>' %
        (tiempo.day, tiempo.month, tiempo.year), styles['Normal'])
    #=======

    #>>>>>>> c39095c0cdc5175aaf93d43954826f4ba55db4a2
    lista.append(Spacer(0, 40))
    lista.append(fecha)
    lista.append(Spacer(0, 10))
    style_table = ParagraphStyle('Default')
    #style_table.textColor= 'black'
    #style_table.alignment= TA_CENTER
    style_table.fontSize = 10
    style_table.spaceAfter = 15
    style_table.spaceBefore = 0
    style_table.spaceAfter = 0
    style_table.leading = 20  # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName = 'Times-Roman'

    header = Paragraph("<b>LISTADO DE RUBROS</b>", style)
    lista.append(header)
    lista.append(Spacer(0, 10))
    headings = ('Codigo En Sistema', 'Nombre', 'Nombre Cientifico',
                'T/Humedad', 'T/Impureza')
    array = []
    for p in Rubro.objects.filter(null=False):
        array.append([
            Paragraph(p.codigo_en_sistema(), style_table),
            Paragraph(p.nombre, style_table),
            Paragraph(p.nombre_cientifico, style_table),
            Paragraph('%s' % p.tolerancia_humedad, style_table),
            Paragraph('%s' % p.tolerancia_impureza, style_table)
        ])

    t = Table([headings] + array)
    t.setStyle(
        TableStyle([
            ('GRID', (0, 0), (len(headings), -1), 2, colors.grey),
            ('LINEBELOW', (1, 0), (-1, 0), 2, colors.grey),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor(0x41a02a)),
            ('BACKGROUND', (0, 1), (len(headings), len(array)),
             colors.HexColor(0xdbf706)),
            #('BACKGROUND', (0, 0), (-3, 0), colors.yellow),

            #('BACKGROUND', (0, 0), (-1, 0), colors.palegreen)d1e82af7
        ]))
    lista.append(t)
    doc.build(lista)
    response.write(buff.getvalue())
    buff.close()
    return response
コード例 #56
0
    def render_using_config(self, config):

        # draw outline if in debug
        if self.debug or config.get('debug'):
            self.draw_debug_outline(config)

        # get the text to render
        text = self.extract_content(config)

        # choose the method to draw the string
        text_align = config['text-align']

        if text_align == 'centre':
            style_alignment = TA_CENTER
        elif text_align == 'left':
            style_alignment = TA_LEFT
        else:
            raise Exception("Unhandled value for 'text-align': '%s'" %
                            text_align)

        if config['overflow'] == 'wrap':
            frame = Frame(
                config['x'],
                config['y'],
                config['w'],
                config['h'],
            )

            # create a paragraph style
            font_size = config['font-size']
            style = ParagraphStyle(name='test')
            style.fontName = config['font-family']
            style.alignment = style_alignment

            while font_size > minimum_font_size:
                style.fontSize = font_size
                style.leading = font_size

                para = Paragraph(text, style)

                if frame.add(para, self.canvas):
                    break

                # Paragraph was too big - shrink the font size
                font_size -= 1

        elif config['overflow'] == 'shrink':

            font_size = config['font-size']

            while font_size > minimum_font_size:
                self.canvas.setFont(config['font-family'], font_size)
                if self.canvas.stringWidth(text) <= config['w']:
                    break
                font_size -= 1

            if text_align == 'centre':
                self.canvas.drawCentredString(
                    config['x'] + config['w'] / 2,
                    config['y'] + config['h'] - config['font-size'], text)
            elif text_align == 'left':
                self.canvas.drawString(
                    config['x'],
                    config['y'] + config['h'] - config['font-size'], text)
            else:
                raise Exception("Unhandled value for 'text-align': '%s'" %
                                text_align)

        else:
            raise Exception("Unhandled value of 'overflow': '%s'" %
                            config['overflow'])
コード例 #57
0
style_sh = styles["Heading2"]
style_sh.alignment = TA_LEFT

# Sub-subheading style (questions)
style_ssh = styles["Heading3"]
style_ssh.alignment = TA_LEFT

# Main heading style
style_h = styles['Heading1']
style_h.alignment = TA_CENTER

# Answer Style
style_answer = ParagraphStyle(name='BodyText',
                              parent=styles['Normal'],
                              spaceBefore=6)
style_answer.alignment = TA_LEFT
style_answer.fontName = "Helvetica-Bold"
style_answer.textColor = colors.red
style_answer.fontSize = 15
style_answer.leading = 20
style_answer.spaceAfter = 20

MAX_ANSWER_CHARACTERS_PER_LINE = 35


class PDFTransformer:
    def __init__(self, survey, response_data):
        '''
        Sets up variables needed to write out a pdf
        '''
        self.survey = survey
コード例 #58
0
 def dessineGrille(self,
                   valeurs,
                   verts,
                   erreurs,
                   possibles,
                   barrejs=[],
                   jaunes=[],
                   rouges=[],
                   bleus=[],
                   rougesclairs=[],
                   bleusclairs=[]):
     #si la ligne de grilles a dejjah 3 grilles, passe ah la ligne
     if len(self.grilles) == 3: self.pdfGrilles()
     #cree le quadrillage du sudoku
     grilleStyle = self.grilleStyle()
     grilleStyle.extend([('FONTSIZE', (0, 0), (-1, -1), 11),
                         ('TOPPADDING', (0, 0), (-1, -1), 0)])
     for x, y in verts:
         grilleStyle.append(('TEXTCOLOR', (y, x), (y, x), colors.black))
         grilleStyle.append(
             ('BACKGROUND', (y, x), (y, x), colors.lightgreen))
     for x, y in erreurs:
         grilleStyle.append(('BACKGROUND', (y, x), (y, x), colors.red))
     if len(barrejs) + len(jaunes) + len(rouges) + len(bleus) == 0:
         for x, y in possibles:
             grilleStyle.append(
                 ('BACKGROUND', (y, x), (y, x), colors.lightcyan))
     for ((x, y), valeur) in barrejs:
         grilleStyle.append(
             ('BACKGROUND', (y, x), (y, x), colors.lightgoldenrodyellow))
     for ((x, y), valeur) in jaunes:
         grilleStyle.append(
             ('BACKGROUND', (y, x), (y, x), colors.lightgoldenrodyellow))
     for ((x, y), valeur) in rouges:
         grilleStyle.append(
             ('BACKGROUND', (y, x), (y, x), colors.lightgoldenrodyellow))
     for ((x, y), valeur) in bleus:
         grilleStyle.append(
             ('BACKGROUND', (y, x), (y, x), colors.lightgoldenrodyellow))
     for ((x, y), valeur) in rougesclairs:
         grilleStyle.append(
             ('BACKGROUND', (y, x), (y, x), colors.lightgoldenrodyellow))
     for ((x, y), valeur) in bleusclairs:
         grilleStyle.append(
             ('BACKGROUND', (y, x), (y, x), colors.lightgoldenrodyellow))
     # creje le dico des valeurs
     valeursDic = {}
     for (x, y), valeur in valeurs:
         if (x, y) not in valeursDic: valeursDic[(x, y)] = []
         valeursDic[(x, y)].append(valeur)
     # creje les diffejerents styles
     uniqueStyle = ParagraphStyle('unique')
     uniqueStyle.fontName = 'Helvetica'
     uniqueStyle.alignment = enums.TA_CENTER
     uniqueStyle.fontSize = 11
     erreurStyle = ParagraphStyle('erreur')
     erreurStyle.fontName = 'Helvetica'
     erreurStyle.alignment = enums.TA_CENTER
     erreurStyle.fontSize = 9
     multipleStyle = ParagraphStyle('multiple')
     multipleStyle.fontName = 'Helvetica'
     multipleStyle.alignment = enums.TA_CENTER
     multipleStyle.leading = 7
     multipleStyle.fontSize = 6
     # creje la valeur sous forme d'une matrice 9x9, l'initialise ah vide
     grilleValeurs = [['' for i in range(9)] for i in range(9)]
     # et la remplit avec les valeurs et leur format
     for (x, y), listeValeurs in valeursDic.items():
         listeValeurs.sort()
         listeAffichages = []
         for valeur in listeValeurs:
             #if ((x, y), valeur) in barrejs: listeAffichages.append('<span bgcolor=lightcoral style=strike>' + str(valeur) + '</span>')
             fait = False
             if ((x, y), valeur) in barrejs:
                 valeurStr = '<strike>' + str(valeur) + '</strike>'
             else:
                 valeurStr = str(valeur)
             #listeAffichages.append('<strike>' + str(valeur) + '</strike>')
             #fait = True
             if ((x, y), valeur) in jaunes:
                 listeAffichages.append(
                     '<span bgcolor=darkolivegreen textcolor=white>' +
                     valeurStr + '</span>')
                 fait = True
             if ((x, y), valeur) in rouges:
                 listeAffichages.append(
                     '<span bgcolor=red textcolor=white>' + valeurStr +
                     '</span>')
                 fait = True
             if ((x, y), valeur) in bleus:
                 listeAffichages.append(
                     '<span bgcolor=blue textcolor=white>' + valeurStr +
                     '</span>')
                 fait = True
             if ((x, y), valeur) in rougesclairs:
                 listeAffichages.append('<span bgcolor=lightpink>' +
                                        valeurStr + '</span>')
                 fait = True
             if ((x, y), valeur) in bleusclairs:
                 listeAffichages.append('<span bgcolor=lightskyblue>' +
                                        valeurStr + '</span>')
                 fait = True
             if not fait: listeAffichages.append(valeurStr)
         if (x, y) in possibles:
             if len(listeAffichages) < 6: sep = 2
             else: sep = 3
             grilleValeurs[x][y] = Paragraph(
                 ','.join(listeAffichages[:sep]) + '<br/>' +
                 ','.join(listeAffichages[sep:]), multipleStyle)
         elif (x, y) in erreurs:
             grilleValeurs[x][y] = Paragraph(','.join(listeAffichages),
                                             erreurStyle)
         else:
             grilleValeurs[x][y] = Paragraph(','.join(listeAffichages),
                                             uniqueStyle)
     #cree la table avec les valeurs et la taille de chaque cellule
     grille = Table(grilleValeurs, C_CEL, C_CEL)
     grille.setStyle(grilleStyle)
     self.grilles.append((self.titreGrille, grille))
     self.titreGrille = []
コード例 #59
0
def _ptoTestCase(self):
    """PTO stands for Please Turn Over and is a means for
    specifying content to be inserted when stuff goes over a page.
    This makes one long multi-page paragraph."""

    # Build story.
    story = []

    def fbreak(story=story):
        story.append(FrameBreak())

    styleSheet = getSampleStyleSheet()
    H1 = styleSheet['Heading1']
    H1.pageBreakBefore = 0
    H1.keepWithNext = 0

    bt = styleSheet['BodyText']
    pto = ParagraphStyle('pto', parent=bt)
    pto.alignment = TA_RIGHT
    pto.fontSize -= 1

    def ColorParagraph(c, text, style):
        return Paragraph('<para color="%s">%s</para>' % (c, text), style)

    def ptoblob(blurb, content, trailer=None, header=None, story=story, H1=H1):
        if type(content) not in (type([]), type(())): content = [content]
        story.append(
            PTOContainer([Paragraph(blurb, H1)] + list(content), trailer,
                         header))

    t0 = [ColorParagraph('blue', 'Please turn over', pto)]
    h0 = [ColorParagraph('blue', 'continued from previous page', pto)]
    t1 = [ColorParagraph('red', 'Please turn over(inner)', pto)]
    h1 = [ColorParagraph('red', 'continued from previous page(inner)', pto)]
    ptoblob('First Try at a PTO', [Paragraph(text0, bt)], t0, h0)
    fbreak()
    c1 = Table(
        [('alignment', 'align\012alignment'),
         ('bulletColor', 'bulletcolor\012bcolor'),
         ('bulletFontName', 'bfont\012bulletfontname'),
         ('bulletFontSize', 'bfontsize\012bulletfontsize'),
         ('bulletIndent', 'bindent\012bulletindent'),
         ('firstLineIndent', 'findent\012firstlineindent'),
         ('fontName', 'face\012fontname\012font'),
         ('fontSize', 'size\012fontsize'), ('leading', 'leading'),
         ('leftIndent', 'leftindent\012lindent'),
         ('rightIndent', 'rightindent\012rindent'),
         ('spaceAfter', 'spaceafter\012spacea'),
         ('spaceBefore', 'spacebefore\012spaceb'),
         ('textColor', 'fg\012textcolor\012color')],
        style=[
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, black),
            ('BOX', (0, 0), (-1, -1), 0.25, black),
        ],
    )
    ptoblob('PTO with a table inside', c1, t0, h0)
    fbreak()
    ptoblob('A long PTO', [Paragraph(text0 + ' ' + text1, bt)], t0, h0)
    fbreak()
    ptoblob('2 PTO (inner split)', [
        ColorParagraph('pink', text0, bt),
        PTOContainer([
            ColorParagraph(black, 'Inner Starts', H1),
            ColorParagraph('yellow', text2, bt),
            ColorParagraph('black', 'Inner Ends', H1)
        ], t1, h1),
        ColorParagraph('magenta', text1, bt)
    ], t0, h0)
    _showDoc('test_platypus_pto.pdf', story)
コード例 #60
0
ファイル: proovedor_pdf.py プロジェクト: jose1403/tonino
def info_zona_productor_pdf(request, pk):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "info-de-Productor.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    #response['Content-Disposition'] = 'attachment; filename=%s-%s/%s/%s.pdf'%(pdf_name, tiempo.day,tiempo.month, tiempo.year)
    #response['Content-Disposition'] = 'filename="archivo.pdf"' 
    buff = BytesIO()

    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    styles = getSampleStyleSheet()
    p=  Productor.objects.get(pk=pk, habilitado=True)
    zonas = Productor.zona.contar_zonas(pk=pk)
    style_C= ParagraphStyle('Normal')
    style_C.alignment= TA_RIGHT
    style_C.fontSize= 14
    style_C.textColor= 'black'

    lista=[]
    lista.append(logo_pdf())
    fecha= Paragraph('<b><i>Fecha: %s/%s/%s</i></b>'%(tiempo.day,tiempo.month, tiempo.year), styles['Normal'])
    lista.append(Spacer(0,25))
    
    lista.append(fecha)
    lista.append(Spacer(0,30))

    lista.append(Paragraph("<font><b>CODIGO:</b></font> %s"%p.codigo_en_sistema().upper(), style_C))
    lista.append(Spacer(0,10))
    lista.append(Paragraph("<font ><b>PROOVEDOR:</b></font> %s"%p.codigo_en_sistema().upper(), style_C))
    lista.append(Spacer(0,10))
    
    lista.append(Paragraph("<font ><b>ASIGNADO:</b></font> %s"%p.nombre_o_razon_social.upper(), style_C))
    lista.append(Spacer(0,10))
    lista.append(Paragraph("<font><b>TOTAL DE ZONAS:</b></font> %s"%zonas['CantZonas'], style_C))
    lista.append(Spacer(0,10))
    lista.append(Paragraph("<font><b>HECTAREAS:</b></font> %s Hect."%zonas['CantHectareas'], style_C))
    #*****************************
    lista.append(Spacer(0,20))
    style= ParagraphStyle('Heading1')
    style.textColor= 'black'
    style.alignment= TA_CENTER
    style.fontSize= 18
    style.spaceAfter=15
    style.spaceBefore= 50
    style.spaceAfter=5
    style.leading = 20
    style.bulletIndent = 0
    style.allowOrphans = 0
    style.bulletFontSize = 10
    style.fontName='Helvetica'
    lista.append(Paragraph("<b>ZONAS ASIGANADAS</b>".upper(), style))
    lista.append(Spacer(0,10))

    #****************************
    style_table= ParagraphStyle('Default')

    #style_table.textColor= 'black'
    style_table.alignment= TA_CENTER
    style_table.fontSize= 10
    style_table.spaceAfter=15
    style_table.spaceBefore= 0
    style_table.spaceAfter=0
    style_table.leading = 20 # anchor de tabla
    style_table.bulletIndent = 0
    style_table.allowOrphans = 0
    style_table.bulletFontSize = 5
    style_table.fontName='Times-Roman'
   
    style_table.bulletAnchor= 'start',
    
    cont= 0
    array=[]
    headings = ['N','NOMBRE', 'ESTADO', 'MUNICIPIO', 'EXTENCION']
    for zona in zonas['zonas']:
        cont+=1
        array.append([Paragraph(str(cont), style_table),
        Paragraph(zona.zona, style_table),
        Paragraph(zona.estado, style_table),
        Paragraph(zona.municipio, style_table),
        Paragraph('%s Hect.'%zona.hectareas, style_table)])

    t = Table([headings] + array)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (len(headings), -1), 2, colors.grey),
            ('LINEBELOW', (1, 0), (-1, 0), 2, colors.grey),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor(0x41a02a)),
            ('BACKGROUND', (0, 1), (len(headings), len(array)), colors.HexColor(0xdbf706)),
            #('BACKGROUND', (0, 0), (-3, 0), colors.yellow),

            #('BACKGROUND', (0, 0), (-1, 0), colors.palegreen)d1e82af7

        ]
    ))
    lista.append(t)
    doc.build(lista)
    response.write(buff.getvalue())
    buff.close()
    return response