Ejemplo n.º 1
0
    def _add_Y_items(self):
        """ add Y items labels to the chart (Text and styles). Add also light grid for their lines """

        X_pos = 0
        Y_pos = 3

        # draw the items titles with the right indentation

        for i in self.data.items_order:

            item = self.data.items[i]

            ps = ParagraphStyle("indent")
            ps.fontName = self.DEFAULT_FONT
            ps.fontSize = self.DEFAULT_FONT_SIZE
            ps.leftIndent = item.indent * self.INDENT_SPACE

            p = Paragraph(self._encode_entities(item.label), ps)
            self.table[Y_pos + item.Y_pos][X_pos] = p

            # draw the inner grid for this lines
            start_X = X_pos
            end_X = -1
            start_Y = Y_pos + item.Y_pos
            end_Y = Y_pos + item.Y_pos + item.line_number
            self.styles.append(("LINEABOVE", (start_X, end_Y), (end_X, end_Y), 0.2, "#bbbbbb"))
            self.styles.append(("LINEAFTER", (start_X, start_Y), (end_X, end_Y), 0.2, "#bbbbbb"))

        # line that separate the Y items and the datas
        self.styles.append(("LINEAFTER", (X_pos, Y_pos - 2), (X_pos, -1), 1, colors.black))
Ejemplo n.º 2
0
    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
Ejemplo n.º 3
0
 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"))
Ejemplo n.º 4
0
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
    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
Ejemplo n.º 6
0
def build_encabezado(datos_albaran):
    """
    Devuelve una tabla de dos líneas con los datos del albarán, que es un 
    diccionario de: fecha -como texto-, número (de albarán), kilos, 
    bultos.
    """
    datos_albaran = sanitize(datos_albaran)
    datos = [["Fecha", escribe("Nº Albarán"), "Kilos", "Bultos"], 
             [datos_albaran["fecha"], datos_albaran["número"], 
                datos_albaran["kilos"], datos_albaran["bultos"]]]
    estilo_centrado = ParagraphStyle("Alineado centrado", 
                                     parent=estilos["Normal"])
    estilo_centrado.alignment = enums.TA_CENTER
    estilo_centrado.fontSize += 2
    datos = [[Paragraph(celda, estilos["Normal"]) for celda in datos[0]] ,
             [Paragraph(celda, estilo_centrado) for celda in datos[1]]]
    tabla = Table(datos, 
                  colWidths = (PAGE_WIDTH * 0.9/4,)*4) 
    tabla.setStyle(TableStyle([
        ("BOX", (0, 1), (-1, -1), 1.0, colors.black),
        ("INNERGRID", (0, 1), (-1, -1), 0.25, colors.black), 
        ("ALIGN", (0, 0), (-1, 0), "LEFT"), 
        ("ALIGN", (0, 1), (-1, 1), "CENTER"), 
        ]))
    return tabla
Ejemplo n.º 7
0
def testRml():
    from reportlab.platypus.doctemplate import SimpleDocTemplate
    from reportlab.platypus.flowables import Spacer
    from reportlab.lib.randomtext import randomText

    templ = SimpleDocTemplate('doclet_output.pdf')

    #need a style
    story = []
    normal = ParagraphStyle('normal')
    normal.firstLineIndent = 18
    normal.spaceBefore = 6

    para = Paragraph("Test of doclets.  You should see a little table with a reversed word.", normal)
    story.append(para)

    story.append(Spacer(36,36))
                 
    theDoclet = TestReverseDoclet()
    story.append(theDoclet.asFlowable())
    
    for i in range(5):
        para = Paragraph(randomText(), normal)
        story.append(para)



    templ.build(story)    

    print('saved doclet_output.pdf')
Ejemplo n.º 8
0
def cuadritos_en_ruta():
    """
    Devuelve dos flowables:
    Un texto centrado con el texto de "ENVASES VACÍOS..." y una tabla 
    con el texto y los cuadraditos que se rellenan a mano durante la ruta 
    del transportista.
    """
    estilo_centrado = ParagraphStyle("Alineado centrado", 
                                    parent=estilos["Normal"])
    estilo_centrado.alignment = enums.TA_CENTER
    cab = Paragraph(escribe("ENVASES VACÍOS SIN LIMPIAR, 3 A.D.R."), 
                    estilo_centrado)
    datos = [["G.R.G. 1.000L", "", "", "BIDONES 100L", ""], 
             ["",              "", "", "",             ""], 
             ["DEPÓSITO 600L", "", "", "BIDONES 50L",  ""], 
             ["",              "", "", "",             ""], 
             ["BIDONES 200L",  "", "", "GARRAFAS 60L", ""],
             ["",              "", "", "",             ""], 
             ["BIDONES 25L",   "", "", "BIDONES 10L", ""]]
    datos = [[escribe(c) for c in fila] for fila in datos]
    tabla = Table(datos, 
                  colWidths = (3*cm, 0.75*cm, 5*cm, 3*cm, 0.75*cm))
    tabla.setStyle(TableStyle([
        ("BOX", (1, 0), (1, 0), 1.0, colors.black),
        ("BOX", (4, 0), (4, 0), 1.0, colors.black),
        ("BOX", (1, 2), (1, 2), 1.0, colors.black),
        ("BOX", (4, 2), (4, 2), 1.0, colors.black),
        ("BOX", (1, 4), (1, 4), 1.0, colors.black),
        ("BOX", (4, 4), (4, 4), 1.0, colors.black),
        ("BOX", (1, 6), (1, 6), 1.0, colors.black),
        ("BOX", (4, 6), (4, 6), 1.0, colors.black),
        ]))
    return KeepTogether([Spacer(1, 0.3*cm), cab, Spacer(1, 0.5*cm), tabla])
Ejemplo n.º 9
0
def build_tabla_contenido(data):
    """
    Construye la tabla del contenido del albaranSalida.
    Los datos deben venir en listas. Cada línea de la tabla, una tupla o lista 
    con el código, descripción, cantidad, precio unitario (con dto. si lo 
    lleva e IVA) y número de pedido.
    El precio y cantidad deben ser flotantes para poder calcular el subtotal.
    """
    estilo_cabecera_tabla = ParagraphStyle("Cabecera tabla", 
                                           parent=estilos["Heading3"])
    estilo_cabecera_tabla.fontName = "Times-Bold"
    estilo_cabecera_tabla.alignment = enums.TA_CENTER
    estilo_numeros_tabla = ParagraphStyle("Números tabla", 
                                           parent=estilos["Normal"])
    estilo_numeros_tabla.alignment = enums.TA_RIGHT
    datos = [(Paragraph(escribe("Código"), estilo_cabecera_tabla), 
              Paragraph(escribe("Descripción"), estilo_cabecera_tabla), 
              Paragraph("Cantidad", estilo_cabecera_tabla), 
              Paragraph("Precio/U", estilo_cabecera_tabla), 
              #Paragraph("Total c/IVA", estilo_cabecera_tabla), 
              # CWT: Prefiere la carta de portes sin IVA.
              Paragraph("Total", estilo_cabecera_tabla), 
              Paragraph(escribe("Nº Pedido"), estilo_cabecera_tabla))
            ]
    for d in data:
        fila = (escribe(d[0]), 
                Paragraph(escribe(d[1]),estilos["Normal"]), 
                Paragraph(escribe(utils.float2str(d[2])),estilo_numeros_tabla),
                Paragraph(escribe(utils.float2str(d[3])),estilo_numeros_tabla),
                Paragraph(escribe(utils.float2str(d[2] * d[3])), 
                    estilo_numeros_tabla),
                escribe(d[4])
               )
        datos.append(fila)
    tabla = Table(datos, 
                  colWidths = (PAGE_WIDTH * 0.13, 
                               PAGE_WIDTH * 0.35, 
                               PAGE_WIDTH * 0.09, 
                               PAGE_WIDTH * 0.09, 
                               PAGE_WIDTH * 0.13, 
                               PAGE_WIDTH * 0.11), 
                  repeatRows = 1)
    tabla.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey), 
        ("LINEBEFORE", (0, 0), (-1, -1), 0.25, colors.black),
        ("LINEBELOW", (0, 0), (-1, 0), 1.0, colors.black), 
        ("LINEBELOW", (0, "splitlast"), (-1, "splitlast"), 1.0, colors.black), 
        ("BOX", (0, 0), (-1, -1), 1.0, colors.black),
        ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), 
        ("VALIGN", (0, 0), (-1, 0), "CENTER"), 
        ("VALIGN", (0, 0), (0, -1), "TOP"), 
        ("ALIGN", (0, 0), (-1, 0), "CENTER"), 
        ("ALIGN", (-3, 1), (-1, -1), "RIGHT"), 
        #("ALIGN", (0, 1), (0, -1), "DECIMAL"), <- No puedo cambiar 
        #                               el pivotChar de "." a ",". No me vale.
        ("ALIGN", (-1, 1), (-1, -1), "CENTER"), 
        ("ALIGN", (0, 1), (0, -1), "CENTER"), 
        #("RIGHTPADDING", (0, 1), (0, -1), 0.75 * cm), 
        ]))
    return tabla
Ejemplo n.º 10
0
	def drawText(self,txt,x,y,w,h,style={}):
		margin = 0
		self.canvas.saveState()
		path = self.canvas.beginPath()
		path.rect(x,y,w,h)
		self.canvas.clipPath(path,stroke=1)
		_s = styles['BodyText']
		_s = ParagraphStyle({})
		_s.fontSize = style['fontSize']*1.0
		# _s.fontSize = style['fontSize']
		_s.leading = style['fontSize']
		print _s
		print 'writing text',txt,x,y
		while _s.fontSize > 1.0:
			p = Paragraph(txt.strip(),_s)	
			aw,ah =  p.wrapOn(self.canvas,w-margin*2,h-margin*2)
			print aw,w-margin*2,ah,h-margin*2,_s.fontSize
			break
			if (aw > w-margin*2) or (ah > h-margin*2):
				_s.fontSize = _s.fontSize - 1
				_s.leading = _s.fontSize*1.9
			else:
				break
		p.drawOn(self.canvas,x+margin,y+margin)
		self.canvas.restoreState()
Ejemplo n.º 11
0
    def getBody(self, story=None):
        story = story or self._story
        header_style = ParagraphStyle(name='header_style', fontSize=12, alignment=TA_CENTER)
        story.append(Paragraph('<b>{}</b>'.format(_('List of sessions')), header_style))

        text_style = ParagraphStyle(name='text_style', fontSize=8, alignment=TA_LEFT, leading=10, leftIndent=10)
        text_style.fontName = 'Times-Roman'
        text_style.spaceBefore = 0
        text_style.spaceAfter = 0
        text_style.firstLineIndent = 0

        rows = []
        row_values = []
        for col in [_('ID'), _('Type'), _('Title'), _('Code'), _('Description')]:
            row_values.append(Paragraph('<b>{}</b>'.format(col), text_style))
        rows.append(row_values)

        for sess in self.sessions:
            rows.append([
                Paragraph(sess.friendly_id, text_style),
                Paragraph(_('Poster') if sess.is_poster else _('Standard'), text_style),
                Paragraph(sess.title.encode('utf-8'), text_style),
                Paragraph(sess.code.encode('utf-8'), text_style),
                Paragraph(sess.description.encode('utf-8'), text_style)
            ])

        col_widths = (None,) * 5
        table_style = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('ALIGN', (0, 1), (-1, -1), 'LEFT')
        ])
        story.append(Table(rows, colWidths=col_widths, style=table_style))
        return story
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
 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
Ejemplo n.º 14
0
def build_tabla_totales(dic_totales):
    """
    Construye una tabla con los totales del presupuesto.
    La tabla tiene dos columnas. En la primera están las claves del 
    diccionario «dic_totales». En la segunda los valores correspondientes.
    La última fila de la tabla estará en negrita.
    Si el diccionario de totales trae una clave "orden" (que debería) se 
    seguirá ese orden para mostrarlos en las filas.
    """
    try:
        claves = dic_totales["orden"]
    except KeyError:
        claves = dic_totales.keys()
    datos = []
    for clave in claves:
        datos += [["", clave, dic_totales[clave]]]
    datos[-1][1] = Paragraph("<b>%s</b>" % datos[-1][1], 
                             estilos["BodyText"])
    a_derecha = ParagraphStyle("A derecha", 
                                parent = estilos["BodyText"])
    a_derecha.alignment = enums.TA_RIGHT
    datos[-1][-1] = Paragraph("<b>%s</b>" % datos[-1][-1], 
                              a_derecha)
    tabla = Table(datos, 
                  colWidths = (PAGE_WIDTH * 0.55,   # HACK: Para que ocupe lo  
                               PAGE_WIDTH * 0.15,   # mismo que la otra. 
                               PAGE_WIDTH * 0.2))   # Si no, RL la centra.
    tabla.setStyle(TableStyle([
        ("BOX", (1, 0), (-1, -1), 1.0, colors.black),
        ("INNERGRID", (1, 0), (-1, -1), 0.25, colors.black), 
        ("ALIGN", (1, 0), (-2, -1), "LEFT"), 
        ("ALIGN", (-1, 0), (-1, -1), "RIGHT"), 
        ]))
    return tabla
Ejemplo n.º 15
0
    def _content(self):
        # TODO: move styles somewhere else
        # style for additional information box
        ibs = ParagraphStyle('inputBoxStyle',styles['Message'])
        ibs.fontName = 'Courier'
        ibs.leftIndent = cm
        ibs.spaceBefore = 0.2*cm
        ibs.spaceAfter = 0.5*cm
        # font style for letter subject
        styles['Subject'].fontName = 'Helvetica-Bold'

        content = [
            Paragraph(_("auskunft_subject"), styles['Subject']),
            Paragraph(_("auskunft_greeting"), styles['Greeting']),
            Spacer(0,0.5*cm),
            Paragraph(_("auskunft_question_text"), styles['Message']),
            ListFlowable([
                ListItem(Paragraph(_("auskunft_question_1"),styles['Message'])),
                ListItem(Paragraph(_("auskunft_question_2"),styles['Message'])),
                ListItem(Paragraph(_("auskunft_question_3"),styles['Message'])),
                ListItem(Paragraph(_("auskunft_question_4"),styles['Message'])),
                ],
                bulletType='bullet',
                start='square'
            ),
            Paragraph(_("auskunft_reference"), styles['Message']),
            Paragraph(_("auskunft_par_10"), styles['Message']),
            Paragraph(_("auskunft_par_4"), styles['Message']),
            Paragraph(_("auskunft_par_12"), styles['Message']),

            Paragraph(_("auskunft_standard_application"), styles['Message'])
        ]

        # Registered Applications
        if self.table_apps:
            content += [
                Paragraph(_("auskunft_registered_application_pre"),styles['Message']),
                self.table_apps,
                Paragraph(_("auskunft_registered_application_post"),styles['Message'])
            ]

        # Additional Information
        if self.add_info:
            content += [
                Paragraph(_("auskunft_additional_info_text"), styles['Message']),
                Paragraph(self.add_info,ibs)
            ]

        content += [
            Paragraph(_("auskunft_method_identity"),styles['Message']),
            Paragraph(_("auskunft_expected_response"),styles['Message']),

            Spacer(0,0.5*cm),
            Paragraph(_("auskunft_signature"),styles['Signature']),
            Spacer(0,1.5*cm),
            Paragraph(self.sender_name,styles['Signature'])
        ]

        return content
Ejemplo n.º 16
0
Archivo: log.py Proyecto: 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)
Ejemplo n.º 17
0
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)
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)
Ejemplo n.º 19
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)
def get_prequal_eval_lines_table(prequal_eval_sobject):
    prequal_eval_lines_search = Search('twog/prequal_evaluation_line')
    prequal_eval_lines_search.add_filter('prequal_evaluation_code', prequal_eval_sobject.get_code())
    prequal_eval_lines = prequal_eval_lines_search.get_sobjects()

    # If no prequal eval lines exist for this report, return None so that the PDF won't display a table
    if not prequal_eval_lines:
        return None

    style_sheet = getSampleStyleSheet()
    style_sheet.font_size = 10

    prequal_eval_lines_table_data = [['Timecode', 'F', 'Description', 'Code', 'Scale', 'Sector/Ch', 'In Source']]

    lines_with_values = []
    lines_without_values = []

    for line in prequal_eval_lines:
        if line.get_value('timecode'):
            lines_with_values.append(line)
        else:
            lines_without_values.append(line)

    prequal_eval_lines = sorted(lines_with_values, key=lambda x: x.get_value('timecode'))
    prequal_eval_lines.extend(lines_without_values)

    for line in prequal_eval_lines:
        timecode = line.get('timecode')
        field = line.get('field')
        prequal_line_description = line.get('prequal_line_description')
        type_code = line.get('type_code')
        scale = line.get('scale')
        sector_or_channel = line.get('sector_or_channel')
        in_source = line.get('in_source')

        if any([timecode, field, prequal_line_description, type_code, scale, sector_or_channel, in_source]):
            description_paragraph_style = ParagraphStyle(prequal_line_description)
            description_paragraph_style.fontSize = 8
            description_paragraph = Paragraph(line.get('description'), description_paragraph_style)

            line_data = [timecode, field, description_paragraph, type_code, scale, sector_or_channel, in_source]

            prequal_eval_lines_table_data.append(line_data)

    prequal_eval_lines_table = Table(prequal_eval_lines_table_data, hAlign='LEFT', spaceBefore=5, spaceAfter=5,
                                     colWidths=[(.7 * inch), (.19 * inch), (inch * 2.6), (.4 * inch), (.82 * inch),
                                                (.19 * inch), (.75 * inch), (.3 * inch), (.55 * inch),
                                                (.55 * inch)])

    prequal_eval_lines_table.setStyle([('BOX', (0, 0), (-1, -1), 0.2, colors.black),
                                       ('INNERGRID', (0, 0), (-1, -1), 0.2, colors.black),
                                       ('FONTSIZE', (0, 0), (-1, -1), 8),
                                       ('LEFTPADDING', (0, 0), (-1, -1), 1),
                                       ('RIGHTPADDING', (0, 0), (-1, -1), 1)])

    return prequal_eval_lines_table
Ejemplo n.º 21
0
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
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
 def get_content(self, column_data, row_values, col_values):
     """ return the content of the cell, formated as define in the constructor or in the column object """
  
     res = self.get_raw_content(column_data, row_values, col_values)
     
     ps = ParagraphStyle('num_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(res, ps)                 
         
     return res
Ejemplo n.º 24
0
def generatePdf(startDate, endDate, data):
    fileName = 'timetable_%s-%s.pdf' % (startDate, endDate)
    
    vera = TTFont("Vera", "Vera.ttf")
    pdfmetrics.registerFont(vera)
    
    PAGESIZE = pagesizes.landscape(pagesizes.A4)
    doc = SimpleDocTemplate(fileName, pagesize = PAGESIZE)
    
    styles = getSampleStyleSheet()
    style = ParagraphStyle('style')
    style.fontName = 'Vera'
    style.fontSize = 15;
    style.alignment = 1
    
    elements = []
    elements.append(Paragraph("Urnik <i>%s - %s</i>" % (startDate, endDate), style))
    elements.append(Spacer(0, 20))
    
    header = ['Ura', 'Ponedeljek', 'Torek', 'Sreda', 'Četrtek', 'Petek']
    
    tableData = []
    tableData.append(header)
    
    for i in range(1, len(hours)):
        
        data1 = [hours[i]]
        for j in range(1, len(data)):
            hour = i
            match = [lecture for lecture in data[j] if lecture[3] <= hour <= lecture[4] - 1]
    
            # Found a lecture which is on schedule this hour
            if len(match) == 1:
                data1.append(unicode(match[0][0] + '\n' + match[0][1] + '\n' + match[0][2], 'utf-8', 'ignore'))
            else:
                data1.append('')
                
        tableData.append(data1)
    
    table = Table(tableData)
    table.setStyle(TableStyle([
                               ('TOPPADDING', (0, 0), (-1, -1), 1),
                               ('SPAN', (0, 0), (1, 1)),
                               ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                               ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
                               ('INNERGRID', (0, 0), (-1, -1), 0.2, colors.black),
                               ('BOX', (0, 0), (-1, -1), 0.2, colors.black)
                               ]))
    
    elements.append(table)
    doc.build(elements)
    
    return fileName
Ejemplo n.º 25
0
 def _processTOCPage(self):
     style1 = ParagraphStyle({})
     style1.fontName = "Times-Bold"
     style1.fontSize = modifiedFontSize(18, self._fontsize)
     style1.leading = modifiedFontSize(22, self._fontsize)
     style1.alignment = TA_CENTER
     p = Paragraph( _("Table of contents"), style1)
     self._story.append(Spacer(inch, 1*cm))
     self._story.append(p)
     self._story.append(Spacer(inch, 2*cm))
     self._story.append(self._toc)
     self._story.append(PageBreak())
Ejemplo n.º 26
0
Archivo: log.py Proyecto: dairdr/notes
	def drawConventions(self, canvas, doc):
		column_style = TableStyle([
			('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
			('BOX', (0, 0), (-1, -1), 0.25, colors.black),
			('TOPPADDING', (0, 0), (-1, -1), 6),
			('BACKGROUND', (0, 0), (-1, -1), colors.gray),
			('FONTSIZE', (0, 0), (-1, -1), 8),
			('ALIGN', (0, 0), (-1, -1), 'CENTER'),
			('VALIGN',(0, 0),(-1, -1),'MIDDLE')
		])

		style = ParagraphStyle(name='Style')
		style.fontName = 'Helvetica-Bold'
		style.fontSize = 7
		style.alignment = TA_CENTER
		data = [
			[Paragraph('CONVENCIONES ACERCA DE LA EVALUACIÓN POR DESEMPEÑOS SEGUN DECRETO 1290 DE 2009', style)]
		]
		table = Table(data, colWidths='*', rowHeights=0.15*inch, style=column_style)
		

		column_style = TableStyle([
			('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
			('BOX', (0, 0), (-1, -1), 0.25, colors.black),
			('TOPPADDING', (0, 0), (-1, -1), 5),
			('BACKGROUND', (0, 0), (-1, -1), '#CCCCCC'),
			('FONTSIZE', (0, 0), (-1, -1), 7),
			('ALIGN', (0, 0), (-1, -1), 'CENTER'),
			('VALIGN',(0, 0),(-1, -1),'MIDDLE')
		])
		data = [
			['DESEMPEÑO BAJO: 1.0 a 6.4', 'DESEMPEÑO BASICO: 6.5 a 7.9', 'DESEMPEÑO ALTO: 8.0 a 9.4', 'DESEMPEÑO SUPERIOR: 9.5 a 10']
		]
		table2 = Table(data, colWidths='*', rowHeights=0.15*inch, style=column_style)

		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 + 50)
Ejemplo n.º 27
0
def build_head2(texto, ancho_linea = PAGE_WIDTH - 5.5*cm, offset_linea = 0.0):
    """
    Devuelve el texto con el estilo de encabezado de 2º. nivel y el subrayado.
    """
    estilo_head2 = ParagraphStyle("Header2", 
                                  parent = estilos["Normal"])
    estilo_head2.fontSize = 14
    estilo_head2.fontName = "Times-Italic"
    estilo_head2.textColor = colors.gray
    texto = Paragraph(escribe(texto), estilo_head2)
    linea = LineaHorizontal(ancho_linea, offset = offset_linea, 
                            color = colors.green)
    return KeepTogether([texto, Spacer(1, 0.1*cm), linea, Spacer(1, 0.15*cm)])
Ejemplo n.º 28
0
def insert_line(text, margin=0, size=12, color=black):
    global ACTUAL_LINE
    s = ParagraphStyle('my_style')
    s.textColor = color
    s.fontSize = size
    s.fontName = "Helvetica"
    s.leftIndent = margin
    lines = simpleSplit(text, "Helvetica", size, aW - 25 * mm)
    for line in lines:
        p = Paragraph(line, s)
        p.wrapOn(pdf_file, aW, aH)
        p.drawOn(pdf_file, 10 * mm, ACTUAL_LINE * mm)
        ACTUAL_LINE -= 9
    def test2(self):
        sty = ParagraphStyle(name = 'normal')
        sty.fontName = 'Times-Roman'
        sty.fontSize = 10
        sty.leading = 12

        p = Paragraph('one two three',sty)
        p.wrap(20,36)
        self.assertEqual(len(p.split(20,24)),2) #widows allowed
        self.assertEqual(len(p.split(20,16)),0) #orphans disallowed
        p.allowWidows = 0
        self.assertEqual(len(p.split(20,24)),0) #widows disallowed
        p.allowOrphans = 1
        self.assertEqual(len(p.split(20,16)),2) #orphans allowed
Ejemplo n.º 30
0
    def drawMetadata(self):
        data = [('Artist', self.artist), ('Made', self.place), ('Date', self.date)]
        data = self.artist + ", " + self.date + ", " + self.place
#        self.canvas.setFont('TheSans', 12)
#        self.canvas.drawString(PAGE_HEIGHT*0.635, PAGE_WIDTH*0.86, data)

        parastyle = ParagraphStyle('pad')
        parastyle.textColor = 'black'
        parastyle.fontSize = 10
        parastyle.leading = 20
        parastyle.font = 'TheSans-Bold'
        paragraph = Paragraph(data, parastyle)
        paragraph.wrapOn(self.canvas, PAGE_HEIGHT*0.25, PAGE_WIDTH*0.1)
        paragraph.drawOn(self.canvas, PAGE_HEIGHT*0.635, PAGE_WIDTH*0.84)
Ejemplo n.º 31
0
        if ".png" in line:
            if len(line.split()) == 4:
                l, w, h, align = line.split()
                add_image(l, int(w), int(h), align)
            else:
                add_image(line)

        elif "ctime()" in line:
            add_text(time.ctime())
        else:
            add_text(line)
    doc.build(page)


styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
page = []

text = """
Pass Key:
Secret Key:
 
Hello,
This a key file to decrypt the encrypted message.

"""

if __name__ == "__main__":
    name, doc = make_doc("myform.pdf")
    show(text)
Ejemplo n.º 32
0
           title_pdf1, str_semana)
make_footer(pdf_rep1, 0, 0, sizex, 120., color_RGB2, path_elem)

# contenido panel 1
pdf_rep1.setFillColorRGB(color_RGB1[0] / 255., color_RGB1[1] / 255.,
                         color_RGB1[2] / 255.)
pdf_rep1.rect(10., 150., 545., 815., fill=False, stroke=True)
pdf_rep1.rect(10., 940., 470., 50., fill=True, stroke=True)
pdf_rep1.setFillColorRGB(1, 1, 1)
pdf_rep1.setFont("Avenir", 24)
pdf_rep1.drawString(25., 955., 'Precipitaciones sobre el Valle de Aburrá')

pdf_rep1.drawImage(path_elem+'ppt_rad/Evento.png', \
                25., 400., 520., 520., mask = 'auto')

style1 = ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontName='Avenir', fontSize=20,\
                       leading = 24)

par1 = Paragraph(
    u'Imagen de reflectividad del radar a las 03:46 del 12 de agosto, \
                    correspondiente al evento de precipitación con número de informe \
                    1182, en el cual se observa que durante el evento las precipitaciones \
                    alcanzaron a cubrir por completo el Valle de Aburrá con intensidades \
                    predominantemente bajas y algunos núcleos de intensidades altas \
                    en la ladera occidental de Medellín y norte de Barbosa.',
    style1)
par1.wrap(515, 890)
par1.drawOn(pdf_rep1, 25., 165)

# contenido panel 2
pdf_rep1.setFillColorRGB(color_RGB1[0] / 255., color_RGB1[1] / 255.,
                         color_RGB1[2] / 255.)
Ejemplo n.º 33
0
 def get_story(self):
     return [Paragraph("Hello World", ParagraphStyle("dummy"))]
Ejemplo n.º 34
0
class ArrlRadiogram:

    defaults = {'padding_top': 3, 'align': TA_LEFT}

    styles = {
        'default':
        ParagraphStyle(
            'default',
            fontName='Helvetica-Bold',
            fontSize=10,
            leading=5,
            leftIndent=0,
            rightIndent=0,
            firstLineIndent=0,
            alignment=TA_LEFT,
            spaceBefore=0,
            spaceAfter=0,
            bulletFontName='Helvetica',
            bulletFontSize=10,
            bulletIndent=0,
            textColor=blue,
            backColor=None,
            wordWrap=None,
            borderWidth=0,
            borderPadding=0,
            borderColor=None,
            borderRadius=None,
            allowWidows=1,
            allowOrphans=0,
            textTransform=None,  # 'uppercase' | 'lowercase' | None
            endDots=None,
            splitLongWords=1,
        ),
    }

    data_map = {
        'ARRL_MSG_NUMBER': {
            'align': TA_CENTER
        },
        'ARRL_MSG_PRECEDENCE': {
            'align': TA_CENTER
        },
        'ARRL_MSG_HX': {
            'align': TA_CENTER
        },
        'ARRL_MSG_STATION_OF_ORIGIN': {
            'align': TA_CENTER
        },
        'ARRL_MSG_CHECK': {
            'align': TA_CENTER
        },
        'ARRL_MSG_PLACE_OF_ORIGIN': {
            'align': TA_CENTER
        },
        'ARRL_MSG_TIME': {
            'align': TA_CENTER
        },
        'ARRL_MSG_DATE': {
            'align': TA_CENTER
        },
        'ARRL_MSG_ADDRESS': {},
        'ARRL_MSG_PHONE': {},
        'ARRL_MSG_EMAIL': {},
        'ARRL_MSG_WORD_1': {},
        'ARRL_MSG_WORD_2': {},
        'ARRL_MSG_WORD_3': {},
        'ARRL_MSG_WORD_4': {},
        'ARRL_MSG_WORD_5': {},
        'ARRL_MSG_WORD_6': {},
        'ARRL_MSG_WORD_7': {},
        'ARRL_MSG_WORD_8': {},
        'ARRL_MSG_WORD_9': {},
        'ARRL_MSG_WORD_10': {},
        'ARRL_MSG_WORD_11': {},
        'ARRL_MSG_WORD_12': {},
        'ARRL_MSG_WORD_13': {},
        'ARRL_MSG_WORD_14': {},
        'ARRL_MSG_WORD_15': {},
        'ARRL_MSG_WORD_16': {},
        'ARRL_MSG_WORD_17': {},
        'ARRL_MSG_WORD_18': {},
        'ARRL_MSG_WORD_19': {},
        'ARRL_MSG_WORD_20': {},
        'ARRL_MSG_WORD_21': {},
        'ARRL_MSG_WORD_22': {},
        'ARRL_MSG_WORD_23': {},
        'ARRL_MSG_WORD_24': {},
        'ARRL_MSG_WORD_25': {},
        'ARRL_STATION_CALLSIGN': {},
        'ARRL_STATION_PHONE': {},
        'ARRL_STATION_NAME': {},
        'ARRL_STATION_EMAIL': {},
        'ARRL_STATION_STREET': {},
        'ARRL_STATION_CITY_STATE_ZIP': {},
        'ARRL_RECD_FROM': {},
        'ARRL_RECD_DATE': {},
        'ARRL_RECD_TIME': {},
        'ARRL_SENT_TO': {},
        'ARRL_SENT_DATE': {},
        'ARRL_SENT_TIME': {}
    }
Ejemplo n.º 35
0
    def Imprimer(self, event=None):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.styles import ParagraphStyle

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

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

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

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

        # Tableau
        dataTableau = []
        largeurColonnesSuivantes = 70
        largeurColonne1 = largeur_page - 80 - 1.0 * (
            len(self.dictImpression["entete"]) - 1) * largeurColonnesSuivantes
        largeursColonnes = [
            largeurColonne1,
        ]
        for x in range(0, len(self.dictImpression["entete"]) - 1):
            largeursColonnes.append(largeurColonnesSuivantes)

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

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

            for ligne in listeLignes:
                dataTableau.append(ligne)

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

        # Formatage des lignes "Activités"
        for indexColoration, typeColoration in self.dictImpression[
                "coloration"]:

            if typeColoration == "activite":
                listeStyles.append(
                    ('FONT', (0, indexColoration + 1),
                     (-1, indexColoration + 1), "Helvetica-Bold", 7))
                listeStyles.append(
                    ('BACKGROUND', (0, indexColoration + 1),
                     (-1, indexColoration + 1), (0.91, 0.91, 0.91)))

            if typeColoration == "regroup":
                listeStyles.append(
                    ('FONT', (0, indexColoration + 1),
                     (-1, indexColoration + 1), "Helvetica-Bold", 7))
                listeStyles.append(('TEXTCOLOR', (0, indexColoration + 1),
                                    (-1, indexColoration + 1), (1, 1, 1)))
                listeStyles.append(('BACKGROUND', (0, indexColoration + 1),
                                    (-1, indexColoration + 1), (0, 0, 0)))

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

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
Ejemplo n.º 36
0
    def create_pdf(self):
        """
		Create a pdf
		"""
        story = []

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

        spacer = Spacer(0, 0.07 * inch)

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

        line = MCLine(-30, 470)
        story.append(line)
        story.append(spacer)

        text_data = [
            "#", "SP. Sys. Code", "SP. Code", "SP. Name", "SP. Cost",
            "SP. INV. QTY."
        ]
        d = []
        font_size = 8
        centered = ParagraphStyle(name="centered", alignment=TA_CENTER)
        for text in text_data:
            ptext = "<font size=%s><b>%s</b></font>" % (font_size, text)
            p = Paragraph(ptext, centered)
            d.append(p)

        data = [d]

        line_num = 1

        formatted_line_data = []

        for val in select_all_spare_parts():

            line_data = [
                str(line_num), val.gen_code, val.code, val.name, val.price,
                val.inv_qty
            ]

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

        table = Table(data,
                      colWidths=[50, 80, 80, 180, 50, 70],
                      rowHeights=20,
                      style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black)])
        story.append(table)
        story.append(spacer)

        matxtnum = '<font size=11><p><u>Manager</u><br/>Mohamed Althubiti</p></font>'
        pmatxtnum = Paragraph(matxtnum, centered)
        data = [['', '', '', '', pmatxtnum]]
        t = Table(data, colWidths=[150, 5, 250, 5, 150])
        t.setStyle(
            TableStyle([('LINEABOVE', (3, 2), (-1, -1), 0.25, colors.black)]))
        story.append(t)
        #########################################################################################

        story.append(spacer)

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

        subprocess.Popen([self.refile], shell=True)
    def build_index_Tafonomia(self, records, sito):

        if os.name == 'posix':
            home = os.environ['HOME']
        elif os.name == 'nt':
            home = os.environ['HOMEPATH']

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

        logo = Image(logo_path)
        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch
        logo.hAlign = "LEFT"

        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.fontSize = 8
        styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        ###################### ELENCO SCHEDE TAFONOMICHE ###########

        lst = []
        lst.append(logo)

        lst.append(Paragraph("<b>ELENCO SCHEDE TAFONOMICHE</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data), styH1))

        table_data = []
        for i in range(len(records)):
            exp_index = Tafonomia_index_pdf_sheet(records[i])
            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [50, 80, 80, 80, 100, 60, 50, 60, 60, 60, 60, 150]

        table_data_formatted = Table(table_data, colWidths, style=styles)
        table_data_formatted.hAlign = "LEFT"

        lst.append(table_data_formatted)
        # lst.append(Spacer(0,2))

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

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

        f.close()

        ###################### ELENCO SCHEDE STRUTTURE TAFONOMICHE ###########

        lst = []
        lst.append(logo)

        lst.append(
            Paragraph("<b>ELENCO SCHEDE STRUTTURE TAFONOMICHE</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data),
                      styH1))

        table_data = []
        for i in range(len(records)):
            exp_index = Tafonomia_index_II_pdf_sheet(records[i])
            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [50, 50, 40, 100, 60, 50, 50, 60, 60, 60, 80]

        table_data_formatted = Table(table_data, colWidths, style=styles)
        table_data_formatted.hAlign = "LEFT"

        lst.append(table_data_formatted)
        # lst.append(Spacer(0,2))

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

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

        f.close()
Ejemplo n.º 38
0
    def try_it(text,style,dedent,aW,aH):
        P=XPreformatted(text,style,dedent=dedent)
        dumpXPreformattedFrags(P)
        w,h = P.wrap(aW, aH)
        dumpXPreformattedLines(P)
        S = P.split(aW,aH)
        dumpXPreformattedLines(P)
        for s in S:
            s.wrap(aW,aH)
            dumpXPreformattedLines(s)
            aH = 500

    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    styleSheet = getSampleStyleSheet()
    B = styleSheet['BodyText']
    DTstyle = ParagraphStyle("discussiontext", parent=B)
    DTstyle.fontName= 'Helvetica'
    for (text,dedent,style, aW, aH, active) in [('''


The <font name=courier color=green>CMYK</font> or subtractive

method follows the way a printer
mixes three pigments (cyan, magenta, and yellow) to form colors.
Because mixing chemicals is more difficult than combining light there
is a fourth parameter for darkness.  For example a chemical
combination of the <font name=courier color=green>CMY</font> pigments generally never makes a perfect

black -- instead producing a muddy color -- so, to get black printers
don't use the <font name=courier color=green>CMY</font> pigments but use a direct black ink.  Because
<font name=courier color=green>CMYK</font> maps more directly to the way printer hardware works it may
Ejemplo n.º 39
0
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []
    a = story.append

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet['Heading2']
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet['Heading3']
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet['BodyText']
    btj = ParagraphStyle('bodyText1j', parent=bt, alignment=TA_JUSTIFY)
    btr = ParagraphStyle('bodyText1r', parent=bt, alignment=TA_RIGHT)
    btc = ParagraphStyle('bodyText1c', parent=bt, alignment=TA_CENTER)
    a(
        Paragraph(
            """
        <a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)""" %
            (time.ctime(946684800.0 if invariant else time.time()),
             len(story)), bt))

    for i in range(10):
        a(Paragraph('Heading 1 always starts a new page (%d)' % len(story),
                    h1))
        for j in range(3):
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            a(
                Paragraph(
                    'Heading 2 always starts a new frame (%d)' % len(story),
                    h2))
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            for j in range(3):
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=2) +
                        ' (%d)' % len(story), bt))
                a(
                    Paragraph(
                        'I should never be at the bottom of a frame (%d)' %
                        len(story), h3))
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=1) +
                        ' (%d)' % len(story), bt))

    for align, bts in [('left', bt), ('JUSTIFIED', btj), ('RIGHT', btr),
                       ('CENTER', btc)]:
        a(Paragraph('Now we do &lt;br/&gt; tests(align=%s)' % align, h1))
        a(Paragraph('First off no br tags', h3))
        a(Paragraph(_text1, bts))
        a(Paragraph("&lt;br/&gt; after 'the' in line 4", h3))
        a(
            Paragraph(_text1.replace('forms of the', 'forms of the<br/>', 1),
                      bts))
        a(Paragraph("2*&lt;br/&gt; after 'the' in line 4", h3))
        a(
            Paragraph(
                _text1.replace('forms of the', 'forms of the<br/><br/>', 1),
                bts))
        a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5", h3))
        a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/>', 1),
                    bts))
        a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5", h3))
        a(
            Paragraph(
                _text1.replace('I suggested ', 'I suggested<br/><br/>', 1),
                bts))
        a(Paragraph("&lt;br/&gt; at the end of the paragraph!", h3))
        a(Paragraph("""text one<br/>text two<br/>""", bts))
        a(Paragraph("Border with &lt;br/&gt; at the end of the paragraph!",
                    h3))
        bt1 = ParagraphStyle('bodyText1', bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""", bt1))
        a(Paragraph("Border no &lt;br/&gt; at the end of the paragraph!", h3))
        bt1 = ParagraphStyle('bodyText1', bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two""", bt1))
        a(Paragraph("Different border style!", h3))
        bt2 = ParagraphStyle('bodyText1', bt1)
        bt2.borderWidth = 1.5
        bt2.borderColor = colors.toColor('blue')
        bt2.backColor = colors.gray
        bt2.borderRadius = 3
        bt2.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""", bt2))
    for i in 0, 1, 2:
        P = Paragraph(
            """This is a paragraph with <font color='blue'><a href='#top'>with an incredibly
long and boring link in side of it that
contains lots and lots of stupidly boring and worthless information.
So that we can split the link and see if we get problems like Dinu's.
I hope we don't, but you never do Know.</a></font>""", bt)
        a(P)

    doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf'))
    doc.multiBuild(story)
Ejemplo n.º 40
0
def lista_productores_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 Proovedores</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 Productor.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
Ejemplo n.º 41
0
pdfMerger.write(OutputFile)

# Read newly created PDF to extract bookmarks
pdffile = PdfFileReader(OutputFile)
outlines = pdffile.outlines

# # Create Text File for fun
# f = open('bookmarks.txt',"w+")
# for x in outlines:
#     f.write('{:.<60} {:d}'.format(x.get("/Title"),x.get("/Page")+2)+'\n')
# f.close()

# Create PDF File
style = ParagraphStyle(
    name='Normal',
    fontName='Courier',
    fontSize=10,
)
story = []

pdf_name = 'bookmarks.pdf'
doc = SimpleDocTemplate(pdf_name,
                        pagesize=letter,
                        bottomMargin=.4 * inch,
                        topMargin=.6 * inch,
                        rightMargin=.8 * inch,
                        leftMargin=.8 * inch)

text_content = ""

for x in outlines:
Ejemplo n.º 42
0
def formato_menbrete_pdf():
    lista= []
    stylemenbrete= ParagraphStyle('Heading1')
    stylemenbrete.textColor=('black')
    stylemenbrete.alignment= TA_CENTER
    stylemenbrete.fontSize= 12
    stylemenbrete.spaceBefore= 5
    stylemenbrete.spaceAfter=5
    stylemenbrete.leading = 20
    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)
    nombre= Paragraph(datos.NOMBRE.upper(), stylemenbrete)
    #fin **********************************
    rif = Paragraph('RIF: %s'% (datos.RIF.upper()), stylemenbrete)
    direccion=Paragraph('DIRECCION: %s'% (datos.DIRECCION.upper()), stylemenbrete)
    telefonos =Paragraph('%s / %s'% (datos.TELEFONO, datos.CELULAR), stylemenbrete)
    codigo_postal=Paragraph('CODIGO POSTAL: %s'% (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)
Ejemplo n.º 43
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_LEFT
    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, 'fiscalizacion',
                         'PROVIDENCIA.pdf'), 'rb'))
    # create response object
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Fiscalizacion_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)
        fecha_codigo_y = 7 if page == 2 else 0
        y_minus = 15 if page == 2 else 0
        print_text_bold(unicode(documento.pst.razon_social), 220,
                        770 + y_minus, pdf)
        print_text_bold(unicode(documento.pst.rif), 220, 752 + y_minus, pdf)
        if documento.pst.rtn != None:
            text_rtn = unicode(documento.pst.rtn)
        else:
            text_rtn = u'S/RTN'
        print_text_bold(text_rtn, 220, 737 + y_minus, pdf)

        pdf.drawString(80, 830 + (y_minus - fecha_codigo_y),
                       unicode(documento.codigo))
        pdf.drawString(335, 830 + (y_minus - fecha_codigo_y), unicode(fecha))

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

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

        # datos de gerente
        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)
            # cuadro que contiene los datos del pst
            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, 'fiscalizacion',
                                 '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
Ejemplo n.º 44
0
 def __init__(self, *args, **kwargs):
     self.doc = SimpleDocTemplate("procuration.pdf",
                                  pagesize=A4,
                                  rightMargin=72,
                                  leftMargin=72,
                                  topMargin=120,
                                  bottomMargin=18)
     styles = getSampleStyleSheet()
     styles.add(
         ParagraphStyle(
             name='Justify',
             alignment=TA_JUSTIFY,
             fontSize=12,
         ))
     styles.add(
         ParagraphStyle(
             name='Center',
             alignment=TA_CENTER,
             fontSize=24,
         ))
     self.text = []
     ptext = '<b>Procuration</b>'
     self.text.append(Paragraph(ptext, styles["Center"]))
     self.text.append(Spacer(0, 50))
     p = '''Je soussignée [NOM SOCIETE] ([NUM TVA]) dont le siège est situé [RUE] [NUM] - [code postal] [COMMUNE] (BE),'''
     ptext = '%s' % p
     self.text.append(Paragraph(ptext, styles["Justify"]))
     p = '''Représenté(e) par : [Nom Gérant], N.N. : [numéro national], résidante à [adresse résidence] ;'''
     ptext = '%s' % p
     self.text.append(Paragraph(ptext, styles["Justify"]))
     self.text.append(Spacer(0, 10))
     p = '''En sa qualité de gérant de [NOM SOCIETE Sprl] ; [NUM TVA]'''
     ptext = '%s' % p
     self.text.append(Paragraph(ptext, styles["Justify"]))
     p = '''Dont le siège est situé [adresse siège] (BE)'''
     ptext = '%s' % p
     self.text.append(Paragraph(ptext, styles["Justify"]))
     self.text.append(Spacer(0, 10))
     p = '''Déclare par la présente donner mandat et procuration à L.G. & Associates SCSPRL – 29 avenue Reine Marie Henriette à 1190 Forest, BE0454.784.696, Cabinet de comptabilité agréé sous le numéro IPCF: 70483836, pouvant être représenté par Monsieur Olivier Guillaume ou l’un de ses collaborateurs pour :'''
     ptext = '%s' % p
     self.text.append(Paragraph(ptext, styles["Justify"]))
     self.text.append(Spacer(0, 10))
     ptext = '''<ul>
     <li>intervenir en leur nom et pour leur compte auprès de l’administration des contributions directes, de l’administration de la TVA et de l’enregistrement et des domaines pour signer et introduire les déclarations ;</li>
     <li>rédiger les réponses aux questions, aux demandes d’informations, aux avis de modifications, déclarations de régularisations et réclamations ;</li>
     <li>mener des discussions et signer des accords avec les services de contrôle et la direction et les représenter dans leurs relations avec les administrations précitées.</li>
     </ul>'''
     self.text.append(Paragraph(ptext, styles["Justify"]))
     self.text.append(Spacer(0, 10))
     p = '''De plus, tous les renseignements à cette fin peuvent être pris auprès de tierces personneset d’institutions et tous les documents nécessaires être signés par le mandataire.'''
     ptext = '%s' % p
     self.text.append(Paragraph(ptext, styles["Justify"]))
     self.text.append(Spacer(0, 10))
     p = '''Par ailleurs, le mandataire est autorisé à transférer à des tiers la présente procuration par le biais d’une procuration spéciale.'''
     ptext = '%s' % p
     self.text.append(Paragraph(ptext, styles["Justify"]))
     self.text.append(Spacer(0, 10))
     p = '''L’actuelle procuration restera valable hormis révocation écrite et expresse signifiée au mandataire et à l’Administration.'''
     ptext = '%s' % p
     self.text.append(Paragraph(ptext, styles["Justify"]))
     self.doc.build(self.text, canvasmaker=LGCanvas)
Ejemplo n.º 45
0
    def _drawItems(self, TOP, LEFT):  # noqa

        # Items
        i = self._drawItemsHeader(TOP, LEFT)
        self.pdf.setFont('DejaVu', 7)

        items_are_with_tax = self.invoice.use_tax

        # List
        will_wrap = False
        for item in self.invoice.items:
            if TOP - i < 30 * mm:
                will_wrap = True

            style = ParagraphStyle('normal', fontName='DejaVu', fontSize=7)
            p = Paragraph(item.description, style)
            p2 = Paragraph(item.commits, style)

            pwidth, pheight = p.wrapOn(
                self.pdf, 70 * mm if items_are_with_tax else 120 * mm, 30 * mm)
            i_add = max(float(pheight) / mm, 4.23)

            pwidth2, pheight2 = p2.wrapOn(
                self.pdf, 70 * mm if items_are_with_tax else 115 * mm, 30 * mm)
            i_add2 = max(float(pheight2) / mm, 4.23)

            if will_wrap and TOP - i - i_add - i_add2 < 8 * mm:
                will_wrap = False
                self.pdf.rect(LEFT * mm, (TOP - i) * mm, (LEFT + 156) * mm,
                              (i + 2) * mm,
                              stroke=True,
                              fill=False)  # 140,142
                self.pdf.showPage()

                i = self._drawItemsHeader(self.TOP, LEFT)
                TOP = self.TOP
                self.pdf.setFont('DejaVu', 7)

            # leading line
            path = self.pdf.beginPath()
            path.moveTo(LEFT * mm, (TOP - i + 3.5) * mm)
            path.lineTo((LEFT + 176) * mm, (TOP - i + 3.5) * mm)
            self.pdf.setLineWidth(0.1)
            self.pdf.drawPath(path, True, True)
            self.pdf.setLineWidth(1)

            i += i_add
            p.drawOn(self.pdf, (LEFT + 1) * mm, (TOP - i + 3) * mm)
            i += i_add2
            p2.drawOn(self.pdf, (LEFT + 5) * mm, (TOP - (i) + 3) * mm)

            i1 = i - i_add2
            i1 -= 4.23

            if items_are_with_tax:
                if float(int(item.count)) == item.count:
                    self.pdf.drawRightString(
                        (LEFT + 85) * mm, (TOP - i1) * mm,
                        u'%s %s' % (locale.format(
                            "%i1", item.count, grouping=True), item.unit))
                else:
                    self.pdf.drawRightString(
                        (LEFT + 85) * mm, (TOP - i1) * mm,
                        u'%s %s' % (locale.format(
                            "%.2f", item.count, grouping=True), item.unit))
                self.pdf.drawRightString(
                    (LEFT + 110) * mm, (TOP - i1) * mm,
                    currency(item.price, self.invoice.currency,
                             self.invoice.currency_locale))
                self.pdf.drawRightString(
                    (LEFT + 134) * mm, (TOP - i1) * mm,
                    currency(item.total, self.invoice.currency,
                             self.invoice.currency_locale))
                self.pdf.drawRightString((LEFT + 144) * mm, (TOP - i1) * mm,
                                         '%.0f %%' % item.tax)
                self.pdf.drawRightString(
                    (LEFT + 173) * mm, (TOP - i1) * mm,
                    currency(item.total_tax, self.invoice.currency,
                             self.invoice.currency_locale))
                i1 += 5
            else:
                if float(int(item.count)) == item.count:
                    self.pdf.drawRightString(
                        (LEFT + 135) * mm, (TOP - i1) * mm,
                        u'%s %s' % (locale.format(
                            "%i1", item.count, grouping=True), item.unit))
                else:
                    self.pdf.drawRightString(
                        (LEFT + 135) * mm, (TOP - i1) * mm,
                        u'%s %s' % (locale.format(
                            "%.2f", item.count, grouping=True), item.unit))
                self.pdf.drawRightString(
                    (LEFT + 156) * mm, (TOP - i1) * mm,
                    currency(item.price, self.invoice.currency,
                             self.invoice.currency_locale))
                self.pdf.drawRightString(
                    (LEFT + 173) * mm, (TOP - i1) * mm,
                    currency(item.total, self.invoice.currency,
                             self.invoice.currency_locale))
                i1 += 5

        if will_wrap:
            self.pdf.rect(LEFT * mm, (TOP - i) * mm, (LEFT + 156) * mm,
                          (i + 2) * mm,
                          stroke=True,
                          fill=False)  # 140,142
            self.pdf.showPage()

            i = 0
            TOP = self.TOP
            self.pdf.setFont('DejaVu', 7)

        if self.invoice.rounding_result:
            path = self.pdf.beginPath()
            path.moveTo(LEFT * mm, (TOP - i) * mm)
            path.lineTo((LEFT + 176) * mm, (TOP - i) * mm)
            i += 5
            self.pdf.drawPath(path, True, True)
            self.pdf.drawString((LEFT + 1) * mm, (TOP - i) * mm,
                                _(u'Rounding'))
            self.pdf.drawString(
                (LEFT + 68) * mm, (TOP - i) * mm,
                currency(self.invoice.difference_in_rounding,
                         self.invoice.currency, self.invoice.currency_locale))
            i += 3

        path = self.pdf.beginPath()
        path.moveTo(LEFT * mm, (TOP - i) * mm)
        path.lineTo((LEFT + 176) * mm, (TOP - i) * mm)
        self.pdf.drawPath(path, True, True)

        if not items_are_with_tax:
            self.pdf.setFont('DejaVu-Bold', 11)
            self.pdf.drawString(
                (LEFT + 100) * mm, (TOP - i - 7) * mm,
                '%s: %s' % (_(u'Total'),
                            currency(self.invoice.price, self.invoice.currency,
                                     self.invoice.currency_locale)))
        else:
            self.pdf.setFont('DejaVu-Bold', 6)
            self.pdf.drawString((LEFT + 1) * mm, (TOP - i - 2) * mm,
                                _(u'Breakdown VAT'))
            vat_list, tax_list, total_list, total_tax_list = [
                _(u'VAT rate')
            ], [_(u'Tax')], [_(u'Without VAT')], [_(u'With VAT')]
            for vat, items in self.invoice.generate_breakdown_vat().items():
                vat_list.append("%s%%" % locale.format('%.2f', vat))
                tax_list.append(
                    currency(items['tax'], self.invoice.currency,
                             self.invoice.currency_locale))
                total_list.append(
                    currency(items['total'], self.invoice.currency,
                             self.invoice.currency_locale))
                total_tax_list.append(
                    currency(items['total_tax'], self.invoice.currency,
                             self.invoice.currency_locale))

            self.pdf.setFont('DejaVu', 6)
            text = self.pdf.beginText((LEFT + 1) * mm, (TOP - i - 5) * mm)
            text.textLines(vat_list)
            self.pdf.drawText(text)

            text = self.pdf.beginText((LEFT + 11) * mm, (TOP - i - 5) * mm)
            text.textLines(tax_list)
            self.pdf.drawText(text)

            text = self.pdf.beginText((LEFT + 27) * mm, (TOP - i - 5) * mm)
            text.textLines(total_list)
            self.pdf.drawText(text)

            text = self.pdf.beginText((LEFT + 45) * mm, (TOP - i - 5) * mm)
            text.textLines(total_tax_list)
            self.pdf.drawText(text)

            # VAT note
            if self.invoice.client.vat_note:
                text = self.pdf.beginText((LEFT + 1) * mm, (TOP - i - 11) * mm)
                text.textLines([self.invoice.client.vat_note])
                self.pdf.drawText(text)

            self.pdf.setFont('DejaVu-Bold', 11)
            self.pdf.drawString(
                (LEFT + 100) * mm,
                (TOP - i - 14) * mm,
                u'%s: %s' %
                (_(u'Total with tax'),
                 currency(self.invoice.price_tax, self.invoice.currency,
                          self.invoice.currency_locale)),
            )

        if items_are_with_tax:
            self.pdf.rect(LEFT * mm, (TOP - i - 17) * mm, (LEFT + 156) * mm,
                          (i + 19) * mm,
                          stroke=True,
                          fill=False)  # 140,142
        else:
            self.pdf.rect(LEFT * mm, (TOP - i - 11) * mm, (LEFT + 156) * mm,
                          (i + 13) * mm,
                          stroke=True,
                          fill=False)  # 140,142

        self._drawCreator(TOP - i - 20, self.LEFT + 98)
Ejemplo n.º 46
0
def print_bill_school(request, a_id):

    school = request.user.school
    now = datetime.now().date()
    response = HttpResponse(content_type='application/pdf')

    response['Content-Disposition'] = 'attachment; filename="Facture' + str(
        school.id) + "-" + str(datetime.now().strftime('%Y%m%d')) + ".pdf"
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            topMargin=0.3 * inch,
                            leftMargin=0.3 * inch,
                            rightMargin=0.3 * inch,
                            bottomMargin=0.3 * inch)

    sample_style_sheet = getSampleStyleSheet()

    sacado = ParagraphStyle(
        'sacado',
        fontSize=20,
        leading=26,
        borderPadding=0,
        alignment=TA_CENTER,
    )

    elements = []
    title_black = ParagraphStyle(
        'title',
        fontSize=20,
    )
    subtitle = ParagraphStyle(
        'title',
        fontSize=16,
        textColor=colors.HexColor("#00819f"),
    )
    normal = ParagraphStyle(
        name='Normal',
        fontSize=10,
    )
    normalr = ParagraphStyle(name='Normal', fontSize=12, alignment=TA_RIGHT)

    logo = Image('https://sacado.xyz/static/img/sacadoA1.png')
    logo_tab = [[
        logo,
        "ASSOCIATION SACADO.XYZ \n2B avenue de la pinède \n83400 La Capte Hyères \nFrance"
    ]]
    logo_tab_tab = Table(logo_tab,
                         hAlign='LEFT',
                         colWidths=[0.7 * inch, 5 * inch])

    elements.append(logo_tab_tab)
    elements.append(Spacer(0, 0.2 * inch))

    try:
        accounting = Accounting.objects.get(id=a_id,
                                            school=school,
                                            is_active=1)
    except:
        messages.error(request, "Violation de droit. Accès interdit.")
        return redirect("index")

    paragraph0 = Paragraph(accounting.objet, sacado)
    elements.append(paragraph0)
    elements.append(Spacer(0, 0.5 * inch))

    school_datas = "REF : " + accounting.chrono + "\n\n" + school.name + "\n" + school.code_acad + "\n" + str(
        school.nbstudents
    ) + " élèves \n" + school.address + "\n" + school.town + ", " + school.country.name
    demandeur = school_datas + "\n\nMontant de la cotisation : " + str(
        school.amount) + "€"

    demandeur_tab = [[
        demandeur,
        "ASSOCIATION SACADO.XYZ \n2B avenue de la pinède \n83400 La Capte \nHyères \nFrance \n\n\n\n"
    ]]
    demandeur_tab_tab = Table(demandeur_tab,
                              hAlign='LEFT',
                              colWidths=[5 * inch, 2 * inch])

    elements.append(demandeur_tab_tab)
    elements.append(Spacer(0, 0.2 * inch))

    my_texte_ = "Sous réserve du bon fonctionnement de son hébergeur LWS, l'association SACADO met l'ensemble des fonctionnalités du site https://sacado.xyz à disposition des enseignants de l'établissement sus-mentionné et dénommé par " + school.name + "."
    paragraph = Paragraph(my_texte_, normal)
    elements.append(paragraph)
    elements.append(Spacer(0, 0.2 * inch))

    my_texte = "La cotisation est acquittée le " + str(
        accounting.date.strftime('%d-%m-%Y')) + "."

    paragraph = Paragraph(my_texte, normal)
    elements.append(paragraph)
    elements.append(Spacer(0, 1 * inch))

    my__texte = "Le trésorier Bruno Serres "

    paragraf = Paragraph(my__texte, normal)
    elements.append(paragraf)

    doc.build(elements)

    return response
Ejemplo n.º 47
0
    def draw_footer(self):
        from corehq.apps.domain.views import DomainBillingStatementsView

        totals_x = inches(5.85)
        line_height = inches(0.25)
        subtotal_y = inches(3.5)
        tax_y = subtotal_y - line_height
        credit_y = tax_y - line_height
        total_y = credit_y - (line_height * 2)

        totals_money_x = totals_x + inches(1)

        self.canvas.setFillColorRGB(*LIGHT_GRAY)
        self.canvas.rect(
            inches(5.7),
            inches(2.3),
            inches(2.05),
            inches(0.5),
            fill=1
        )
        self.canvas.setFillColorRGB(*BLACK)

        self.canvas.drawString(totals_x, subtotal_y, "Subtotal:")
        self.canvas.drawString(totals_x, tax_y,
                               "Tax (%0.2f%%):" % self.tax_rate)
        self.canvas.drawString(totals_x, credit_y, "Credit:")
        self.canvas.drawString(totals_x, total_y, "Total:")
        self.canvas.drawString(
            totals_money_x,
            subtotal_y,
            get_money_str(self.subtotal)
        )
        self.canvas.drawString(
            totals_money_x,
            tax_y,
            get_money_str(self.applied_tax)
        )
        self.canvas.drawString(
            totals_money_x,
            credit_y,
            get_money_str(self.applied_credit)
        )
        self.canvas.drawString(
            totals_money_x,
            total_y,
            get_money_str(self.total)
        )

        self.canvas.setFontSize(SMALL_FONT_SIZE)
        self.canvas.drawString(inches(5.85), inches(2.1),
                               "Thank you for using CommCare HQ.")
        self.canvas.setFontSize(DEFAULT_FONT_SIZE)

        width = inches(5.00)
        left_x = inches(0.5)

        options = "PAYMENT OPTIONS:"
        self.canvas.setFontSize(SMALL_FONT_SIZE)
        options_text = Paragraph(options, ParagraphStyle(''))
        options_text.wrapOn(self.canvas, width, inches(.12))
        options_text.drawOn(self.canvas, left_x, inches(3.5))
        self.canvas.setFontSize(DEFAULT_FONT_SIZE)

        flywire = """<strong>International payments:</strong>
Make payments in your local currency
via bank transfer or credit card by following this link:
<link href='{flywire_link}' color='blue'>{flywire_link}</link><br />""".format(
            flywire_link="https://wl.flywire.com/?destination=DMG"
        )
        flywire_text = Paragraph(flywire, ParagraphStyle(''))
        flywire_text.wrapOn(self.canvas, width, inches(.4))
        flywire_text.drawOn(self.canvas, left_x, inches(2.95))

        credit_card = """<strong>Credit card payments (USD)</strong> can be made online here:<br />
<link href='{payment_page}' color='blue'>{payment_page}</link><br />""".format(
            payment_page=absolute_reverse(
                DomainBillingStatementsView.urlname, args=[self.project_name])
        )
        credit_card_text = Paragraph(credit_card, ParagraphStyle(''))
        credit_card_text.wrapOn(self.canvas, width, inches(.5))
        credit_card_text.drawOn(self.canvas, left_x, inches(2.4))

        ach_or_wire = """<strong>ACH or Wire:</strong> If you make payment via ACH
or Wire, please make sure to email
<font color='blue'>{invoicing_contact_email}</font>
so that we can match your payment to the correct invoice.  Please include:
Invoice No., Project Space, and payment date in the email. <br />""".format(
            invoicing_contact_email=settings.INVOICING_CONTACT_EMAIL,
        )
        ach_or_wire_text = Paragraph(ach_or_wire, ParagraphStyle(''))
        ach_or_wire_text.wrapOn(self.canvas, width, inches(.5))
        ach_or_wire_text.drawOn(self.canvas, left_x, inches(1.7))

        ach_payment_text = """<strong>ACH payment</strong>
(preferred over wire payment for transfer in the US):<br />
Bank: {bank_name}
Bank Address: {bank_address}
Account Number: {account_number}
Routing Number or ABA: {routing_number_ach}<br />""".format(
            bank_name=self.bank_name,
            bank_address=self.bank_address,
            account_number=self.account_number,
            routing_number_ach=self.routing_number_ach
        )
        wire_payment_text = """<strong>Wire payment</strong>:<br />
Bank: {bank_name}
Bank Address: {bank_address}
Account Number: {account_number}
Routing Number or ABA: {routing_number_wire}
Swift Code: {swift_code}<br/>""".format(
            bank_name=self.bank_name,
            bank_address=self.bank_address,
            account_number=self.account_number,
            routing_number_wire=self.routing_number_wire,
            swift_code=self.swift_code
        )
        payment_info2 = Paragraph('\n'.join([
            ach_payment_text,
            wire_payment_text,
        ]), ParagraphStyle(''))
        payment_info2.wrapOn(self.canvas, width - inches(0.1), inches(0.9))
        payment_info2.drawOn(self.canvas, inches(0.6), inches(0.5))
Ejemplo n.º 48
0
 def estiloPC(self):
     """
     :return: estilo para cuerpo del reporte
     """
     return ParagraphStyle(name="centrado", alignment=TA_CENTER)
Ejemplo n.º 49
0
    def Main_Body(self):
        self.width, self.height = A4 
        self.left_margin = 50
        self.c.drawImage(r"d:\workspace\prj_klnz\bn_ibbl.jpg", self.left_margin + 180, self.top_y_pos, 180, 19)
        self.c.drawImage(r"d:\workspace\prj_klnz\ibbl.jpg", self.left_margin+141, self.top_y_pos - 15, 35, 35)
        self.c.setFont("Helvetica", 12)
        self.top_y_pos -= 15
        self.c.drawImage(r"d:\workspace\prj_klnz\ar_ibbl.jpg", self.left_margin + 180, self.top_y_pos, 180, 19)
        self.top_y_pos -= 10
        self.c.drawString(self.left_margin + 180, self.top_y_pos, "Islami Bank Bangladesh Limited")
        self.top_y_pos -= 15
        self.c.setFont("Helvetica", 10)
        self.c.drawString(self.left_margin + 210, self.top_y_pos, "Zonal Office, Khulna")
        self.top_y_pos -= 15
        self.c.setFont("Helvetica", 8)
        self.c.drawString(self.left_margin + 150, self.top_y_pos, "Khulna Shopping Complex, 4, Old Jessore Road, Khulna, Bangladesh")
        self.top_y_pos -= 7
        self.c.line(self.left_margin, self.top_y_pos, 570, self.top_y_pos)

        self.c.setFont("Helvetica", 10)
        self.top_y_pos -= 17
        self.c.drawString(self.left_margin, self.top_y_pos, "Ref.IBBL/ZO/KLN/Incre-2015/ID-203051/")
        self.c.drawString(self.left_margin + 447, self.top_y_pos, "Date: 12.03.2016")

        self.top_y_pos -= 67
        styles = getSampleStyleSheet()
        # create return address
        address = """
        <b>Jb. Muhammad Moinuddin</b> <br/>
        Asstt. Officer Gr.-I<br/>
        Islami Bank Bangladesh Limited <br/>
        Zonal Office <br/>
        Khulna
        """
        p = Paragraph(address, styles["Normal"])
        p.wrapOn(self.c, self.width-60, self.height)
        p.drawOn(self.c, self.left_margin, self.top_y_pos)

        self.top_y_pos -= 27
        styles = getSampleStyleSheet()
        # create return address
        subject = """
        <b>Sub: <u>Annual Increment.</u></b> <br/>
        """
        p = Paragraph(subject, styles["Normal"])
        p.wrapOn(self.c, self.width-60, self.height)
        p.drawOn(self.c, self.left_margin + 210, self.top_y_pos)

        self.top_y_pos -= 17
        self.c.drawString(self.left_margin, self.top_y_pos, "Muhtaram,")
        self.top_y_pos -= 17
        self.c.drawString(self.left_margin, self.top_y_pos, "Assalamu Alaikum.")

        self.top_y_pos -= 47
        ptext = """
        We are pleased to sanction you an Annual Increment of Tk. 770/- per month with effect from
        14.10.2015 in the scale of pay of Tk.14,950-770x4-18,030-EB-840x6-23,070-910x3-25,800/-
        raising your basic pay from Tk. 15,720/- to Tk. 16,490/- only together with other admissible
        allowance in the grade.
        """ 
        styles.add(ParagraphStyle(name='Justify', alignment=TA_LEFT))
        p = Paragraph(ptext, styles["Normal"])
        p.wrapOn(self.c, self.width-60, self.height)
        p.drawOn(self.c, self.left_margin, self.top_y_pos)

        self.top_y_pos -= 17
        styles = getSampleStyleSheet()
        subject = """
        Your next Annual Increment will fall due on <b><u>14.10.2016</u></b> <br/>
        """
        p = Paragraph(subject, styles["Normal"])
        p.wrapOn(self.c, self.width-60, self.height)
        p.drawOn(self.c, self.left_margin, self.top_y_pos)

        self.top_y_pos -= 17
        self.c.drawString(self.left_margin, self.top_y_pos, "Ma-assalam.")
        self.top_y_pos -= 17
        self.c.drawString(self.left_margin, self.top_y_pos, "Yours faithfully,")
        self.top_y_pos -= 17
        self.c.drawString(self.left_margin + 20, self.top_y_pos, "Sd/-")

        self.top_y_pos -= 17
        styles = getSampleStyleSheet()
        subject = """
        <b>(Abu Naser Mohammed Nazmul Bari)</b>
        """
        p = Paragraph(subject, styles["Normal"])
        p.wrapOn(self.c, self.width-60, self.height)
        p.drawOn(self.c, self.left_margin, self.top_y_pos)

        self.top_y_pos -= 17
        styles = getSampleStyleSheet()
        subject = """
        <u>EXECUTIVE VICE PRESIDENT & HEAD OF ZONE</u>
        """
        p = Paragraph(subject, styles["Normal"])
        p.wrapOn(self.c, self.width-60, self.height)
        p.drawOn(self.c, self.left_margin, self.top_y_pos)

        self.CC_Footer()

        self.c.showPage()
        self.c.save()
Ejemplo n.º 50
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
Ejemplo n.º 51
0
    def draw_table(self):
        origin_x = inches(0.5)
        origin_y = inches(6.72)
        self.canvas.translate(origin_x, origin_y)

        height = inches(2.9)
        description_x = inches(2.4)
        quantity_x = inches(3.15)
        rate_x = inches(3.9)
        subtotal_x = inches(5.1)
        credits_x = inches(6.0)
        total_x = inches(7.25)
        header_height = inches(0.3)

        self.canvas.rect(0, 0, total_x, -height)
        self.canvas.setFillColorRGB(*LIGHT_GRAY)
        self.canvas.rect(0, 0, total_x, header_height,
                         fill=1)
        self.canvas.setFillColorRGB(*BLACK)
        self.canvas.line(description_x, header_height, description_x, -height)
        self.canvas.line(quantity_x, header_height, quantity_x, -height)
        self.canvas.line(rate_x, header_height, rate_x, -height)
        self.canvas.line(subtotal_x, header_height, subtotal_x, -height)
        self.canvas.line(credits_x, header_height, credits_x, -height)

        self.canvas.setFontSize(SMALL_FONT_SIZE)
        self.canvas.drawCentredString(midpoint(0, description_x),
                                      inches(0.1),
                                      "PRODUCT")
        self.canvas.drawCentredString(midpoint(description_x, quantity_x),
                                      inches(0.1),
                                      "QUANTITY")
        self.canvas.drawCentredString(midpoint(quantity_x, rate_x),
                                      inches(0.1),
                                      "UNIT COST")
        self.canvas.drawCentredString(midpoint(rate_x, subtotal_x),
                                      inches(0.1),
                                      "SUBTOTAL")
        self.canvas.drawCentredString(midpoint(subtotal_x, credits_x),
                                      inches(0.1),
                                      "CREDITS")
        self.canvas.drawCentredString(midpoint(credits_x, total_x),
                                      inches(0.1),
                                      "TOTAL")
        self.canvas.setFontSize(DEFAULT_FONT_SIZE)

        coord_y = 0
        for item_index in range(len(self.items)):
            if coord_y < -height:
                raise InvoiceError("Cannot fit line items on invoice")
            item = self.items[item_index]

            description = Paragraph(item.description,
                                    ParagraphStyle('',
                                                   fontSize=12,
                                                   ))
            description.wrapOn(self.canvas, description_x - inches(0.2),
                               -header_height)
            coord_y -= description.height + inches(0.05)
            description.drawOn(self.canvas, inches(0.1), coord_y)
            self.canvas.drawCentredString(
                midpoint(description_x, quantity_x),
                coord_y,
                str(item.quantity)
            )
            self.canvas.drawCentredString(
                midpoint(quantity_x, rate_x),
                coord_y,
                get_money_str(item.unit_cost)
            )
            self.canvas.drawCentredString(
                midpoint(rate_x, subtotal_x),
                coord_y,
                get_money_str(item.subtotal)
            )
            self.canvas.drawCentredString(
                midpoint(subtotal_x, credits_x),
                coord_y,
                get_money_str(item.credits)
            )
            self.canvas.drawCentredString(
                midpoint(credits_x, total_x),
                coord_y,
                get_money_str(item.total)
            )
            coord_y -= inches(0.1)
            self.canvas.line(0, coord_y, total_x, coord_y)

        self.canvas.translate(-origin_x, -origin_y)
Ejemplo n.º 52
0
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
Ejemplo n.º 53
0
    def __init__(self, versie):
        self.date = datetime.datetime.now()

        self.bedrijfsnaam = "Syntrus"

        self.defaultPageSize = letter
        self.PAGE_HEIGHT = self.defaultPageSize[1]
        self.PAGE_WIDTH = self.defaultPageSize[0]
        self.styles = getSampleStyleSheet()

        self.version = versie
        self.Topleft = f"PVE SAREF {self.version}"
        self.BijlageDisclaimer = f"Bijlages van regels zijn in het mapje BasisBijlages, bijlagen van opmerkingen in het mapje OpmerkingBijlages."
        self.GeaccepteerdDisclaimer = f"Geaccepteerde statussen zijn in het groen."
        self.NietGeaccepteerdDisclaimer = (
            f"Niet geaccepteerde statussen zijn in het rood.")
        self.Topright = "CONCEPT"
        self.Centered = "PARAMETERS"
        self.Bottomleft = "%s-%s-%s" % (
            self.date.strftime("%d"),
            self.date.strftime("%m"),
            self.date.strftime("%Y"),
        )

        self.LeftPadding = 22
        self.BottomPadding = 20
        self.TopPadding = 33
        self.RightPadding = 55
        self.TopRightPadding = 0
        self.kostenverschil = 0

        self.InhoudWidth = self.PAGE_WIDTH - self.LeftPadding - (
            self.RightPadding / 3)

        self.OpmerkingBoxPadding = self.PAGE_HEIGHT - (self.TopPadding * 2)
        self.OpmerkingBoxTitelHeight = 20
        self.OpmerkingBoxHeight = -150
        self.PrePVEBoxHeight = -75
        self.logo = "./utils/logo.png"

        self.hoofdstukStyle = ParagraphStyle(
            textColor=colors.Color(red=1, green=1, blue=1),
            backColor=colors.Color(red=49 / 255,
                                   green=133 / 255,
                                   blue=154 / 255),
            name="Normal",
            fontName="Calibri-Bold",
            fontSize=8,
            leading=12,
        )

        self.paragraafStyle = ParagraphStyle(
            textColor=colors.Color(red=33 / 255,
                                   green=89 / 255,
                                   blue=103 / 255),
            bg=colors.Color(red=182 / 255, green=221 / 255, blue=232 / 255),
            backColor=colors.Color(red=182 / 255,
                                   green=221 / 255,
                                   blue=232 / 255),
            name="Normal",
            fontName="Calibri-Bold",
            fontSize=8,
            leftIndent=30,
        )

        self.regelStyle = ParagraphStyle(name="Normal",
                                         fontName="Calibri",
                                         fontSize=8,
                                         leftIndent=60)

        self.regelStyleSwitch = ParagraphStyle(
            backColor=colors.Color(red=218 / 255,
                                   green=237 / 255,
                                   blue=242 / 255),
            name="Normal",
            fontName="Calibri",
            fontSize=8,
            leftIndent=60,
        )

        self.regelStyleOpmrk = ParagraphStyle(
            name="Normal",
            fontName="Calibri",
            fontSize=8,
            leftIndent=60,
            textColor=colors.red,
        )
        self.regelStyleOpmrkGreen = ParagraphStyle(
            name="Normal",
            fontName="Calibri",
            fontSize=8,
            leftIndent=60,
            textColor=colors.green,
        )
        self.regelStyleOpmrkOrange = ParagraphStyle(
            name="Normal",
            fontName="Calibri",
            fontSize=8,
            leftIndent=60,
            textColor=colors.orange,
        )

        self.regelStyleSwitchOpmrk = ParagraphStyle(
            backColor=colors.Color(red=218 / 255,
                                   green=237 / 255,
                                   blue=242 / 255),
            name="Normal",
            fontName="Calibri",
            fontSize=8,
            leftIndent=60,
            textColor=colors.red,
        )
        self.regelStyleSwitchOpmrkGreen = ParagraphStyle(
            backColor=colors.Color(red=218 / 255,
                                   green=237 / 255,
                                   blue=242 / 255),
            name="Normal",
            fontName="Calibri",
            fontSize=8,
            leftIndent=60,
            textColor=colors.green,
        )
        self.regelStyleSwitchOpmrkOrange = ParagraphStyle(
            backColor=colors.Color(red=218 / 255,
                                   green=237 / 255,
                                   blue=242 / 255),
            name="Normal",
            fontName="Calibri",
            fontSize=8,
            leftIndent=60,
            textColor=colors.orange,
        )
Ejemplo n.º 54
0
    def get_styles(self):
        pdfmetrics.registerFont(TTFont(
            'SimSun', '../fonts/SimSun.ttf'))  # 默认不支持中文,需要注册字体
        pdfmetrics.registerFont(TTFont(
            'SimSunBd', '../fonts/SimSun-bold.ttf'))  # 默认不支持中文,需要注册字体

        # registerFontFamily('SimSun', normal='SimSun', bold='SimSunBd', italic='VeraIt', boldItalic='VeraBI')

        stylesheet = getSampleStyleSheet()  # 获取样式集

        # 获取reportlab自带样式
        Normal = stylesheet['Normal']
        BodyText = stylesheet['BodyText']
        Italic = stylesheet['Italic']
        Title = stylesheet['Title']
        Heading1 = stylesheet['Heading1']
        Heading2 = stylesheet['Heading2']
        Heading3 = stylesheet['Heading3']
        Heading4 = stylesheet['Heading4']
        Heading5 = stylesheet['Heading5']
        Heading6 = stylesheet['Heading6']
        Bullet = stylesheet['Bullet']
        Definition = stylesheet['Definition']
        Code = stylesheet['Code']

        # 自带样式不支持中文,需要设置中文字体,但有些样式会丢失,如斜体Italic。有待后续发现完全兼容的中文字体
        Normal.fontName = 'SimSun'
        Italic.fontName = 'SimSun'
        BodyText.fontName = 'SimSun'
        Title.fontName = 'SimSunBd'
        Heading1.fontName = 'SimSun'
        Heading2.fontName = 'SimSun'
        Heading3.fontName = 'SimSun'
        Heading4.fontName = 'SimSun'
        Heading5.fontName = 'SimSun'
        Heading6.fontName = 'SimSun'
        Bullet.fontName = 'SimSun'
        Definition.fontName = 'SimSun'
        Code.fontName = 'SimSun'

        # 添加自定义样式
        stylesheet.add(
            ParagraphStyle(
                name='body',
                fontName="SimSun",
                fontSize=10,
                textColor='black',
                leading=20,  # 行间距
                spaceBefore=0,  # 段前间距
                spaceAfter=10,  # 段后间距
                leftIndent=0,  # 左缩进
                rightIndent=0,  # 右缩进
                firstLineIndent=20,  # 首行缩进,每个汉字为10
                alignment=TA_JUSTIFY,  # 对齐方式

                # bulletFontSize=15,       #bullet为项目符号相关的设置
                # bulletIndent=-50,
                # bulletAnchor='start',
                # bulletFontName='Symbol'
            ))
        body = stylesheet['body']
        return {
            "Normal": Normal,
            "Italic": Italic,
            "BodyText": BodyText,
            "Title": Title,
            "Heading1": Heading1,
            "Heading2": Heading2,
            "Heading3": Heading3,
            "Heading4": Heading4,
            "Heading5": Heading5,
            "Heading6": Heading6,
            "Bullet": Bullet,
            "Definition": Definition,
            "Code": Code,
            "body": body
        }
Ejemplo n.º 55
0
    def createFiche_Train(self):
        """
            Fonction qui créé une fiche liée uniquement à la réservation d'un train.
            Dans l'ordre sur la fiche :
            - le demandeur (avec la date de la demande) et le 1er voyageur (saut de page).
            - la liste des voyageurs (saut de page a chaque voyageur ajouté).
            - les détails de la réservation et les compléments (dont le lien avec fiche hôtel ou non).
            Les informations viennent de différents dictionnaires : infos_perso (ConvNameInfo)pour le demandeur, voyage pour les voyageurs (ConvVoyage),
            voyage (et a l'intérieur les dictionnaires aller et retour) pour les détails de réservation de train (ConvVoyage), complement pour motif et commentaires (ConvVoyage).
            La fonction parcout tous ses dictionnaires.
            Utilisation du module python reportlab pour la création de fichier.
            Le fichier est créé et stocké dans le dossier stockagefiche. La fonction sendmail permet ensuite de détruire ce fichier.
        """

        outfilename = 'fichetrain' + self.infos_perso.get(
            'nom') + self.infos_perso.get('prenom') + str(
                self.numbertrain) + '.pdf'
        outfiledir = './Fiche/stockagefiche/train'
        outfilepath = os.path.join(outfiledir, outfilename)
        doc = SimpleDocTemplate(outfilepath,
                                pagesize=A4,
                                rightMargin=60,
                                leftMargin=50,
                                topMargin=50,
                                bottomMargin=25)

        Story = []
        styles = getSampleStyleSheet()

        styles.add(
            ParagraphStyle(name='Justify',
                           alignment=TA_JUSTIFY,
                           fontName="Times-Roman"))
        texte = '<font size=34><strong>Fiche Voyage n°' + str(
            self.numbertrain) + '</strong></font>'
        Story.append(Paragraph(texte, styles["Justify"]))
        Story.append(Spacer(1, 32))
        texte = 'Catégorie : Billeterie et Réservation'
        texte2 = '<font size=14>' + texte + '</font>'
        Story.append(Paragraph(texte2, styles["Justify"]))
        Story.append(Spacer(1, 10))
        if 'hotel' in self.voyage.keys():
            texte = "Information complémentaire : Lien avec la fiche hotel n° " + str.capitalize(
                str(self.numberhotel))
            texte2 = "<font size=14>" + texte + "</font>"
            Story.append(Paragraph(texte2, styles["Justify"]))
        Story.append(Spacer(1, 30))
        im = Image(logoMNT, 2 * inch, 2 * inch)
        Story.append(im)
        Story.append(Spacer(1, 16))
        texte = '<font size=14><strong>Catégorie : Information Demandeur</strong></font>'
        Story.append(Paragraph(texte, styles["Justify"]))
        Story.append(Spacer(1, 10))
        texte = 'Nom : ' + str.capitalize(self.infos_perso.get('nom'))
        texte2 = '<font size=11>' + texte + '</font>'
        Story.append(Paragraph(texte2, styles["Justify"]))
        Story.append(Spacer(1, 4))
        texte = 'Prénom : ' + str.capitalize(self.infos_perso.get('prenom'))
        texte2 = '<font size=11>' + texte + '</font>'
        Story.append(Paragraph(texte2, styles["Justify"]))
        Story.append(Spacer(1, 4))
        texte = 'E-mail : ' + self.infos_perso.get('mail')
        texte2 = '<font size=11>' + texte + '</font>'
        Story.append(Paragraph(texte2, styles["Justify"]))
        Story.append(Spacer(1, 4))
        date_today = str(self.date.day) + '/' + str(
            self.date.month) + '/' + str(self.date.year)
        texte = 'Date de la demande : ' + str(date_today)
        texte2 = '<font size=11>' + texte + '</font>'
        Story.append(Paragraph(texte2, styles["Justify"]))
        Story.append(Spacer(1, 10))
        if 'voyageurs' in self.voyage.keys():
            texte = '<font size=14><strong>Catégorie : Information Voyageur(s) </strong></font>'
            Story.append(Paragraph(texte, styles["Justify"]))
            Story.append(Spacer(1, 10))
            voyageur = self.voyage.get('voyageurs')
            i = 0
            while i < len(voyageur):
                texte = '<font size=12><strong> Voyageur n°' + str(
                    i + 1) + '</strong></font>'
                Story.append(Paragraph(texte, styles["Justify"]))
                Story.append(Spacer(1, 10))
                voyageur_i = voyageur[i]
                if 'nom' in voyageur_i.keys() and 'prenom' in voyageur_i.keys(
                ) and 'mail' in voyageur_i.keys():
                    texte = "Nom : " + str.capitalize(voyageur_i.get('nom'))
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = " Prénom : " + str.capitalize(
                        voyageur_i.get('prenom'))
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = "E-Mail : " + voyageur_i.get('mail')
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = 'Numéro de téléphone : ' + voyageur_i.get(
                        'telephone')
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = 'Statut : ' + str.capitalize(
                        voyageur_i.get('statut'))
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = 'Lieu de travail : ' + str.capitalize(
                        voyageur_i.get('lieu_de_travail'))
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = 'Section ou service : ' + voyageur_i.get(
                        'section_service')
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = 'Date de naissance : ' + voyageur_i.get(
                        'date_de_naissance')
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = 'Grand Voyageur : ' + str.capitalize(
                        voyageur_i.get('grand_voyageur'))
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    texte = 'Carte de réduction : ' + str.capitalize(
                        voyageur_i.get('reductions'))
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
                    Story.append(Spacer(1, 10))
                    i += 1
                    Story.append(PageBreak())
                    Story.append(im)
                    Story.append(Spacer(1, 20))
        texte = '<font size=14><strong>Catégorie : Détails du voyage </strong></font>'
        Story.append(Paragraph(texte, styles["Justify"]))
        Story.append(Spacer(1, 10))
        if 'aller' in self.voyage.keys():
            texte = '<font size=11><strong> Catégorie : Aller </strong></font>'
            Story.append(Paragraph(texte, styles["Justify"]))
            Story.append(Spacer(1, 7))
            aller = self.voyage.get('aller')
            if 'départ' in aller.keys() and 'arrivée' in aller.keys(
            ) and 'jour' in aller.keys():
                texte = "Départ : " + str.capitalize(aller.get('départ'))
                texte2 = "<font size=11>" + texte + "</font>"
                Story.append(Paragraph(texte2, styles["Justify"]))
                Story.append(Spacer(1, 4))
                texte = " Arrivée : " + str.capitalize(aller.get('arrivée'))
                texte2 = "<font size=11>" + texte + "</font>"
                Story.append(Paragraph(texte2, styles["Justify"]))
                Story.append(Spacer(1, 4))
                texte = "Date : " + aller.get('jour')
                texte2 = "<font size=11>" + texte + "</font>"
                Story.append(Paragraph(texte2, styles["Justify"]))
                Story.append(Spacer(1, 4))
                if 'heure' in aller.keys():
                    texte = "Horaires : " + aller.get('heure')
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
            Story.append(Spacer(1, 10))
        if 'retour' in self.voyage.keys():
            texte = '<font size=11><strong> Catégorie : Retour </strong></font>'
            Story.append(Paragraph(texte, styles["Justify"]))
            Story.append(Spacer(1, 7))
            retour = self.voyage.get('retour')
            if 'départ' in retour.keys() and 'arrivée' in retour.keys(
            ) and 'jour' in retour.keys():
                texte = "Départ : " + str.capitalize(retour.get('départ'))
                texte2 = "<font size=11>" + texte + "</font>"
                Story.append(Paragraph(texte2, styles["Justify"]))
                Story.append(Spacer(1, 4))
                texte = " Arrivée : " + str.capitalize(retour.get('arrivée'))
                texte2 = "<font size=11>" + texte + "</font>"
                Story.append(Paragraph(texte2, styles["Justify"]))
                Story.append(Spacer(1, 4))
                texte = "Date : " + retour.get('jour')
                texte2 = "<font size=11>" + texte + "</font>"
                Story.append(Paragraph(texte2, styles["Justify"]))
                Story.append(Spacer(1, 4))
                if 'heure' in retour.keys():
                    texte = "Horaires : " + retour.get('heure')
                    texte2 = "<font size=11>" + texte + "</font>"
                    Story.append(Paragraph(texte2, styles["Justify"]))
                    Story.append(Spacer(1, 4))
            Story.append(Spacer(1, 10))
        Story.append(Spacer(1, 10))
        texte = '<font size=14><strong>Catégorie : Complément </strong></font>'
        Story.append(Paragraph(texte, styles["Justify"]))
        Story.append(Spacer(1, 7))
        motif = self.complement.get('motif')
        commentaires = self.complement.get('commentaires')
        texte = "Motif : " + str.capitalize(motif)
        texte2 = "<font size=11>" + texte + "</font>"
        Story.append(Paragraph(texte2, styles["Justify"]))
        Story.append(Spacer(1, 4))
        texte = "Commentaires : " + str.capitalize(commentaires)
        texte2 = "<font size=11>" + texte + "</font>"
        Story.append(Paragraph(texte2, styles["Justify"]))
        Story.append(Spacer(1, 4))
        if 'hotel' in self.voyage.keys():
            texte = "Autre : Lien avec la fiche hotel n° " + str.capitalize(
                str(self.numberhotel))
            texte2 = "<font size=11>" + texte + "</font>"
            Story.append(Paragraph(texte2, styles["Justify"]))
        else:
            texte = "Autre : Pas de fiche hôtel liée."
            texte2 = "<font size=11>" + texte + "</font>"
            Story.append(Paragraph(texte2, styles["Justify"]))
        if 'retour' in self.voyage.keys() or 'aller' in self.voyage.keys():
            doc.build(Story,
                      onFirstPage=self.addPageInfo,
                      onLaterPages=self.addPageInfo)
        else:
            return None
Ejemplo n.º 56
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, 'fiscalizacion', 'CONSTANCIA.pdf'),
            'rb'))
    # create response object
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Fiscalizacion_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, 'fiscalizacion',
                             '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
Ejemplo n.º 57
0
 def estiloPR(self):
     """
     :return: estilo para encabezado del reporte
     """
     return ParagraphStyle(name="derecha", alignment=TA_RIGHT)
Ejemplo n.º 58
0
 def estiloPL(self):
     """
     :return: estilo para descripcion del reporte
     """
     return ParagraphStyle(name="izquierda", alignment=TA_LEFT)
Ejemplo n.º 59
0
def cedula_hallazgo(documento):
    domicilio, gerente, supervisor, funcionarios, apoyo = documento_info(
        documento)

    output = PdfFileWriter()
    # create response object
    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename=Cedula_de_Hallazgo.pdf'

    buffer = StringIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=50,
                            bottomMargin=100)
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER, fontSize=8))
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              fontSize=8))

    Story = []

    I = Image(os.path.join(settings.BASE_DIR, 'static', 'img', 'logo.png'))
    I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth
    I.drawWidth = 1.25 * inch
    data = [[I, '', '', '', '', ''], ['SUJETO PASIVO:', '', '', '', '', ''],
            ['MATERIA:', '', '', '', '', '']]
    data[0][2] = Paragraph(
        u'''<b>CEDULA DE HALLAZGOS<br/>
                            Contribución Especial del 1% por la Presentación de<br/>
                            Servicios Turísticos</b>''', styles["Center"])
    data[0][4] = documento.codigo
    data[1][1] = documento.pst.nombre_o_razon()
    data[1][3] = 'RIF: ' + documento.pst.rif
    data[2][1] = documento.hallazgos_materia
    data[2][3] = 'PERIODO: ' + documento.fecha_notificacion.strftime(
        "%d/%m/%Y")
    w = [80, 30, 90, 90, 80, 80]
    Story.append(
        Table(data,
              colWidths=w,
              style=[('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                     ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                     ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                     ('FONTSIZE', (0, 0), (-1, -1), 8),
                     ('SPAN', (0, 0), (1, 0)), ('SPAN', (2, 0), (3, 0)),
                     ('SPAN', (4, 0), (5, 0)), ('SPAN', (1, 1), (2, 1)),
                     ('SPAN', (1, 2), (2, 2)), ('SPAN', (3, 1), (5, 1)),
                     ('SPAN', (3, 2), (5, 2))]))
    Story.append(Spacer(1, 12))

    data = [['CONDICIÓN', 'CRITERIO', 'EFECTO', 'EVIDENCIA'], ['', '', '', ''],
            ['', '', '', '']]
    try:
        data[2][0] = Paragraph(documento.hallazgos_condicion,
                               styles["Justify"])
        data[2][1] = Paragraph(documento.hallazgos_criterio, styles["Justify"])
        data[2][2] = Paragraph(documento.hallazgos_efecto, styles["Justify"])
        data[2][3] = Paragraph(documento.hallazgos_evidencia,
                               styles["Justify"])
    except:
        pass
    Story.append(
        Table(data,
              colWidths=[95, 170, 81, 105],
              style=[
                  ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                  ('GRID', (0, 2), (-1, 2), 0.25, colors.black),
                  ('FONTSIZE', (0, 0), (-1, -1), 8),
                  ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                  ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                  ('VALIGN', (0, 2), (-1, 2), 'TOP'),
              ]))
    Story.append(Spacer(1, 12))

    ptext = 'Observaciones: <u>%s</u>' % documento.observaciones
    Story.append(Paragraph(ptext, styles['Normal']))
    Story.append(Spacer(1, 12))

    Story.append(
        Paragraph('Fiscal Actuante: %s' % gerente.get_full_name(),
                  styles['Normal']))
    Story.append(
        Paragraph('Supervisor: %s' % supervisor.get_full_name(),
                  styles['Normal']))

    doc.build(Story)

    watermark = PdfFileReader(buffer)
    output.addPage(watermark.getPage(0))
    output.write(response)
    return response
Ejemplo n.º 60
0
def export_pdf_all_students_school(request):

    school = request.user.school
    today = datetime.now()
    scolar_year = this_year_from_today(today)
    subjects = []
    teacher = request.user.teacher

    elements = []

    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'attachment; filename="export_pdf_all_students_school_' + scolar_year + '.pdf"'

    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            topMargin=0.3 * inch,
                            leftMargin=0.3 * inch,
                            rightMargin=0.3 * inch,
                            bottomMargin=0.3 * inch)

    sample_style_sheet = getSampleStyleSheet()

    sacado = ParagraphStyle(
        'sacado',
        fontSize=20,
        leading=26,
        borderPadding=0,
        alignment=TA_CENTER,
    )

    title = ParagraphStyle(
        'title',
        fontSize=20,
        textColor=colors.HexColor("#00819f"),
    )

    subtitle = ParagraphStyle(
        'title',
        fontSize=16,
        textColor=colors.HexColor("#00819f"),
    )

    normal = ParagraphStyle(
        name='Normal',
        fontSize=12,
    )
    style_cell = TableStyle([('SPAN', (0, 1), (1, 1)),
                             ('TEXTCOLOR', (0, 1), (-1, -1),
                              colors.Color(0, 0.7, 0.7))])

    subjects = Subject.objects.all()

    for user in school.users.filter(user_type=0).order_by(
            "student__level", "last_name"):

        logo = Image('D:/uwamp/www/sacado/static/img/sacadoA1.png')

        logo_tab = [[
            logo,
            "SACADO \nBilan de compétences - Année scolaire " + scolar_year
        ]]
        logo_tab_tab = Table(logo_tab,
                             hAlign='LEFT',
                             colWidths=[0.7 * inch, 5 * inch])
        logo_tab_tab.setStyle(
            TableStyle([('TEXTCOLOR', (0, 0), (-1, 0),
                         colors.Color(0, 0.5, 0.62))]))
        elements.append(logo_tab_tab)
        elements.append(Spacer(0, 0.1 * inch))

        paragraph = Paragraph(
            user.last_name + " " + user.first_name + " - " +
            user.student.level.name, title)
        elements.append(paragraph)
        elements.append(Spacer(0, 1 * inch))

        for subject in subjects:
            elements.append(Spacer(0, 0.5 * inch))
            groups = subject.subject_group.filter(students=user.student)
            g_name = "-"
            for g in groups:
                g_name += g.teacher.user.last_name + " - "

            paragraph = Paragraph(subject.name + " - " + g_name, title)
            elements.append(paragraph)

            elements.append(Spacer(0, 0.5 * inch))
            ##########################################################################
            #### Gestion des compétences
            ##########################################################################
            sk_tab = []
            skills = Skill.objects.filter(subject=subject)

            for skill in skills:

                resultlastskills = skill.student_resultskill.filter(
                    student=user.student)
                point = 0
                i = 1
                for rs in resultlastskills:
                    point += rs.point
                    i += 1
                if point == 0:
                    sc = "N.E"
                elif i > 1:
                    sc = str(round(point / (i - 1), 0)) + "%"
                else:
                    sc = str(point) + "%"
                sk_tab.append([skill.name, sc])

            skill_tab = Table(sk_tab,
                              hAlign='LEFT',
                              colWidths=[5.2 * inch, 1 * inch])
            skill_tab.setStyle(
                TableStyle([
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]))

            elements.append(skill_tab)

        elements.append(PageBreak())

    doc.build(elements)
    return response