Beispiel #1
0
def firstPageSR():
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.platypus import Paragraph, Frame
    from reportlab.lib.colors import orange

    c = Canvas("out/firstPageSR.pdf", landscape(A4))
    body = Frame(cm, cm, 19 * cm, 20 * cm, showBoundary=1)
    right = Frame(20 * cm, cm, 6 * cm, 20 * cm, showBoundary=1)
    style = ParagraphStyle(styles["Normal"])
    style2 = styles["BodyText"]
    style.textColor = orange
    style.fontSize = 60

    imgPhoenix = Image("phoenix.jpg", 5 * cm, 5 * cm)
    imgPhoenix.hAlign = 'RIGHT'
    imgPhoenix.vAlign = 'TOP'
    imgOrange = Image("orange.jpg", 2 * cm, 2 * cm)
    imgOrange.hAlign = 'RIGHT'
    imgOrange.vAlign = 'BOTTOM'
    StoryRight = [imgPhoenix]
    p = Paragraph("Team Beluga", style2)
    StoryRight.append(p)
    StoryRight.append(imgOrange)

    StoryBody = [Paragraph("<b>Sprint Review</b>", style)]
    p = Paragraph("Sprint N 13", style2)
    StoryBody.append(p)

    body.addFromList(StoryBody, c)
    right.addFromList(StoryRight, c)
    c.save()
Beispiel #2
0
 def insertImage(self, image, size=None, align=None):
     if size and isinstance(size, (int, float)):
         image = Image(image, width=size * cm, height=size * cm)
         if align:
             image.hAlign = align
         else:
             image.hAlign = 'LEFT'
         self.data.append(image)
     else:
         self.data.append(Image(image))
Beispiel #3
0
    def build(self):
        doc = TagDocTemplate(self.out_file)
        doc.addPageTemplates([BackgroundTemplate(
            'qringly.pdf', name='background')])

        story = []
        style = styles['Normal']
        
        # FIXME: The tempfiles are handled in an ugly manner.
        tempfiles = []
        for sticker in self.stickers:
            try:
                handle, tmp = mkstemp('_qrtag.png')
                os.close(handle)
                img = sticker.build()
                img.save(tmp, 'png')
                scaled_size = INNER_WIDTH - 4 * PAD
                story.append(NextPageTemplate('background'))
                qr_img = PDFImage(tmp, width=scaled_size, height=scaled_size)
                qr_img.hAlign = 'CENTER'
                story.append(Spacer(INNER_WIDTH, 2 * PAD))
                story.append(qr_img)
                story.append(Paragraph(sticker.line, line_style))
                story.append(PageBreak())
            finally:
                tempfiles.append(tmp)

        doc.build(story)
        for tmp in tempfiles:
            os.remove(tmp)
Beispiel #4
0
def create_header(overview, language, title_style, style1, style2):
    story = []
    story.append(
        Paragraph(
            "<strong>{}</strong>".format(get_field(overview, 'name',
                                                   language)), title_style))
    story.append(Spacer(1, .30 * inch))
    story.append(
        Paragraph(
            "<strong>{}</strong>".format(
                get_field(overview, 'subtitle', language)), style1))
    story.append(Spacer(1, .18 * inch))
    if language == 'mn':
        h3 = "<strong>Үүрэг Амлалтын Хэрэгжилтийн Байдал 2020</strong>"
        img = Image('{}status_key.jpg'.format(file_url),
                    width=480,
                    height=41.076)
    else:
        h3 = "<strong>Status of Commitments as of May 2020</strong>"
        img = Image('{}graphics.jpg'.format(file_url),
                    width=360,
                    height=41.076)
    story.append(Paragraph(h3, style2))
    img.hAlign = 'RIGHT'
    story.append(img)
    return story
Beispiel #5
0
    def __init__(self, conn, logtype):
        self.conn = conn
        self.DATA_TYPE = logtype
        
        doc = SimpleDocTemplate(
            self.PDF_NAME,
            pagesize=A4,
            bottomMargin=.4 * inch,
            topMargin=.6 * inch,
            rightMargin=.8 * inch,
            leftMargin=.8 * inch)
        """ with open("your_text_file.txt", "r") as txt_file:
            text_content = txt_file.read() """
        logo = "report/logo.png"
        im = Image(logo, 1 * inch, 1 * inch)
        im.hAlign = 'LEFT'
        self.flowables.append(im)
        self.flowables.append(Spacer(1, 18))
        P = Paragraph(self.REPORT_HEADER,  styles['Normal_CENTER'])
        self.flowables.append(P)
        self.flowables.append(Spacer(1, 1*inch))

        if logtype == 1:
            for i in logtypes:
                self.DATA_TYPE = i
                self.drawTable()
                self.drawPlots()
        else:
            self.drawTable()
            self.drawPlots()
        

        doc.build(
            self.flowables,
        )
Beispiel #6
0
 def get_image(self, path, width=3*inch, alignement='LEFT'):
     img = utils.ImageReader(path)
     iw, ih = img.getSize()
     aspect = ih / float(iw)
     final_im = Image(path, width=width, height=(width * aspect))
     final_im.hAlign = alignement
     return final_im
Beispiel #7
0
    def getTable(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT
        styNormal.fontSize = 6

        conn = Connection()

        thumb_path = conn.thumb_path()
        thumb_path_str = thumb_path['thumb_path']
        latitude = Paragraph("<b>Latitude</b><br/>" + str(self.latitude),
                             styNormal)
        longitude = Paragraph("<b>Longitude</b><br/>" + str(self.longitude),
                              styNormal)
        name_vessel = Paragraph(
            "<b>Name Vessel</b><br/>" + str(self.name_vessel), styNormal)
        foto = Paragraph("<b>Photo ID</b><br/>" + str(self.foto), styNormal)
        decription = Paragraph(
            "<b>Description</b><br/>" + str(self.description), styNormal)
        #us_presenti = Paragraph("<b>US-USM presenti</b><br/>", styNormal)

        logo = Image(self.thumbnail)
        logo.drawHeight = 1 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1 * inch
        logo.hAlign = "CENTER"

        thumbnail = logo
        data = [foto, thumbnail, latitude, longitude, name_vessel, decription]

        return data
Beispiel #8
0
    def _header_footer(canvas,doc):
        #guardamos el estado de nuestro canvas , para poder dibujar en el 
        canvas.saveState()
        canvas.setTitle("Cotizacion Cliente")
        styles = getSampleStyleSheet()

        #header
        header = Image('/home/borbolla/metrology/static_media/assets/images/borbolla_metrology_logo.jpg' )
        header.drawHeight = 60
        header.drawWidth = 424
        header.hAlign = 'RIGHT'
        w , h = header.wrap(doc.width , doc.topMargin)
        header.drawOn(canvas , doc.leftMargin , 700)
        
        marcas = Image('/home/borbolla/metrology/static_media/assets/images/marcas.png' )
        marcas.drawWidth = 90
        marcas.drawHeight = 477
        marcas.drawOn(canvas , 20,200) 
        
        marcas2 = Image('/home/borbolla/metrology/static_media/assets/images/logo.png' )
        marcas2.drawWidth = 116
        marcas2.drawHeight = 34
        marcas2.drawOn(canvas , 20,150) 

        # Footer
        footer = Paragraph('www.borbollametrology.com', styles['Normal'])
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, h)
 
        # Release the canvas
        canvas.restoreState()
Beispiel #9
0
 def add_section_sequences(self, plots=[], stats=None):
     section = self.get_section_number()
     subsection = itertools.count(1)
     plots = sorted(list(plots), key=lambda x : x[1].basecalling)
     if stats is not None:
         self.story.append(Paragraph("{:d} Basecalling".format(section), self.heading_style))
         self.story.append(Spacer(1, 0))
         self.story.append(Paragraph("{:d}.{:d} Summary".format(section, next(subsection)), self.heading2_style))
         #['Tag', 'Basecalling', 'Sum', 'Mean', 'Median', 'N50', 'Maximum']
         header = ['', ''] + list(stats.columns.values[2:])
         table_data = [header] + [[y if isinstance(y, str) else '{:.0f}'.format(y) for y in x] for x in stats.values]
         table_style = [ ('FONTSIZE', (0,0), (-1, -1), 10),
                         ('LINEABOVE', (0,1), (-1,1), 0.5, colors.black),
                         ('LINEBEFORE', (2,0), (2,-1), 0.5, colors.black),
                         ('ALIGN', (0,0), (1,-1), 'LEFT'),
                         ('ALIGN', (2,0), (-1,-1), 'RIGHT')]
         self.story.append(Table(table_data, style=table_style))
         self.story.append(Spacer(1, 0))
     for key, group in itertools.groupby(plots, lambda x : x[1].basecalling):
         self.story.append(Paragraph('{:d}.{:d} {}:'.format(section, next(subsection), key.capitalize()), self.heading2_style))
         for plot_file, plot_wildcards in sorted(list(group), key=lambda x : x[1].i):
             im = svg2rlg(plot_file)
             im = Image(im, width=im.width * self.plot_scale, height=im.height * self.plot_scale)
             im.hAlign = 'CENTER'
             self.story.append(im)
             self.story.append(Spacer(1, 0))
     self.story.append(Spacer(1, 0.5*cm))
Beispiel #10
0
    def firstPage(self):
        img = Image('static/lr.png', kind='proportional')
        img.drawHeight = 0.5*inch
        img.drawWidth = 2.4*inch
        img.hAlign = 'LEFT'
        self.elements.append(img)

        spacer = Spacer(30, 100)
        self.elements.append(spacer)

        img = Image('static/ohka.png')
        img.drawHeight = 2.5*inch
        img.drawWidth = 5.5*inch
        self.elements.append(img)

        spacer = Spacer(10, 250)
        self.elements.append(spacer)

        psDetalle = ParagraphStyle('Resumen', fontSize=9, leading=14, justifyBreaks=1, alignment=TA_LEFT, justifyLastLine=1)
        text = """REPORTE DE SERVICIOS PROFESIONALES<br/>
        Empresa: Nombre del Cliente<br/>
        Fecha de Inicio: 23-Oct-2019<br/>
        Fecha de actualización: 01-Abril-2020<br/>
        """
        paragraphReportSummary = Paragraph(text, psDetalle)
        self.elements.append(paragraphReportSummary)
        self.elements.append(PageBreak())
    def getTable(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT
        styNormal.fontSize = 6

        conn = Connection()

        thumb_path = conn.thumb_path()
        thumb_path_str = thumb_path['thumb_path']
        area = Paragraph("<b>Area</b><br/>" + str(self.area), styNormal)

        us = Paragraph("<b>Artefact ID</b><br/>" + str(self.us), styNormal)
        foto = Paragraph("<b>Photo ID</b><br/>" + str(self.foto), styNormal)
        decription = Paragraph(
            "<b>Description</b><br/>" + str(self.description), styNormal)
        #us_presenti = Paragraph("<b>US-USM presenti</b><br/>", styNormal)

        logo = Image(self.thumbnail)
        logo.drawHeight = 1 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1 * inch
        logo.hAlign = "CENTER"

        thumbnail = logo
        data = [foto, thumbnail, us, area, decription]

        return data
Beispiel #12
0
    def build_index_Casse(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']
        styBackground = ParagraphStyle('background',
                                       parent=styNormal,
                                       backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()
        lst = [logo]
        lst.append(
            Paragraph(
                "<b>ELENCO CASSE CAMPIONI</b><br/><b>Scavo: %s,  Data: %s</b>"
                % (sito, data), styH1))

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

        styles = exp_index.makeStyles()
        colWidths = [20, 350, 250, 100]

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

        # table_data_formatted.setStyle(styles)

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

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

        doc = SimpleDocTemplate(f,
                                pagesize=(29 * cm, 21 * cm),
                                showBoundary=0,
                                topMargin=15,
                                bottomMargin=40,
                                leftMargin=30,
                                rightMargin=30)
        # doc.build(lst, canvasmaker=NumberedCanvas_Sindex)
        doc.build(lst)

        f.close()
Beispiel #13
0
def generate_pdf(file_name, trip, image_file):
    width, height = letter
    pdf = SimpleDocTemplate(file_name, pagesize=letter)

    data = [[
        'Name', 'Confirmation Number', 'Total', 'Adults', 'Children', 'Seats'
    ]]
    total_adults = 0
    total_children = 0

    for group in trip.groups:

        name = "%s %s" % (group.first_name, group.last_name)
        total = group.adults + group.children
        seats = list()
        for passenger in group.passengers:
            seats.append(passenger.position)
        seats.sort()
        data.append([
            name, group.confirmation_number, total, group.adults,
            group.children, " ,".join(seats)
        ])
        total_adults += group.adults
        total_children += group.children

    data.append([
        "TOTALS", "", total_adults + total_children, total_adults,
        total_children, ""
    ])

    table = Table(data)

    style = TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.black),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
        ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
        ('FONTNAME', (0, 0), (-1, 0), 'Times-Bold'),
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    ])
    table.setStyle(style)

    img = Image(image_file)
    img_width = img.drawWidth
    img_height = img.drawHeight

    new_height = 600
    img_scale = new_height / img_height
    new_width = img_scale * img_width
    img.drawWidth = new_width
    img.drawHeight = new_height
    img.hAlign = 'CENTER'

    elems = list()
    elems.append(table)
    elems.append(PageBreak())
    elems.append(img)

    pdf.build(elems)
Beispiel #14
0
def logo_pdf():
    datos = DATOS_DE_LA_EMPRESA.objects.get(pk=1)
    url= '/home/chuy/proyectos/naturista/tonino/nucleo/static'
    string= '/media/%s'%str(datos.LOGO)
    fichero= os.path.normpath(os.path.join(os.path.dirname(__file__),'../nucleo/static/'))
    logo= Image('%s%s'%(fichero, datos.LOGO.url), width=300, height=100)
    logo.hAlign = 'LEFT'
    return logo
Beispiel #15
0
    def _header_footer(self, canvas, doc):
        """ Renders a header and footer which will be inserted regardless of pdf method"""
        
        # Save the state of our canvas so we can draw on it
        canvas.saveState()
        stylesheet = getSampleStyleSheet()
 
        # Header
        logo = Image("http://www.fabco.la/fabco-seal-1.png", width=1.5*inch, height=1.5*inch)
        logo.hAlign = 'CENTER'
        
        stylesheet['BodyText'].fontSize = 10    
        stylesheet['BodyText'].leading = 14
        stylesheet['BodyText'].leftIndent = 5
        stylesheet['BodyText'].textColor = 'gray'
        
        FabcoAddress = "Fabco Art Services\n166 West Avenue 34\nLos Angeles CA 90031"
                                       
                                       
        project = get_object_or_404(Project, pk=self.pk)
        rightHeader = "Job #%s\nCompletion Date %s" % (project.project_id, project.due_date)
        
        # Build and format Left Header Table:
        leftHeaderData = [[FabcoAddress],
                            [project.client.first_name + ' ' + project.client.last_name+'\n'+project.client.address.street+'\n'+project.client.address.city + ' ' + project.client.address.zip_code], 
                            ]
        leftHeaderTable = Table(leftHeaderData)
        leftHeaderTable.setStyle(TableStyle([
                                            ('LEFTPADDING',(0,0),(0, 1),0),
                                            ('TOPPADDING',(0,1),(0, 1), 30),
                                            ('BOTTOMPADDING',(0,1),(0, 1), 0),                                            
                                            ]))

        # Build and format Header Table:
        headerData = [([leftHeaderTable, logo, rightHeader])]
        headerTable = Table(headerData, colWidths=doc.width/3)
        headerTable.setStyle(TableStyle([
            ('VALIGN', (0, 0), (-3, 0), 'MIDDLE'),
            ('VALIGN', (0, 0), (0, 0), 'TOP'),
            ('ALIGN',(1,0),(1,0),'CENTER'),
            ('ALIGN',(2,0),(2,0),'RIGHT'),
            ('LEFTPADDING',(0,0),(0,0),-1),
            ('RIGHTPADDING',(2,0),(2,0),-1),        
            ]))
        
        
        # find required space | I don't really understand this..    
        w, h = headerTable.wrap(doc.width, doc.height)
        # render to canvas | I also don't really understand this..
        headerTable.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - doc.bottomMargin) 
 
        # Footer
        footer = Paragraph('Client Signature: _________________________', stylesheet['Normal'])
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, doc.bottomMargin)
 
        # Release the canvas
        canvas.restoreState()
def sampleTablePDF():
    logo = "cimpress_sample.jpg"
    cup = "coffee-cup.jpg"
    imCup = Image(cup)

    im = Image(logo)

    im.hAlign = "CENTER"
    doc = SimpleDocTemplate("cimpress_sample_print_order.pdf",
                            pagesize=(im.drawWidth + 400, im.drawHeight + 400))
    content = []
    barcodeObject1 = BarcodeRender("Hello", barHeight=20, barWidth=1)
    barcodeObject2 = BarcodeRender("Hello", barHeight=20, barWidth=1)
    imCup.drawHeight = barcodeObject1.height
    imCup.drawWidth = barcodeObject1.height
    tTableStyle = [
        # ('BACKGROUND', (-1, 0), (-1, 0), colors.red),
        # ('BACKGROUND', (0, 0), (0, 0), colors.yellow),
        ('ALIGN', (0, 0), (0, 0), "RIGHT"),
        ('ALIGN', (-1, 0), (-1, 0), "LEFT"),
        ('ALIGN', (1, 0), (1, 0), "CENTER"),
        ('VALIGN', (0, 0), (0, 0), "MIDDLE"),
        ('VALIGN', (1, 0), (1, 0), "MIDDLE"),
        ('VALIGN', (-1, 0), (-1, 0), "MIDDLE"),
        # ('BACKGROUND', (0, 0), (0, 0), colors.orange),
        # ('BACKGROUND', (-1, 0), (-1, 0), colors.red),
        # ('BACKGROUND', (1, 0), (1, 0), colors.yellow),

        # ('SPAN', (0, -1), (-1, -1)),
        #  ('BACKGROUND', (0, -1), (-1, -1), colors.black),
        #  ('ALIGN', (0, -1), (-1, -1), "CENTER")
    ]
    styles = getSampleStyleSheet()
    styleHeading = ParagraphStyle('title',
                                  fontSize=20,
                                  leading=24,
                                  alignment=TA_LEFT)
    productDelivery = ParagraphStyle('title',
                                     fontSize=12,
                                     leading=24,
                                     alignment=TA_LEFT,
                                     textColor=colors.green)

    paras = []
    paras.append(
        Paragraph("SP: 01/27 Q: 1 <br/> SKU: 343434 <br/> ", styleHeading))
    paras.append(
        Paragraph("FAYA dwfdf dsfdsf sfdsf dsf sd fdsfds sdfdsfds sdfdsf f",
                  productDelivery))
    tableData = [[paras, imCup, barcodeObject2]]
    spacer = Spacer(0, 2 * cm)
    table = Table(data=tableData,
                  colWidths=[300, imCup.drawWidth, barcodeObject2.width])
    table.setStyle(tblstyle=tTableStyle)
    content.append(table)
    content.append(spacer)
    content.append(im)
    doc.build(content)
Beispiel #17
0
def get_images_grafana(request):
    if request.user.is_authenticated:

        buffer = io.BytesIO()

        filename = request.data.get('filename')
        textos = request.data.get('textos')
        urls = request.data.get("urls")

        document = []
        doc = SimpleDocTemplate(buffer,
                                pagesize=letter,
                                rightMargin=72,
                                leftMargin=72,
                                topMargin=72,
                                bottomMargin=18)
        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(name='centeredHeading',
                           alignment=TA_CENTER,
                           fontSize=24,
                           parent=styles['Heading1']))
        styles.add(
            ParagraphStyle(name='centeredHeading2',
                           alignment=TA_CENTER,
                           fontSize=16,
                           parent=styles['Heading2']))

        document.append(Paragraph(textos[0], styles['centeredHeading']))
        document.append(Paragraph(textos[1], styles['centeredHeading2']))
        document.append(Spacer(1, 12))

        x = 0

        for url in urls:
            document.append(Paragraph(textos[2 + x], styles['Heading2']))
            img = Image(url, doc.width, 2.5 * inch)
            img.hAlign = 'LEFT'
            document.append(img)
            document.append(Spacer(1, 1.1 * inch))
            x += 1

        doc.build(document,
                  onFirstPage=_header_footer,
                  onLaterPages=_header_footer)

        now = datetime.now()
        # dd/mm/YY H:M:S
        dt_string = now.strftime("%d-%m-%Y-%H:%M:%S")

        name = dt_string + filename + ".pdf"

        buffer.seek(0)
        return FileResponse(buffer, as_attachment=True, filename=name)

    msg = {'error': 'Permission Denied!'}
    return Response(msg, status=status.HTTP_403_FORBIDDEN)
Beispiel #18
0
def chooseSig(elements):
    msg = wx.MessageDialog(None, "Include signature?", "Message", wx.YES_NO | wx.ICON_QUESTION)
    if msg.ShowModal() == wx.ID_YES:
	logo = "/home/mb/Dropbox/Office/%sSignature.png" % settings.HOME_FOLDER
	im = Image(logo, 2*inch, 0.75*inch)
	im.hAlign = "LEFT"
	elements.append(im)
    else:
	elements.append(Spacer(1, 36))
Beispiel #19
0
def generarPDF(pk):  #Función generar pdf
    title1 = ParagraphStyle(
        'parrafos',
        alignment=TA_CENTER,
        fontSize=20,
        fontName="Times-Bold",
        spaceAfter=30,
        spaceBefore=0
    )  #Mostrara el titulo dentro del pdf, su tamaño, tipo de letra, donde se situa

    body = ParagraphStyle(
        'parrafos',
        alignment=TA_JUSTIFY,
        fontSize=12,
        fontName="Courier",
        leftIndent=36,
        spaceAfter=20,
        spaceBefore=20
    )  #El cuerpo dentro del pdf, tamaño, tipo de letra y donde se situa
    # header_bold = ParagraphStyle('parrafos',
    # alignment=TA_CENTER,
    # fontSize=15,
    # fontName="Times-Bold",
    # spaceAfter=5,
    # spaceBefore=15
    # )

    info = []  #La iformación del usuario
    I = Image(settings.PATH_MEDIA + 'ljr.jpg')
    I.drawHeight = 1.0 * inch
    I.drawWidth = 1.0 * inch
    I.hAlign = 'LEFT'

    info.append(I)

    e = Solicitud.objects.get(pk=pk)

    title_ = Paragraph(
        "SOLICITUD DE BECA 2020 ", title1
    )  #Todo esto va dentro del cuerpo del pdf o visualización del admin
    info.append(title_)
    info.append(Paragraph("NOMBRE: {}".format(e.nombre), body))
    info.append(Paragraph("APELLIDO PATERNO: {}".format(e.ap), body))
    info.append(Paragraph("APELLIDO MATERNO: {}".format(e.am), body))
    info.append(Paragraph("DOMICILIO: {}".format(e.domicilio), body))
    info.append(Paragraph("COLONIA: {}".format(e.colonia), body))
    info.append(Paragraph("TELEFONO: {}".format(e.telefono), body))
    info.append(Paragraph("FECHA DE NACIMIENTO: {}".format(e.fn), body))
    info.append(Paragraph("GRADO ACADEMICO: {}".format(e.ga), body))
    info.append(Paragraph("MATRICULA: {}".format(e.matricula), body))
    info.append(
        Paragraph("FORMACIÓN ARTISTICA: {}".format(e.formacion_artistica),
                  body))
    info.append(Paragraph("MODALIDAD: {}".format(e.modalidad), body))
    info.append(Paragraph("GENERO: {}".format(e.genero), body))
    info.append(Paragraph("CORREO: {}".format(e.correo), body))
    return info  #Retorna a info
Beispiel #20
0
def generarPDF(pk):

    # La alineación de el titulo y el tamaño
    title1 = ParagraphStyle('parrafos',
                            alignment=TA_CENTER,
                            fontSize=20,
                            fontName="Times-Bold",
                            spaceAfter=30,
                            spaceBefore=0)
    # Y el contenido
    body = ParagraphStyle('parrafos',
                          alignment=TA_JUSTIFY,
                          fontSize=12,
                          fontName="Courier",
                          leftIndent=36,
                          spaceAfter=20,
                          spaceBefore=20)
    # header_bold = ParagraphStyle('parrafos',
    # alignment=TA_CENTER,
    # fontSize=15,
    # fontName="Times-Bold",
    # spaceAfter=5,
    # spaceBefore=15
    # )

    # Aqui podemos configurar las imagenes que queremos que se visualicen en el reporte

    info = []
    I = Image(settings.PATH_MEDIA + 'ljr.jpg')
    I.drawHeight = 1.0 * inch
    I.drawWidth = 1.0 * inch
    I.hAlign = 'LEFT'

    info.append(I)

    # Aqui vamos a filtrar los modelos por su llave primaria y asi poder verlos en el reporte

    e = Solicitud.objects.get(pk=pk)

    title_ = Paragraph("SOLICITUD DE BECA 2020 ", title1)
    info.append(title_)
    info.append(Paragraph("NOMBRE: {}".format(e.nombre), body))
    info.append(Paragraph("APELLIDO PATERNO: {}".format(e.ap), body))
    info.append(Paragraph("APELLIDO MATERNO: {}".format(e.am), body))
    info.append(Paragraph("DOMICILIO: {}".format(e.domicilio), body))
    info.append(Paragraph("COLONIA: {}".format(e.colonia), body))
    info.append(Paragraph("TELEFONO: {}".format(e.telefono), body))
    info.append(Paragraph("FECHA DE NACIMIENTO: {}".format(e.fn), body))
    info.append(Paragraph("GRADO ACADEMICO: {}".format(e.ga), body))
    info.append(Paragraph("MATRICULA: {}".format(e.matricula), body))
    info.append(
        Paragraph("FORMACIÓN ARTISTICA: {}".format(e.formacion_artistica),
                  body))
    info.append(Paragraph("MODALIDAD: {}".format(e.modalidad), body))
    info.append(Paragraph("GENERO: {}".format(e.genero), body))
    info.append(Paragraph("CORREO: {}".format(e.correo), body))
    return info
Beispiel #21
0
    def build_P_sheets(self, records, sito):
        home = os.environ['HFF_HOME']
        self.width, self.height = (A3)

        home_DB_path = '{}{}{}'.format(home, os.sep, 'HFF_DB_folder')
        logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'banner.png')

        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']
        styBackground = ParagraphStyle('background',
                                       parent=styNormal,
                                       backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()
        list = []
        list.append(logo)

        list.append(
            Paragraph(
                "<b>HFF Archaeological Survey UW - Photo Index</b><br/><br/><b>Location: %s,  Date: %s</b><br/>"
                % (sito, data), styH1))

        table_data = []

        for i in range(len(records)):
            exp_index = Photo_index_pdf(records[i])

            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [50, 100, 120, 190, 120, 190]

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

        list.append(table_data_formatted)
        list.append(Spacer(0, 0))

        filename = '{}{}{}'.format(self.PDF_path, os.sep, 'Photo_index_UW.pdf')
        f = open(filename, "wb")

        doc = SimpleDocTemplate(f,
                                pagesize=A2,
                                showBoundary=0,
                                topMargin=15,
                                bottomMargin=40,
                                leftMargin=30,
                                rightMargin=30)
        doc.build(list, canvasmaker=NumberedCanvas_USindex)

        f.close()
Beispiel #22
0
def chooseSig(elements):
    msg = wx.MessageDialog(None, "Include signature?", "Message",
                           wx.YES_NO | wx.ICON_QUESTION)
    if msg.ShowModal() == wx.ID_YES:
        logo = "/home/mb/Dropbox/Office/%sSignature.png" % settings.HOME_FOLDER
        im = Image(logo, 2 * inch, 0.75 * inch)
        im.hAlign = "LEFT"
        elements.append(im)
    else:
        elements.append(Spacer(1, 36))
Beispiel #23
0
    def img(self, e):
        width = toLength(e.get('width'))
        height = toLength(e.get('height'))
        path = e.get('src')
        align = e.get('align', 'left').upper()

        img_obj = Image(self.get_from_url(path), width=width, height=height)
        img_obj.hAlign = align

        yield img_obj
Beispiel #24
0
    def build_index_Finds(self, records, sito):
        home = os.environ['PYARCHINIT_HOME']

        home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder')
        logo_path = '{}{}{}'.format(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']
        styBackground = ParagraphStyle('background',
                                       parent=styNormal,
                                       backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        lst = []
        lst.append(logo)
        lst.append(
            Paragraph(
                "<b>ELENCO MATERIALI</b><br/><b>Scavo: %s,  Data: %s</b>" %
                (sito, data), styH1))

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

        styles = exp_index.makeStyles()
        colWidths = [70, 110, 110, 110, 35, 35, 60, 60, 60, 60]

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

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

        filename = '{}{}{}'.format(self.PDF_path, os.sep,
                                   'elenco_materiali.pdf')
        f = open(filename, "wb")

        doc = SimpleDocTemplate(f,
                                pagesize=(29 * cm, 21 * cm),
                                showBoundary=0,
                                topMargin=15,
                                bottomMargin=40,
                                leftMargin=30,
                                rightMargin=30)
        doc.build(lst, canvasmaker=NumberedCanvas_FINDSindex)

        f.close()
Beispiel #25
0
    def get(self, request, performance_uuid):

        # Get performance to be printed
        performance = get_object_or_404(ShowPerformance, uuid=performance_uuid)

        # Create a Platypus story
        response = HttpResponse(content_type="application/pdf")
        response[
            "Content-Disposition"] = f"filename=performance{performance.id}.pdf"
        doc = SimpleDocTemplate(
            response,
            pagesize=portrait(A4),
            leftMargin=2.5 * cm,
            rightMargin=2.5 * cm,
            topMargin=2.5 * cm,
            bottomMargin=2.5 * cm,
        )
        styles = getSampleStyleSheet()
        story = []

        # Festival banner
        if request.festival.banner:
            banner = Image(request.festival.banner.get_absolute_path(),
                           width=18 * cm,
                           height=4 * cm)
            banner.hAlign = 'CENTER'
            story.append(banner)
            story.append(Spacer(1, 1 * cm))

        # Tickets
        tableData = []
        tableData.append(
            (Paragraph(f"<para><b>{performance.show.name}</b></para>",
                       styles['Normal']), "", "", ""))
        tableData.append(
            (f"{performance.date:%a, %e %b} at {performance.time:%I:%M %p}",
             "", "", ""))
        for ticket in request.user.tickets.filter(
                performance_id=performance.id):
            tableData.append(
                (f"{ticket.id}", "", ticket.description, f"£{ticket.cost}"))
        table = Table(tableData,
                      colWidths=(4 * cm, 4 * cm, 4 * cm, 4 * cm),
                      hAlign='LEFT',
                      style=(
                          ('SPAN', (0, 0), (3, 0)),
                          ('SPAN', (0, 1), (3, 1)),
                          ('ALIGN', (0, 2), (0, -1), 'RIGHT'),
                          ('ALIGN', (3, 2), (3, -1), 'RIGHT'),
                      ))
        story.append(table)

        # Create PDF document and return it
        doc.build(story)
        return response
    def build_index_individui_de(self, records, sito):
        home = os.environ['PYARCHINIT_HOME']

        conn = Connection()
        lo_path = conn.logo_path()
        lo_path_str = lo_path['logo']
        home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder')
        if not bool(lo_path_str):
            logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg')
        else:
            logo_path = lo_path_str

        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']
        styBackground = ParagraphStyle('background',
                                       parent=styNormal,
                                       backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        lst = []
        lst.append(logo)
        lst.append(
            Paragraph(
                "<b>LISTE INDIVIDUEL</b><br/><b>Ausgrabungsstätte: %s, Datum: %s</b>"
                % (sito, data), styH1))

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

        styles = exp_index.makeStyles()
        colWidths = [60, 60, 60, 60, 60, 250]

        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 = '{}{}{}'.format(self.PDF_path, os.sep,
                                   'liste_individuel.pdf')
        f = open(filename, "wb")

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

        f.close()
Beispiel #27
0
    def _addFooter(self, image_fd):
        """ Footer elements for receipt """

        footer = self._makeParagraph(
            "For all questions contact {} at {}".format(
                self.rentalInfo['landlord'], self.rentalInfo['phone']),
            'receiptContent')
        im = Image(image_fd, 1 * inch, 0.45 * inch)
        im.hAlign = 'LEFT'
        hr = HRFlowable(width="100%")
        return [im, Spacer(1, 4), hr, Spacer(1, 8), footer]
    def build_index_US(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']
        styBackground = ParagraphStyle('background',
                                       parent=styNormal,
                                       backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        lst = []
        lst.append(logo)
        lst.append(
            Paragraph(
                "<b>ELENCO UNITA' STRATIGRAFICHE</b><br/><b>Scavo: %s,  Data: %s</b>"
                % (sito, data), styH1))

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

        styles = exp_index.makeStyles()
        colWidths = [28, 28, 120, 45, 58, 45, 58, 55, 64, 64, 52, 52, 52]

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

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

        dt = datetime.datetime.now()
        filename = ('%s%s%s_%s_%s_%s_%s_%s_%s%s') % (
            self.PDF_path, os.sep, 'elenco_us', dt.day, dt.month, dt.year,
            dt.hour, dt.minute, dt.second, ".pdf")
        f = open(filename, "wb")

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

        f.close()
Beispiel #29
0
def generate_pdf_new(data_users):

    # List of users
    logo = Image('logo.jpg', 1 * inch, 1 * inch)
    logo.hAlign = 'LEFT'

    data = data_users

    buf = BytesIO()

    pdf = SimpleDocTemplate(buf, pagesize=letter)

    table = Table(data)

    # add style

    style = TableStyle([
        ('BACKGROUND', (0, 0), (3, 0), HexColor('#C7D4DB')),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('FONTNAME', (0, 0), (-1, 0), 'Courier-Bold'),
        ('FONTSIZE', (0, 0), (-1, 0), 10),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
        ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
    ])
    table.setStyle(style)

    # 2) Alternate backgroud color
    rowNumb = len(data)
    for i in range(1, rowNumb):
        bc = colors.white

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

    # 3) Add borders
    ts = TableStyle([
        ('BOX', (0, 0), (-1, -1), -1, HexColor('#e7eaed')),
        ('LINEBEFORE', (2, 1), (2, -1), -1, colors.red),
        ('LINEABOVE', (0, 2), (-1, 2), -1, colors.green),
        ('GRID', (0, 0), (-1, -1), -1, HexColor('#e7eaed')),
    ])
    table.setStyle(ts)

    elems = []

    elems.append(logo)
    elems.append(table)

    pdf.multiBuild(elems)
    pdf = buf.getvalue()

    return pdf
    def build_index_AR(self, records, divelog_id):
        HOME = os.environ['HFF_HOME']
        PDF_path = '{}{}{}'.format(HOME, os.sep, "HFF_PDF_folder")
        home_DB_path = '{}{}{}'.format(HOME, os.sep, 'HFF_DB_folder')
        logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'banner.png')
        logo = Image(logo_path)
        ##      if test_image.drawWidth < 800:
        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch
        # logo_path2 = '{}{}{}'.format(home_DB_path, os.sep, 'logo2.png')
        # logo2 = Image(logo_path2)
        # ##      if test_image.drawWidth < 800:
        # logo2.drawHeight = 0.5*inch*logo2.drawHeight / logo2.drawWidth
        # logo2.drawWidth = 0.5*inch
        # #1 row
        logo.hAlign = "LEFT"

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

        data = self.datestrfdate()

        lst = []
        lst.append(logo)
        lst.append(
            Paragraph("<b>Artefact List</b><br/><b>Data: %s</b>" % (data),
                      styH1))

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

        styles = exp_index.makeStyles()
        colWidths = [42, 60, 45, 45, 45, 58, 45, 58, 55, 64, 64, 52, 52, 65]

        table_data1_formatted = Table(table_data1, colWidths, style=styles)
        table_data1_formatted.hAlign = "LEFT"

        lst.append(table_data1_formatted)
        lst.append(Spacer(0, 2))

        filename = '{}{}{}'.format(self.PDF_path, os.sep, 'artefact_list.pdf')
        f = open(filename, "wb")

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

        f.close()
Beispiel #31
0
def _construct_header():
    header = []

    name_style = ParagraphStyle(name='name',
                                fontName="Times",
                                fontSize=20,
                                leading=20 * 1.2,
                                alignment=TA_CENTER)
    aff_style = ParagraphStyle(name='aff_style',
                               fontName="Times",
                               fontSize=10,
                               alignment=TA_CENTER,
                               leading=10 * 1.2)
    rank_style = ParagraphStyle(name='rank_style',
                                fontName="Times",
                                fontSize=12,
                                alignment=TA_CENTER,
                                leading=12 * 1.2)
    app_style = ParagraphStyle(name='app_style',
                               fontName="Times",
                               fontSize=14,
                               alignment=TA_CENTER,
                               leading=14 * 1.2)

    logo_img = Image("logo-color-tc-arts.png", 2.8 * cm, 2.8 * cm)
    logo_img.hAlign = TA_CENTER
    year_img = Image("70-years.png", 2 * cm, 2 * cm)
    name = Paragraph("THIAGARAJAR COLLEGE, MADURAI - 09", name_style)

    desc = Paragraph(
        "(An Autonomous Institution affliated to Madurai Kamaraj University)",
        aff_style)
    agg = Paragraph("(Re-Accredited with 'A' Grade by NAAC)", aff_style)
    rank = Paragraph("Ranked 34th in NIRF 2019", rank_style)
    app = Paragraph("APPLICATION FOR ADMISSION 2019-2020", app_style)

    w, h = A4
    li = []
    li.append((logo_img, [name, desc, agg, rank, app], year_img))
    tbl = Table(
        li,
        [3 * cm, w - 7.1 * cm, 2.5 * cm],
        style=[
            # ('SPAN', (0, 0), (2, 0)),
            ('ALIGN', (0, 0), (0, 0), 'RIGHT'),
            ('ALIGN', (1, 0), (1, 0), 'LEFT'),
            ('VALIGN', (1, 0), (1, 0), 'TOP'),
            ('VALIGN', (2, 0), (2, 0), 'MIDDLE'),
            # ('BACKGROUND', (1, 0), (1, 0), pink),
            # ('BACKGROUND', (0, 0), (0, 0), red),
            # ('BACKGROUND', (2, 0), (2, 0), blue),
        ])
    return tbl
Beispiel #32
0
def mainMakePdf(list_mahasiswa, kode_dosen, tipe_bimbingan):

    doc = SimpleDocTemplate(
        f'./beritaacarapitak/BERITA ACARA PITAK-{tipe_bimbingan.upper()}-{kelas.getTahunID()}-{kode_dosen}-{kelas.getEmailDosen(kode_dosen)}.pdf',
        pagesize=A4,
        rightMargin=30,
        leftMargin=30,
        topMargin=30,
        bottomMargin=18)
    doc.pagesize = portrait(A4)
    elements = []

    logo = Image("logoKAMBING.PNG", 3.5 * inch, 1 * inch)
    logo.hAlign = "LEFT"

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))

    for npm in list_mahasiswa:
        studentid, studentname = getDataMahasiswa(npm)
        status_nilai, nilai_total = totalNilai(
            studentid, config.MINIMUM_PERTEMUAN_BIMBINGAN, kode_dosen,
            tipe_bimbingan)
        status_nilai = True
        if status_nilai:
            JUDUL_BIMBINGAN = f"{getJudulFromNpm(npm)}"
            KODE_DOSEN = kode_dosen
            NAMA_DOSEN = kelas.getNamaDosen(KODE_DOSEN)
            NIDN_DOSEN = getNIDNDosen(KODE_DOSEN)
            TAHUN_AJARAN = kelas.getTahunAjaran(
                kelas.getProdiIDwithStudentID(studentid)).split(' ')[-1]
            makePdf(npm_mahasiswa=studentid,
                    nama_mahasiswa=studentname,
                    tipe_bimbingan=getTipeBimbingan(studentid),
                    nama_pembimbing=NAMA_DOSEN,
                    kode_dosen_pembimbing=KODE_DOSEN,
                    nidn_pembimbing=NIDN_DOSEN,
                    tahun_ajaran=TAHUN_AJARAN,
                    photo=cekPhotoRoute(studentid),
                    judul=JUDUL_BIMBINGAN,
                    total_nilai=str(nilai_total),
                    elements=elements,
                    logo=logo,
                    styles=styles,
                    kode_dosen_koordinator='NN056L')
            elements.append(PageBreak())

        else:
            pass

    doc.build(elements)
Beispiel #33
0
 def add_section_alignments(self, counts=[], bases=[], identity=[], coverage=[]):
     section = self.get_section_number()
     subsection = itertools.count(1)
     self.story.append(Paragraph("{:d} Alignments".format(section), self.heading_style))
     self.story.append(Spacer(1, 0))
     if bases:
         self.story.append(Paragraph("{:d}.{:d} Mapped bases (primary alignments)".format(section, next(subsection)), self.heading2_style))
         for b, label in bases:
             im = svg2rlg(b)
             im = Image(im, width=im.width * self.plot_scale, height=im.height * self.plot_scale)
             im.hAlign = 'CENTER'
             self.story.append(Paragraph(label, self.normal_style))
             self.story.append(im)
             self.story.append(Spacer(1, 0))
     if counts:
         self.story.append(Paragraph("{:d}.{:d} Mapped reads".format(section, next(subsection)), self.heading2_style))
         for c, label in counts:
             im = svg2rlg(c)
             im = Image(im, width=im.width * self.plot_scale, height=im.height * self.plot_scale)
             im.hAlign = 'CENTER'
             self.story.append(Paragraph(label, self.normal_style))
             self.story.append(im)
             self.story.append(Spacer(1, 0))
     if identity:
         self.story.append(Paragraph("{:d}.{:d} Read identity (primary alignments, all aligners)".format(section, next(subsection)), self.heading2_style))
         for b, label in identity:
             im = svg2rlg(b)
             im = Image(im, width=im.width * self.plot_scale, height=im.height * self.plot_scale)
             im.hAlign = 'CENTER'
             self.story.append(Paragraph(label, self.normal_style))
             self.story.append(im)
             self.story.append(Spacer(1, 0))
     if coverage:
         self.story.append(Paragraph("{:d}.{:d} Coverage".format(section, next(subsection)), self.heading2_style))
         im = svg2rlg(coverage[0])
         im = Image(im, width=im.width * self.plot_scale, height=im.height * self.plot_scale)
         im.hAlign = 'CENTER'
         self.story.append(im)
         self.story.append(Spacer(1, 0))
     self.story.append(Spacer(1, 0.5*cm))
def generateCertificate(user,event_name):
    try:
        userProfile = UserProfile.objects.using('mainsite').get(user = user)
    except:
        
        return None
    """
    if event.__class__.__name__!='GenericEvent':
        return None
    """
    # Create a buffer to store the contents of the PDF.
    # http://stackoverflow.com/questions/4378713/django-reportlab-pdf-generation-attached-to-an-email
    buffer = StringIO()
    
    CS = (3508, 2480)  # Certificate [Page] Size
    #CS = landscape(A4)

    # Create the PDF object, using the response object as its "file."

    pdf = canvas.Canvas(buffer, pagesize=CS)

    # Get the width and height of the page.

    (pageWidth, pageHeight) = CS
    
    y = pageHeight
    x = 0
    
    im = Image("/home/shaastra/hospi/certis/certback_final.jpg")
    im.hAlign = 'LEFT'
    
    paintImage(pdf, x, y, im)
    
    # Set font for Participant Name
    lineheight = PDFSetFont(pdf, 'Times-Bold', 80)
    xuser = (30.8 + (65.54/2))*cm
    yuser = 45.62*cm + lineheight
    name = constructName(user)
    pdf.drawString(xuser, yuser, '%s' % name)
    xevent = (24.3 + (65.54/2))*cm
    yevent = 37.62*cm + lineheight
    ename = event_name
    pdf.drawString(xevent, yevent, '%s' % ename)
    
    
    pdf.showPage()
    pdf.save()

    response = buffer.getvalue()
    buffer.close()

    return response
Beispiel #35
0
    def build_index_Documentazione(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']
        styBackground = ParagraphStyle('background',
                                       parent=styNormal,
                                       backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        lst = []
        lst.append(logo)
        lst.append(
            Paragraph(
                "<b>ELENCO DOCUMENTAZIONE</b><br/><b>Scavo: %s,  Data: %s</b>"
                % (sito, data), styH1))

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

        styles = exp_index.makeStyles()
        colWidths = [100, 100, 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_documentazione.pdf')
        f = open(filename, "wb")

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

        f.close()
Beispiel #36
0
    def add_header(self):
        # aiddata logo
        logo = self.dir_base + "/templates/logo.png"

        im = Image(logo, 2.188 * inch, 0.5 * inch)
        im.hAlign = "LEFT"
        self.Story.append(im)

        self.Story.append(Spacer(1, 0.25 * inch))

        # title
        ptext = "<font size=20>AidData geo(query) Request Documentation</font>"
        self.Story.append(Paragraph(ptext, self.styles["Center"]))
Beispiel #37
0
    def add_header(self):
        # aiddata logo
        logo = self.dir_base + '/templates/logo.png'

        im = Image(logo, 2.188*inch, 0.5*inch)
        im.hAlign = 'LEFT'
        self.Story.append(im)

        self.Story.append(Spacer(1, 0.25*inch))

        # title
        ptext = '<font size=20>Data Extraction Tool Request Documentation</font>'
        self.Story.append(Paragraph(ptext, self.styles['Center']))
        self.Story.append(Spacer(1, 0.5*inch))
Beispiel #38
0
    def build_index_Casse(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"]
        styBackground = ParagraphStyle("background", parent=styNormal, backColor=colors.pink)
        styH1 = styleSheet["Heading3"]

        data = self.datestrfdate()
        lst = [logo]
        lst.append(Paragraph("<b>ELENCO CASSE CAMPIONI</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data), styH1))

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

        styles = exp_index.makeStyles()
        colWidths = [20, 350, 250, 100]

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

        # table_data_formatted.setStyle(styles)

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

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

        doc = SimpleDocTemplate(
            f, pagesize=(29 * cm, 21 * cm), showBoundary=0, topMargin=15, bottomMargin=40, leftMargin=30, rightMargin=30
        )
        # doc.build(lst, canvasmaker=NumberedCanvas_Sindex)
        doc.build(lst)

        f.close()
	def build_index_US(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']
		styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink)
		styH1 = styleSheet['Heading3']

		data = self.datestrfdate()

		lst = []
		lst.append(logo)
		lst.append(Paragraph("<b>ELENCO UNITA' STRATIGRAFICHE</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data), styH1))

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

		styles = exp_index.makeStyles()
		colWidths=[28,28,120,45,58,45,58,55,64,64,52,52,52]

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

		lst.append(table_data_formatted)
		lst.append(Spacer(0,2))
		
		
		dt = datetime.datetime.now()
		filename = ('%s%s%s_%s_%s_%s_%s_%s_%s%s') % (self.PDF_path, os.sep, 'elenco_us', dt.day, dt.month, dt.year, dt.hour, dt.minute, dt.second, ".pdf")
		f = open(filename, "wb")

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

		f.close()
Beispiel #40
0
def Image(path, width=None, height=None, ratio=None, hAlign='CENTER', **kw):
    """
    An image with the file at *path*.

    The ratio is the width divided by the height of the source image. If the
    width or the height is given with the ratio, the other dimension is
    calculated from the first.
    """
    if width and ratio:
        height = width / ratio
    elif height and ratio:
        width = height * ratio

    image = BaseImage(path, width, height, **kw)
    image.hAlign = hAlign
    return image
	def build_index_Campioni(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']
		styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink)
		styH1 = styleSheet['Heading3']

		data = self.datestrfdate()

		lst = []
		lst.append(logo)
		lst.append(Paragraph("<b>ELENCO CAMPIONI</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data), styH1))

		table_data = []
		for i in range(len(records)):
			exp_index = Campioni_index_pdf_sheet(records[i])
			table_data.append(exp_index.getTable())
		
		styles = exp_index.makeStyles()
		colWidths=[60,150,60, 60,60, 250, 60]

		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_campioni.pdf')
		f = open(filename, "wb")

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

		f.close()
Beispiel #42
0
def generar_pdf(request, cliente_id=None):
    im = Image('media/ifes/logo_opt.jpg', width=2*inch, height=2*inch)
    im.hAlign = 'CENTER'
    cliente = get_object_or_404(Order, id=cliente_id)
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Orden_de_compra.pdf"
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=30,
                            leftMargin=60,
                            topMargin=30,
                            bottonMargin=10,
                            )
    doc.pagesize = landscape(A4)
    order = []

    styles = getSampleStyleSheet()
    header = Paragraph("Orden de compra", styles['Heading1'])
    fetch = [(f.order_date) for f in Order.objects.all() ]
    fecha = Paragraph("Fecha:", styles['Heading2'])
    order.append(im)
    order.append(header)
    order.append(fecha)

    headings = ('Orden de compra', 'Fecha', 'Monto total', 'Usuario', 'Operador','Producto','precio unitario','cantidad','total')
    allorder = [(p.orden_de_compra, p.order_date, p.total_amount, p.user, p.operador, a.product, a.product.price, a.quantity, (a.product.price*a.quantity)) for p in Order.objects.filter(user = cliente_id) for a in ProductOrder.objects.filter(order__user= cliente_id)]

    t = Table([headings] + allorder + fetch)
    t.setStyle(TableStyle(
        [
            ('GRID', (0,0), (10, -1), 1, colors.green),
            ('LINEBELOW', (0,0), (-1,0), 2, colors.greenyellow),
            ('BACKGROUND', (0,0), (-1,0), colors.green)
        ]
    ))

    order.append(t)
    doc.build(order)
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #43
0
def create(nodenick):
    buffer = StringIO()
    doc = SimpleDocTemplate(buffer)
    doc.author = "dinemo"
    doc.subject = "Network monitoring report"
    doc.title = "Network monitoring report"
    Story = []
#   img = Image("dinemomaster/static/images/logo.jpg", 214, 50)
    img = Image("dinemomaster/static/images/logo.jpg", 107, 25)
    img.hAlign='RIGHT'
    Story.append(img)
    Story.append(Spacer(1,7 * cm))
    style = styles["title"]
    style.textColor = "darkblue"
    style.fontSize = 20
    Story.append(Paragraph("Network moritoring report", style))
    Story.append(Spacer(1,0.5 * cm))
    style.fontSize = 14
    Story.append(Paragraph("Generated on %s" % strftime("%d %h %Y"), style))
    if nodenick:
        style.fontSize = 16
        Story.append(Spacer(1,1 * cm))
        Story.append(Paragraph("            \"%s\" node network metrics""" % nodenick, style))
    style = styles["Normal"]
    style.textColor = "black"
    Story.append(PageBreak())




    for i in range(100):
        bogustext = ("Paragraph number %s. " % i) *20
        p = Paragraph(bogustext, style)
        Story.append(p)
        Story.append(Spacer(1,0.2*cm))

    doc.build(Story, onLaterPages= _later_page)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Beispiel #44
0
    def _header_factura(canvas,doc):
        #guardamos el estado de nuestro canvas , para poder dibujar en el 
        canvas.saveState()
        canvas.setTitle("Factura")
        styles = getSampleStyleSheet()

        #header
        header = Image('/home/borbolla/metrology/static_media/assets/images/logo_servicio.png' )
        header.drawHeight = 70
        header.drawWidth = 399
        header.hAlign = 'RIGHT'
        w , h = header.wrap(doc.width , doc.topMargin)
        header.drawOn(canvas , doc.leftMargin , 700)
        
        

        # Footer
        footer = Paragraph('www.borbollametrology.com', styles['Normal'])
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, h)
 
        # Release the canvas
        canvas.restoreState()
Beispiel #45
0
def go(parts):
    doc=SimpleDocTemplate("templated.pdf",
        leftMargin=1.5*inch, topMargin=1.75*inch)

    styles=getStyles()

    stuff=[]
    stuff.append(Paragraph(parts['date'], styles['plain']))
    stuff.append(Spacer(1, 0.25*inch))
    stuff.append(Paragraph(parts['name'], styles['plain']))
    stuff.append(Paragraph(parts['address'], styles['plain']))
    stuff.append(Paragraph("%(city)s, %(state)s  %(zip)s" % parts,
        styles['main']))

    stuff.append(Paragraph("Dear %(name)s:" % parts, styles['main']))

    stuff.append(Paragraph("""
Thank you for your recent donation of $%(amount)s to the Santa Clara Schools
Foundation. Your generous contribution is an investment in the future of our
community's children and ultimately everyone's future.
""" % parts, styles['main']))

    stuff.append(Paragraph("""
Since 1992 the foundation has been providing grants to individual classroom
teachers to help them enrich the learning experiences of their students and
that grant program will continue as before. The annual campaign to which you
have so generously responded will expand the foundation's efforts beyond
individual classrooms and enable us to help students on a district-wide basis.
As you obviously are aware, this is a critical need in these times of crippling
cuts to education funding.
""" % parts, styles['main']))

    stuff.append(Paragraph("""
Thank you again for your gift to the Santa Clara Schools Foundation. Your
contribution is genuinely appreciated and will be put to good use in improving
the education of our young people.
""" % parts, styles['main']))

    stuff.append(Paragraph("Sincerely,", styles['plain']))
    # Space before sig
    stuff.append(Spacer(1, 0.125*inch))

    # Signature here
    img=Image("paulfrench.jpg", width=2.5 * inch, height=0.40742 * inch)
    img.hAlign = 'LEFT'
    stuff.append(img)

    # space after sig
    # stuff.append(Spacer(1, 0.125*inch))

    stuff.append(Paragraph("Paul A. French", styles['plain']))
    stuff.append(Paragraph("President, Santa Clara Schools Foundation",
        styles['plain']))

    stuff.append(Spacer(1, 0.5*inch))

    stuff.append(Paragraph("""
Your contribution is fully tax deductible. No goods or services were provided
by the Santa Clara Schools Foundation in consideration for this contribution.
""" % parts, styles['footer']))

    doc.build(stuff)
Beispiel #46
0
Image("lj8100.jpg")
""",after=0.1)
disc("""will display as""")
try:
    getStory().append(Image(I))
except:
    disc("""An image should have appeared here.""")
disc("""whereas""")
eg("""
im = Image("lj8100.jpg", width=2*inch, height=2*inch)
im.hAlign = 'CENTER'
""", after=0.1)
disc('produces')
try:
    im = Image(I, width=2*inch, height=2*inch)
    im.hAlign = 'CENTER'
    getStory().append(Image(I, width=2*inch, height=2*inch))
except:
    disc("""An image should have appeared here.""")
heading2("""$Spacer(width, height)$""")
disc("""This does exactly as would be expected; it adds a certain amount of space into the story.
At present this only works for vertical space.
""")
CPage(1)
heading2("""$PageBreak()$""")
disc("""This $Flowable$ represents a page break. It works by effectively consuming all vertical
space given to it. This is sufficient for a single $Frame$ document, but would only be a
frame break for multiple frames so the $BaseDocTemplate$ mechanism
detects $pageBreaks$ internally and handles them specially.
""")
CPage(1)
Beispiel #47
0
def evaluation_pdf(request, app_id):
    application = get_object_or_404(Application, id=app_id)
    evaluation, created = Evaluation.objects.get_or_create(application=application)
    
    try:
        from reportlab.pdfgen import canvas
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.platypus import Paragraph, Image, Spacer, SimpleDocTemplate
        from reportlab.lib import enums
        import settings, copy
        from datetime import date
    except:
        return HttpResponse("Missing library")
    
    width, pageHeight = letter
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = "attachment; filename=application_%s.pdf" %  app_id
    
    stylesheet = getSampleStyleSheet()
    normalStyle = copy.deepcopy(stylesheet['Normal'])
    normalStyle.fontName = 'Times-Roman'
    normalStyle.fontSize = 12
    normalStyle.leading = 15
    
    centreAlign = copy.deepcopy(normalStyle)
    centreAlign.alignment = enums.TA_CENTER

    rightAlign = copy.deepcopy(normalStyle)
    rightAlign.alignment = enums.TA_RIGHT

    lindent = copy.deepcopy(normalStyle)
    lindent.leftIndent = 12

    h1 = copy.deepcopy(normalStyle)
    h1.fontName = 'Times-Bold'
    h1.fontSize = 18
    h1.leading = 22
    h1.backColor = '#d0d0d0'
    h1.borderPadding = 3
    h1.spaceBefore = 3
    h1.spaceAfter = 3

    h2 = copy.deepcopy(normalStyle)
    h2.fontName = 'Times-Bold'
    h2.fontSize = 14
    h2.leading = 18
    h2.backColor = '#e8e8e8'
    h2.borderPadding = 3
    h2.spaceBefore = 3
    h2.spaceAfter = 3

    page = SimpleDocTemplate(response, pagesize=letter, title="EWB application")
    p = []
    
    p.append(Paragraph("<strong><em>PRIVATE AND CONFIDENTIAL</em></strong>", centreAlign))
    p.append(Spacer(0, 10))
    p.append(Paragraph("Engineers Without Borders Canada", normalStyle))
    p.append(Spacer(0, 6))
    p.append(Paragraph("<strong>%s</strong>" % application.session.name, normalStyle))
    p.append(Spacer(0, -40))
    img = Image(settings.MEDIA_ROOT + '/images/emaillogo.jpg', 100, 51)
    img.hAlign = 'RIGHT'
    p.append(img)
    #p.line(50, height - 90, width - 50, height - 90)
    p.append(Spacer(0, 10))

    p.append(Paragraph("Application for", normalStyle))
    p.append(Spacer(0, 5))

    parsed_name = ''
    if application.profile.first_name:
        parsed_name = application.profile.first_name
    if application.profile.first_name and application.profile.last_name:
        parsed_name = parsed_name + ' '
    if application.profile.last_name:
        parsed_name = parsed_name + application.profile.last_name
    p.append(Paragraph(parsed_name, h1))
    
    p.append(Paragraph("<strong>Submitted " + str(application.updated.date()) + "</strong>", normalStyle))
    p.append(Spacer(0, -13))
    p.append(Paragraph("Printed: " + str(date.today()), rightAlign))
    p.append(Spacer(0, 14))
    
    p.append(Paragraph("<strong>English language</strong>&nbsp;&nbsp;&nbsp;&nbsp;Reading: %d&nbsp;&nbsp;&nbsp;Writing: %d&nbsp;&nbsp;&nbsp;Speaking %d" % (application.en_reading, application.en_writing, application.en_speaking), normalStyle))
    p.append(Paragraph("<strong>French language</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reading: %d&nbsp;&nbsp;&nbsp;Writing: %d&nbsp;&nbsp;&nbsp;Speaking %d" % (application.fr_reading, application.fr_writing, application.fr_speaking), normalStyle))
    #p.append(Paragraph("<strong>GPA             </strong>   %d" % application.gpa, normalStyle))
    p.append(Spacer(0, 20))

    p.append(Paragraph("Resume", h2))
    try:
        p.append(Paragraph(application.resume_text.replace("<br>", "<br/>").replace("</p>", "<br/><br/>"), lindent))
    except:
        p.append(Paragraph(strip_tags(application.resume_text).replace("\n", "<br/>"), lindent))
    p.append(Spacer(0, 20))

    p.append(Paragraph("References", h2))
    try:
        p.append(Paragraph(application.references.replace("<br>", "<br/>").replace("</p>", "<br/><br/>"), lindent))
    except:
        p.append(Paragraph(strip_tags(application.resume_text).replace("\n", "<br/>"), lindent))
    p.append(Spacer(0, 20))
    
    p.append(Paragraph("Application Questions", h2))
    for question in application.session.application_questions():
        p.append(Paragraph("<strong>%s</strong>" % question.question, normalStyle))
        answer = Answer.objects.filter(application=application, question=question)
        if answer:
            p.append(Paragraph(answer[0].answer.replace("\n", "<br/>"), lindent))
        else:
            p.append(Paragraph("<em>No answer</em>", lindent))
        p.append(Spacer(0, 20))
        

    """
    for m in activity.get_metrics():
        metricname = ''
        for mshort, mlong in ALLMETRICS:
            if mshort == m.metricname:
                metricname = mlong
                
        p.append(Paragraph(metricname, h2))
        for x, y in m.get_values().items():
            if x and y:
                p.append(Paragraph(fix_encoding(str(x)), bold))
                p.append(Paragraph(fix_encoding(str(y)), lindent))
                p.append(Spacer(0, 10))
            
        p.append(Spacer(0, 10))
    """    
    
    page.build(p)
    return response
Beispiel #48
0
#create a bar chart and specify positions, sizes, and colors



########   Now lets put everything together.   ########

# create a list and add the elements of our document (image, paragraphs, table, chart) to it
story = []

#define the style for our paragraph text
styles = getSampleStyleSheet()
styleN = styles['Normal']

#First add the Vizard Logo
im = Image("C:/Users/oo/Documents/python_none_pythonfiles/py_pic/logo.png", width=1.6*inch, height=1*inch)
im.hAlign = 'LEFT'
story.append(im)
story.append(Spacer(1,.25*inch))

#add the title
P1="<strong>Results for Vizard Experiment</strong>"
story.append(Paragraph(P1,styleN))
story.append(Spacer(1,.25*inch))

#convert data to paragraph form and then add paragraphs
story.append(Paragraph(dataToParagraph(subject1, results1),styleN))
story.append(Spacer(1,.25*inch))
story.append(Paragraph(dataToParagraph(subject2, results2),styleN))
story.append(Spacer(1,.5*inch))

#add our table - first prepare data and then pass this to myTable function
Beispiel #49
0
    def generarPlanillaFamilia(self):
	from reportlab.lib.pagesizes import A4
	from reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle
	from reportlab.platypus import Spacer, SimpleDocTemplate, Table, TableStyle
	from reportlab.platypus import Paragraph, Image
	from reportlab.lib import colors

	pdf_x_familia = QtGui.QFileDialog.getSaveFileName(self, "Guardar Planilla Komunal (*.pdf)", QtCore.QDir.homePath() + "/familia-" + str(self.ui.tableWidget.item(self.ui.tableWidget.currentRow(), 1).text()) + ".pdf", "Documento PDF (*.pdf)")
	styleSheet=getSampleStyleSheet()
	story=[]
	h1=styleSheet['Heading1']
	h1.pageBreakBefore=0
	h1.keepWithNext=1
	h1.backColor=colors.red
	h2=styleSheet['Heading2']
	h2.pageBreakBefore=0
	h2.keepWithNext=1

	img=Image("img/logo_pdf_barra.png",580,70)
	img.hAlign = "LEFT"

	texto_principal = ""
	estilo_texto = ParagraphStyle('',
		        fontSize = 22,
                        alignment = 0,
                        spaceBefore = 0,
                        spaceAfter = 0,
			#backColor = '#fff',
			textColor = '#999',
			leftIndent = 10 )

	otro_estilo= ParagraphStyle('',
	             fontSize = 20,
		     textColor = '#000',
		     leftIndent = 200,
		     rightIndent = 50)

	style_barra= ParagraphStyle('',
		     fontSize = 13,
		     textColor = '#000',
		     backColor='#f5f5f5',
		     borderColor ='#a3a3a3',
		     borderWidth = 1,
		     borderPadding = (1, 2, 5))

	style_fecha= ParagraphStyle('',
		     fontSize = 11,
		     textColor = '#000',
		     leftIndent = 500,
		     rightIndent = 10)

	h = Paragraph( texto_principal, estilo_texto)
	banner = [ [ img , h ] ]

	ban = Table( banner, colWidths=300 )
	ban.setStyle([ ('ALIGN',(0,0),(0,0),'LEFT'),('ALIGN',(0,0),(1,0),'LEFT'), ('VALIGN',(0,0),(1,0),'TOP'),
			('TEXTCOLOR',(0,1),(0,-1), colors.blue) ])
	story.append(ban)
	story.append(Spacer(0,10))

	dia = time.localtime()
	mes = dia.tm_mon
	mes_sp = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre','Octubre', 'Noviembre', 'Diciembre']

	hoy='%s %d' % (mes_sp[mes-1], dia.tm_year)
	P= Paragraph(hoy,style_fecha)
	story.append(P)
	story.append(Spacer(0,25))

	P= Paragraph("<b>Censo Socio-Economico</b> ",otro_estilo)
	story.append(P)
	story.append(Spacer(0,25))

	P=Paragraph("<b>Información General</b> ",style_barra)
	story.append(P)
	story.append(Spacer(0,25))


	style=styleSheet['BodyText']

	consejo = self.dbconn.execute("select * from consejo_comunal where id_consejo=1").fetchone()

	data_consejo = [['Consejo Comnual: ', consejo[2] ],
			['Estado' ,'Municipio:' , 'Parroquia:', 'Sector: ' ],
			[ consejo[3], consejo[4] , consejo[5] , consejo[6]] ,
			['Dirección: ', consejo[7] ] ]
	c=Table(data_consejo, colWidths=148)
	c.setStyle([  ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
		      ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('SPAN',(1,3),(3,3)), ('SPAN',(1,0),(-1,0))
		   ])
	story.append(c)
	story.append(Spacer(0,15))



	jefe = self.dbconn.execute("SELECT *, (Date('now') -fecha_nacimiento) as edad FROM familia where id_grupo= 1 AND jefe_familia= 'S'").fetchone()

	PO = Paragraph('''<font size=12> <b> Jefe de Familia</b></font>''',styleSheet["BodyText"])
	print jefe
	sexoJefe = "Masculino" if jefe[6] == "M" else "Femenino"
	if (jefe[9]== '' or jefe[9]== 0):
	    ingreso = "N/P"
	else:
	    ingreso = jefe[9] + " Bs. "
	datos_jefe = [[ Paragraph('''<font size=12> <b> Jefe de Familia</b></font>''',styleSheet["BodyText"]) ],
		    ['Cedula: ', jefe[12]+jefe[4], 'Apellidos y Nombres: ' , str(jefe[2])+ ' ' + str(jefe[3]) , 'Sexo: ', sexoJefe ],
		    [ 'Lugar de Nacimiento: ',jefe[12] , 'Fecha Nacimiento: ', jefe[5], 'Edad: ', jefe[19] ],
		    ['Edo Civil: ',jefe[11], 'Ingreso Mensual: ', ingreso , 'Grado de Instrucción', jefe[10] ],
		    ['Ocupación: ', jefe[8]] ]

	colwidths = (100, 90, 100, 90, 110, 100)
	j = Table( datos_jefe, colwidths )
	j.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black),('SPAN',(0,0),(5,0)) ])
	story.append(j)
	story.append(Spacer(0,15))

	self.dbconn.execute("SELECT *, (Date('now') -fecha_nacimiento) as edad FROM familia where id_grupo= 1 AND jefe_familia= 'N'")
	rs = self.dbconn.fetchall()

	integrantes = [[Paragraph('''<font size=12> <b> Integrantes del grupo familiar</b></font>''',styleSheet["BodyText"])],
			['Cedula', 'Nombre/Apellido', 'Parentesco', 'Sexo', 'Edad', 'Edo Civil' , 'Instrucción', 'Ocupación','Ingreso']]
	for familia in rs:
	    	if (familia[9]== "" or familia[9]== "0"):
		    ingreso = "N/P"
		else:
		    ingreso = familia[9] + " Bs. "

		integrantes.append([str(familia[4]), str(familia[2])+ " " + str(familia[3]), str(familia[7]), str(familia[6]), str(familia[19]),str(familia[11]), str(familia[10]), str(familia[8]), ingreso ])

	t=Table(integrantes, (55,150, 60, 35, 35, 50, 80, 80, 45))

	t.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black), ('SPAN',(0,0),(8,0))
	 ])

	story.append(t)
	story.append(Spacer(0,15))



	vivienda = self.dbconn.execute("SELECT * FROM vivienda where id_grupo= 1").fetchone()

	datos_vivienda = [[ Paragraph('''<font size=12><b>Características de la vivienda</b></font>''',styleSheet["BodyText"]) ],
		    ['Tipo de Vivienda: ', vivienda[2], 'Estado de la Vivienda: ' , vivienda[3] , 'Tenencia: ', vivienda[4] ],
		    ['Material del Piso: ',vivienda[5] , 'Material de Paredes: ', vivienda[6] ],
		    ['Material Techo: ', vivienda[7],'Habitaciones: ',vivienda[8], 'Sala Comedor: ', vivienda[9] ],
		    ['Baños', vivienda[10] , 'Cocina: ', vivienda[11], 'Uso de Vivienda: ', vivienda[12]],
		    ['Le gustaria Mejorar: ', vivienda[13]] ]

	v=Table(datos_vivienda, (100,100, 110, 100, 90, 90))
	v.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black),('SPAN',(0,0),(5,0)),('SPAN',(3,2),(5,2)),('SPAN',(1,5),(5,5))
	 ])
	story.append(v)
	story.append(Spacer(0,15))


	salud = self.dbconn.execute("SELECT * FROM salud_bienestar where id_familia = 1").fetchone()
	vacuna = "Si" if salud[2] == "S" else "No"
	datos_salud = [[ Paragraph('''<font size=12><b>Salud y Bienestar</b></font>''',styleSheet["BodyText"]) ],
		    ['Los Niños estan vacunados: '+ str(salud[2]), '', 'Solo menores de seis(6) años : ' + str(salud[3]),  '', 'Todos: ' + salud[4], '' ] ]

	datos_salud.append( ['De las siguientes vacunas cuales tiene la seguridad de haberles suministrado:' ])

	self.dbconn.execute("SELECT desc_vacuna, id_salud FROM tipos_vacuna LEFT OUTER JOIN vacuna  ON tipos_vacuna.id_tipo_vacuna = vacuna.id_tipo_vacuna")
	rs = self.dbconn.fetchall()
	a = 1
	i = 3
	fila = ""

	for vacuna in rs:
	    si_no = "X" if vacuna[1] else ""
	    fila = fila + vacuna[0] + ","+ si_no + ","
	    if (a == i ):
		i = i + 3
		fila = fila[0:-1].split(',')
		datos_salud.append(  fila )
		fila = ""
	    a = a + 1


	datos_salud.append( ['Algunos de los miembros de la familia a presentado problemas de:' ])

	self.dbconn.execute("SELECT desc_enfermedad, id_salud FROM tipo_enfermedad LEFT OUTER JOIN enfermedad  ON tipo_enfermedad.id_tipo_enfermedad = enfermedad.id_tipo_enfermedad where activa='s'")
	rs = self.dbconn.fetchall()
	a = 1
	i = 3
	fila = ""

	for enfermedad in rs:
	    si_no = "X" if enfermedad[1] else ""
	    fila = fila + enfermedad[0] + ","+ si_no + ","
	    if (a == i ):
		i = i + 3
		fila = fila[0:-1].split(',')
		datos_salud.append(  fila )
		fila = ""
	    a = a + 1

	v=Table(datos_salud, (120,90, 110, 90, 90, 90))
	v.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),	('BOX', (0,0), (-1,-1), 0.25, colors.black),
	    ('SPAN',(0,0),(5,0)), ('SPAN',(0,1),(1,1)), ('SPAN',(2,1),(3,1)),('SPAN',(4,1),(5,1)), ('SPAN',(0,2),(5,2)),('SPAN',(0,6),(5,6)) ])


	story.append(v)
	story.append(Spacer(0,25))



	servicios = self.dbconn.execute("SELECT * FROM servicios_publicos where familia = 1").fetchone()

	serv_publicos = [[ Paragraph('''<font size=12><b>Servicios Publicos Existentes</b></font>''',styleSheet["BodyText"]) ],
		    ['Aguas Blancas: ', servicios[1], 'Aguas Servidas: ' , servicios[2] , 'Gas: ', servicios[3] ],
		    ['Sistema Electrico: ',servicios[4] , 'Recolección de Basura: ', servicios[5] ],
		    ['Otros Servicios: '],
		    ['Telefonía: ', servicios[6],'Transporte: ',servicios[7] ],
		    ['Mecanismos de Información: ', '', servicios[8] ] ]

	s=Table(serv_publicos, (90,100, 115, 100, 90, 90))
	s.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black),('SPAN',(0,0),(5,0)),('SPAN',(0,3),(5,3)),('SPAN',(0,5),(1,5)) ,('SPAN',(2,5),(5,5)) ])
	story.append(s)
	story.append(Spacer(0,15))

	par_comunitaria = [[ Paragraph('''<font size=12><b>Participacion Comunitaria</b></font>''',styleSheet["BodyText"]) ],
		    ['Existe organización Comunitaria: ', servicios[9] ],
		    ['Participación del jefe de familia: ', servicios[13] ],
		    ['Participación de los miembros de familia: ', servicios[10] ] ]
	s=Table(par_comunitaria, (200, 385))
	s.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black),('SPAN',(0,0),(1,0)) ])
	story.append(s)
	story.append(Spacer(0,15))

	doc=SimpleDocTemplate(unicode( pdf_x_familia, "utf-8"), pagesize=letter,leftMargin=10, rightMargin=10, topMargin=10, bottomMargin=10,
			      title="Komunal - Planilla Familiar", author= "Komunal Beta" )
	doc.build( story )
	self.funciones.generar_log(self, "Se genero planilla pdf de familia = "+ str(self.ui.tableWidget.item(self.ui.tableWidget.currentRow(), 1).text()) + " el usuario lo guardo en: " + pdf_x_familia )
Beispiel #50
0
def activity_as_pdf(request, group_slug, activity_id):
    group = get_object_or_404(Network, slug=group_slug)
    activity = get_object_or_404(Activity, pk=activity_id)
    
    if not activity.group.pk == group.pk:
        return HttpResponseForbidden()
    
    try:
        from reportlab.pdfgen import canvas
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.platypus import Paragraph, Image, Spacer, SimpleDocTemplate
        from reportlab.lib import enums
        import settings
    except:
        return HttpResponse("Missing library")
    
    width, pageHeight = letter
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=champ_activity.pdf'
    
    stylesheet = getSampleStyleSheet()
    normalStyle = copy.deepcopy(stylesheet['Normal'])
    normalStyle.fontName = 'Times-Roman'
    normalStyle.fontSize = 12
    normalStyle.leading = 15
    
    bold = copy.deepcopy(normalStyle)
    bold.fontName = 'Times-Bold'
    bold.leftIndent = 6

    rightAlign = copy.deepcopy(normalStyle)
    rightAlign.alignment = enums.TA_RIGHT

    lindent = copy.deepcopy(normalStyle)
    lindent.leftIndent = 12

    bground = copy.deepcopy(normalStyle)
    bground.backColor = '#e0e0e0'

    h1 = copy.deepcopy(normalStyle)
    h1.fontName = 'Times-Bold'
    h1.fontSize = 18
    h1.leading = 22
    h1.backColor = '#d0d0d0'
    h1.borderPadding = 3
    h1.spaceBefore = 3
    h1.spaceAfter = 3

    h2 = copy.deepcopy(normalStyle)
    h2.fontName = 'Times-Bold'
    h2.fontSize = 14
    h2.leading = 18
    h2.backColor = '#e8e8e8'
    h2.borderPadding = 3
    h2.spaceBefore = 3
    h2.spaceAfter = 3

    page = SimpleDocTemplate(response, pagesize=letter, title="EWB Event Summary")
    p = []
    
    p.append(Paragraph("Engineers Without Borders Canada", normalStyle))
    p.append(Paragraph("Event Summary", normalStyle))
    p.append(Spacer(0, -50))
    img = Image(settings.MEDIA_ROOT + '/images/emaillogo.jpg', 100, 51)
    img.hAlign = 'RIGHT'
    p.append(img)
    #p.line(50, height - 90, width - 50, height - 90)
    p.append(Spacer(0, 10))

    p.append(Paragraph("<strong>" + str(activity.date) + "</strong>", rightAlign))
    p.append(Paragraph("Printed: " + str(date.today()), rightAlign))
    p.append(Spacer(0, -20))

    p.append(Paragraph("<strong>" + group.chapter_info.chapter_name + "</strong>", normalStyle))
    p.append(Spacer(0, 20))
    
    p.append(Paragraph(activity.name, h1))
    p.append(Spacer(0, 10))

    p.append(Paragraph("<strong>Volunters:</strong> " + str(activity.numVolunteers), normalStyle))
    p.append(Paragraph("<strong>Prep time:</strong> " + str(activity.prepHours) + " person hours", normalStyle))
    p.append(Paragraph("<strong>Execution time:</strong> " + str(activity.execHours) + " person hours", normalStyle))
    p.append(Spacer(0, 10))
    
    for m in activity.get_metrics():
        metricname = ''
        for mshort, mlong in ALLMETRICS:
            if mshort == m.metricname:
                metricname = mlong
                
        p.append(Paragraph(metricname, h2))
        for x, y in m.get_values().items():
            if x and y:
                p.append(Paragraph(str(x), bold))
                p.append(Paragraph(str(y), lindent))
                p.append(Spacer(0, 10))
            
        p.append(Spacer(0, 10))
        
    
    page.build(p)
    return response
Beispiel #51
0
  Elements=[]

  print(pdf_file)
  #doc = BaseDocTemplate(pdf_file)

  doc = SimpleDocTemplate(
                            pdf_file,
                            fontSize     = 7,
                            pagesize     = letter,
                            topMargin    = .25*inch,
                            bottomMargin = .25*inch,
                            leftMargin   = .25*inch
                          )

  LogoImage = Image('logo512x512.jpg', 1.5*inch, 1.5*inch)
  LogoImage.hAlign = 'LEFT'
  Elements.append(LogoImage)
  Elements.append(Paragraph('Barcodatron',styles['Heading1']))

  Elements.append(Paragraph('Sample Nouns',styles['Heading2']))

  Elements = bcode(Elements,'Sample Job Number','SBJOB:tif952')

  Elements = bcode(Elements,'Sample Part Number','TPN:891')

  Elements.append(Paragraph('Sample Verbs',styles['Heading2']))
  Elements = bcode(Elements,'Preview 1-sided Part label','SBX:genlabelp')
  Elements = bcode(Elements,'Generate 1-sided Part label','SBX:genlabel')
  Elements = bcode(Elements,'Generate 2-sided Job+Part label','SBX:genlabel2s')
  Elements = bcode(Elements,'Check-in Part','SBX:checkin')
Beispiel #52
0
try:
    getStory().append(Image(I))
except:
    disc("""An image should have appeared here.""")
disc("""whereas""")
eg(
    """
im = Image("lj8100.jpg", width=2*inch, height=2*inch)
im.hAlign = 'CENTER'
""",
    after=0.1,
)
disc("produces")
try:
    im = Image(I, width=2 * inch, height=2 * inch)
    im.hAlign = "CENTER"
    getStory().append(Image(I, width=2 * inch, height=2 * inch))
except:
    disc("""An image should have appeared here.""")
heading2("""$Spacer(width, height)$""")
disc(
    """This does exactly as would be expected; it adds a certain amount of space into the story.
At present this only works for vertical space.
"""
)
CPage(1)
heading2("""$PageBreak()$""")
disc(
    """This $Flowable$ represents a page break. It works by effectively consuming all vertical
space given to it. This is sufficient for a single $Frame$ document, but would only be a
frame break for multiple frames so the $BaseDocTemplate$ mechanism
Beispiel #53
0
    def __init__(self, parent, ptID, reason, background, consultant, dueDate):
	filename = "/home/mb/Desktop/GECKO/EMR_outputs/%s/Consults/%s.pdf" % (ptID, EMR_utilities.dateToday())
	doc = SimpleDocTemplate(filename, pagesize=letter, topMargin=60)
	# container for the 'Flowable' objects
	elements = []
	styleSheet = getSampleStyleSheet()
	styleSheet.add(ParagraphStyle(name='Address', fontSize=13, leading=15))
	styleSheet.add(ParagraphStyle(name='Body', fontSize=12, leading=14))

	dem_data = EMR_utilities.getDictData('SELECT * FROM demographics WHERE patient_ID = %s;' % ptID)
	consultDoc = EMR_utilities.name_fixer(consultant)
	if consultDoc.firstname == '':
            consult_data = EMR_utilities.getDictData('SELECT * FROM consultants WHERE lastname = "%s";' \
		% (consultDoc.lastname))
        else:
            consult_data = EMR_utilities.getDictData('SELECT * FROM consultants WHERE lastname = "%s" \
		AND firstname = "%s";' % (consultDoc.lastname, consultDoc.firstname))
	
	patient = 'RE: %(firstname)s %(lastname)s, DOB: %(dob)s' % dem_data
	salutation = 'Dear Dr. %(lastname)s:' % consult_data
	body = 'I am sending %s, a %s %s, to see you regarding %s. %s' % \
		(dem_data['firstname'], EMR_utilities.getAge(ptID), dem_data['sex'], reason, background)
	problems = EMR_formats.getProblems(ptID)
	meds = EMR_formats.getMeds(ptID, display='column')
	qry = "INSERT INTO todo SET patient_ID = %s, date = '%s', description = '%s- %s', priority = 3, \
		category = 'Consult', due_date = '%s', complete = 0;" % (ptID, EMR_utilities.dateToday(), \
		consult_data['lastname'], reason, dueDate)
	EMR_utilities.updateData(qry)
	
	styleSheet = getSampleStyleSheet()
	styleSheet.add(ParagraphStyle(name='Address', fontSize=13, leading=15))
	styleSheet.add(ParagraphStyle(name='Body', fontSize=12, leading=14))

	elements.append(Paragraph('Barron Family Medicine', styleSheet['Address']))
	elements.append(Paragraph('1423 S Big Bend Blvd', styleSheet['Address']))
	elements.append(Paragraph('Richmond Heights, MO 63117', styleSheet['Address']))
	elements.append(Spacer(1,24))
	elements.append(Paragraph('<para align=RIGHT>%s</para>' % EMR_utilities.dateToday(t='display'), styleSheet['Body']))
	elements.append(Spacer(1,24))

	elements.append(Paragraph('Dr. %(lastname)s' % consult_data, styleSheet['Body']))
	elements.append(Paragraph('%(address)s' % consult_data, styleSheet['Body']))
	elements.append(Paragraph('%(city)s, %(state)s  %(zipcode)s' % consult_data, styleSheet['Body']))
	elements.append(Spacer(1, 12))
	elements.append(Paragraph(patient, styleSheet['Body']))
	elements.append(Spacer(1, 12))
	elements.append(Paragraph(salutation, styleSheet['Body']))
	elements.append(Spacer(1, 12))
	elements.append(Paragraph(body, styleSheet['Body']))
	elements.append(Spacer(1,12))
	elements.append(Paragraph("I have attached current medications and problems.  \
		If you have any questions, don't hesitate to call me at (314) 667-5276.", styleSheet['Body']))
	elements.append(Spacer(1,12))
	elements.append(Paragraph('Sincerely,', styleSheet['Body']))
	#elements.append(Spacer(1, 48))
	#If you want the signature automatically then can un-comment these lines.  For now I will sign all.
	logo = "/home/mb/Dropbox/Office/Signature.png"
	im = Image(logo, 2*inch, 0.75*inch)
	im.hAlign = "LEFT"
	elements.append(im)

	elements.append(Paragraph('Michael Barron MD', styleSheet['Body']))
	elements.append(Spacer(1, 12))

	tableList = [[problems, meds,]]
	table = Table(tableList, colWidths=(3*inch, 3*inch), style=[('VALIGN', (0,0), (-1,-1), 'TOP'),
				     							('LEFTPADDING', (0,0), (-1,-1), 0),
			     	     							('RIGHTPADDING', (0,0), (-1,-1), 20)])
	table.hAlign = "LEFT"
	elements.append(table)
	
	# write the document to disk
	doc.build(elements)
	os.system("lp -d Updox %s" % filename)	#extremely slick: prints directly to Updox Printer
Beispiel #54
0
	def generarReporteIndicadores(self):
	    print "Aqui en pdf"
	    from reportlab.lib.pagesizes import A4
	    from reportlab.lib.pagesizes import letter
	    from reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle
	    from reportlab.platypus import Spacer, SimpleDocTemplate, Table, TableStyle
	    from reportlab.platypus import Paragraph, Image
	    from reportlab.lib import colors
	    
	    pdf_x_indicador = QtGui.QFileDialog.getSaveFileName(self, "Guardar Planilla Komunal (*.pdf)", QtCore.QDir.homePath() + "/indicadores-komunal.pdf", "Documento PDF (*.pdf)")
	    styleSheet=getSampleStyleSheet()
	    story=[]
	    h1=styleSheet['Heading1']
	    h1.pageBreakBefore=0
	    h1.keepWithNext=1
	    h1.backColor=colors.red
	    h2=styleSheet['Heading2']
	    h2.pageBreakBefore=0
	    h2.keepWithNext=1
	    
	    img=Image("img/logo_pdf_barra.png",580,70)
	    img.hAlign = "LEFT"
    
	    texto_principal = ""
	    estilo_texto = ParagraphStyle('',
			    fontSize = 22,
			    alignment = 0,
			    spaceBefore = 0,
			    spaceAfter = 0,
			    #backColor = '#fff',
			    textColor = '#999',
			    leftIndent = 10 )
    
	    otro_estilo= ParagraphStyle('',
			 fontSize = 20,
			 textColor = '#000',
			 leftIndent = 200,
			 rightIndent = 50) 
    
	    style_fecha= ParagraphStyle('',
			 fontSize = 11,
			 textColor = '#000',
			 leftIndent = 500,
			 rightIndent = 10)
    
	    h = Paragraph( texto_principal, estilo_texto)
	    banner = [ [ img , h ] ]

	    ban = Table( banner )
	    ban.setStyle([ ('ALIGN',(0,0),(0,0),'LEFT'),('ALIGN',(0,0),(1,0),'LEFT'), ('VALIGN',(0,0),(1,0),'TOP'),
			    ('TEXTCOLOR',(0,1),(0,-1), colors.blue) ])
	    story.append(ban)
	    story.append(Spacer(0,10))
    
	    #dia = time.localtime()
	    #mes = dia.tm_mon
	    #mes_sp = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre','Octubre', 'Noviembre', 'Diciembre']
     
	    #hoy='%s %d' % (mes_sp[mes-1], dia.tm_year)
	    #P= Paragraph(hoy,style_fecha)
	    #story.append(P)
	    #story.append(Spacer(0,25))
    
	    P= Paragraph("<b>Reporte de Indicadores</b> ",otro_estilo)
	    story.append(P)
	    story.append(Spacer(0,25))
	    
	    mayor_60 = self.dbconn.execute("SELECT count(a.fecha_nacimiento) from familia a where fecha_nacimiento < Date('now', '-60 year') AND a.co_consejo=1").fetchone()
    
	    ninos = self.dbconn.execute("SELECT count(a.fecha_nacimiento) from familia a where fecha_nacimiento between Date('now', '-12 year') and Date('now', '-3 year') AND a.co_consejo=1").fetchone()
    
	    personas = self.dbconn.execute("select count(id) as cant_perso,  (select count(sexo) from familia where sexo='F' and co_consejo=1) as cant_mujer,(select count(sexo) from familia where sexo='M' and co_consejo=1) as cant_hombre from familia where co_consejo=1").fetchone()
    
	    familias = self.dbconn.execute("SELECT count(id) FROM familia WHERE jefe_familia='S' AND co_consejo=1").fetchone()
    
	    adolecentes = self.dbconn.execute("SELECT count(a.fecha_nacimiento) from familia a where fecha_nacimiento between Date('now', '-17 year') and Date('now', '-13 year') AND a.co_consejo=1").fetchone()
    
	    alfabetizados = self.dbconn.execute("select count(a.id) from familia a where a.instruccion='N/P' and fecha_nacimiento < Date('now', '-7 year')").fetchone()
	    
	    data_indicador = [['Personas Mayores de 60 Años: ', mayor_60[0] ],
			     ['Niños entre 3 y 12 años: ', ninos[0] ],
			     ['Personas del Sexo Masculino: ', personas[2] ],
			     ['Personas del Sexo Femenino: ', personas[1] ],
			     ['Cantidad de Familias: ', familias[0] ],
			     ['Adolecentes (entre 13 y 17 años): ', adolecentes[0] ],
			     ['Personas Alfabetizadas: ', alfabetizados[0] ],
			     ['Total de Personas en el Consejo: ', personas[0] ]]
	
	    anchocolumna = (350, 80)
	    c=Table(data_indicador, anchocolumna )
	    c.setStyle([  ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
			  ('BOX', (0,0), (-1,-1), 0.25, colors.black)		       ])	
	    story.append(c)
	    story.append(Spacer(0,15))
	    
    
	    style=styleSheet['BodyText']
    
	    doc=SimpleDocTemplate(pdf_x_indicador,pagesize=letter,leftMargin=10, rightMargin=10, topMargin=10, bottomMargin=10, title="Komunal - Reporte de Indicadores", author= "Komunal Beta" )
	    doc.build( story )
Beispiel #55
0
def boletin_liquid_definitiva(request, liquidacion):
    liquid = Liquidacion2.objects.get(numero=liquidacion)
    pagos = Pago2.objects.filter(liquidacion=liquid.pk)

    nombre_reporte = "boletin_liquidacion"
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename='+nombre_reporte+'.pdf; pagesize=letter;'

    #Esta lista contendra todos los elementos que se dibujaran en el pdf
    elementos = []
    doc = SimpleDocTemplate(response, title=nombre_reporte, topMargin=5,
                            bottomMargin=5, rightMargin=15, leftMargin=15)

    for i in range(0, 2):
        #---> Encabezado <---
        styleSheet = getSampleStyleSheet()
        cabecera = styleSheet['Normal']
        cabecera.alignment = TA_CENTER
        cabecera.firstLineIndent = 0
        cabecera.fontSize = 6
        cabecera.fontName = 'Helvetica-Bold'
        cabecera.leftIndent = -380
        cabecera.leading = 7

        logo = Image(settings.STATIC_ROOT+'/reportes/escudo.jpg',
                    width=25, height=35)
        logo.hAlign = 'LEFT'
        elementos.append(logo)

        elementos.append(Spacer(1, -35))
        txtEncabezado = 'País'
        txtEncabezado += '<br />Estado'
        txtEncabezado += '<br />Alcaldía'
        txtEncabezado += '<br />Dirección de Rentas Municipales'
        txtEncabezado += '<br />RIF: '
        encabezado = Paragraph(txtEncabezado, cabecera)
        elementos.append(encabezado)
        #---> Fin Encabezado <---

        #---> Datos Contribuyente <---
        styleSheet2 = getSampleStyleSheet()
        estilo_contrib = styleSheet2['BodyText']
        estilo_contrib.alignment = TA_CENTER
        estilo_contrib.fontSize = 7.5
        estilo_contrib.fontName = 'Times-Roman'
        estilo_contrib.leading = 6
        contrib_style = [
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ]

        elementos.append(Spacer(1, -37))

        contrib1 = Paragraph(u'<b>BOLETIN DE NOTIFICACIÓN</b>', estilo_contrib)
        contrib2 = Paragraph(u'<b>%s</b>' % pagos[0].impuesto.descripcion, estilo_contrib)
        contrib3 = Paragraph(u'<b>PERIODO IMPOSITIVO:</b> %s ' % (liquid.ano), estilo_contrib)
        contrib4 = Paragraph(u'<b>FECHA:</b> %s' % liquid.emision, estilo_contrib)

        tabla_contrib = []
        tabla_contrib.append([contrib1])
        tabla_contrib.append([contrib2])
        tabla_contrib.append([contrib3])
        tabla_contrib.append([contrib4])

        tabla_contrib = Table(tabla_contrib, colWidths=(12.0*cm))
        tabla_contrib.setStyle(TableStyle(contrib_style))
        tabla_contrib.hAlign = 'RIGHT'

        elementos.append(tabla_contrib)
        #---> Fin Datos Contrib <---

        #---> Tabla <---
        elementos.append(Spacer(1, 10))

        estilo_tabla = styleSheet['BodyText']
        estilo_tabla.alignment = TA_CENTER
        estilo_tabla.fontSize = 7.5
        estilo_tabla.leading = 7
        x = [
            ('BACKGROUND', (0, 0), (2, 0), colors.silver),
            ('BACKGROUND', (0, 2), (2, 2), colors.silver),
            ('BACKGROUND', (0, -1), (-1, -1), colors.silver),
            ('GRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 7.5),
        ]
        tabla = []

        # Headers de la tabla
        hdatos = Paragraph('<b>R.I.F.</b>', estilo_tabla)
        hdatos1 = Paragraph('<b>RAZON SOCIAL</b>', estilo_tabla)
        hdatos2 = Paragraph('<b>ID</b>', estilo_tabla)

        hdatos3 = Paragraph('<b>DOMICILIO FISCAL</b>', estilo_tabla)
        x.append(('SPAN', (0, 2), (2, 2))),  # Extendiendo columna

        hdatos4 = Paragraph('<b>PERIODO FISCAL:</b>', estilo_tabla)
        hdatos5 = Paragraph('<b>IMPUESTO TOTAL ANUAL ESTIMADO</b>', estilo_tabla)
        hdatos6 = Paragraph('<b>IMPUESTO TOTAL ANUAL DEFINITIVO</b>', estilo_tabla)
        hdatos7 = Paragraph('<b>DIFERENCIA A CANCELAR</b>', estilo_tabla)
        # Fin Headers de la tabla

        tabla.append([hdatos, hdatos1, hdatos2])
        tabla.append([liquid.contribuyente.num_identificacion, liquid.contribuyente.nombre, liquid.contribuyente.id_contrato])

        # -- Direccion
        tabla.append([hdatos3])
        direccion = Paragraph('%s' % liquid.contribuyente.direccion, estilo_tabla)
        tabla.append([direccion])
        x.append(('SPAN', (0, 3), (2, 3))),  # Extendiendo columna

        # -- Periodo Fiscal
        periodo_fiscal = Paragraph('<b>01 DE ENERO DE ## AL 31 DE DICIEMBRE DE %s</b>' % liquid.ano, estilo_tabla)
        tabla.append([hdatos4, periodo_fiscal])
        x.append(('SPAN', (1, 4), (2, 4))),  # Extendiendo columna

        t = Table(tabla, colWidths=(3.5*cm, 11.5*cm, 3.5*cm))
        t.setStyle(TableStyle(x))
        elementos.append(t)
        elementos.append(Spacer(1, 10))

        tabl2 = []
        y = [
            ('BACKGROUND', (0, 0), (2, 0), colors.silver),
            ('BOX', (0, 5), (6, 0), 0.50, colors.black),
            ('BOX', (0, 9), (6, 0), 0.50, colors.black),
            ('GRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 7.5),
        ]
        tabl2.append([hdatos5, hdatos6, hdatos7])
        montos = liquid.contribuyente.monto_set.filter(contribuyente=liquid.contribuyente, ano=liquid.ano)
        diferencia = float(montos[0].definitivo) - float(montos[0].estimado)
        tabl2.append([montos[0].estimado, montos[0].definitivo, diferencia])

        t2 = Table(tabl2, colWidths=(6.5*cm, 6.5*cm, 5.5*cm))
        t2.setStyle(TableStyle(y))
        elementos.append(t2)
        #---> Fin Tabla <---

        #---> Notas <---
        styleSheetNota = getSampleStyleSheet()
        nota = styleSheetNota['Normal']
        nota.fontSize = 7.5
        nota.fontName = 'Helvetica'
        nota.alignment = TA_JUSTIFY

        elementos.append(Spacer(1, 5))
        txtNota1 = Paragraph('<b>Ordenanza de Impuesto sobre Actividades Económicas vigente:</b><br />', nota)
        elementos.append(txtNota1)

        txtArt1 = Paragraph('"<b>ARTICULO 24.-</b> La declaración definitiva deberá presentarse en el mes de Enero de cada año y comprenderá'+\
                            ' el monto de los ingresos brutos obtenidos en el ejercicio económico entre el 1° de Enero al 31 de Diciembre'+\
                            ' del año anterior, en cada una de las actividades o ramo ejercidas por el contribuyente a que se refiere el'+\
                            ' Clasificador de Actividades Económicas y que hayan sido o no autorizados en la correspondiente Licencia'+\
                            ', la cual conformara la base imponible definitiva para la determinación, cálculo y liquidación del impuesto'+\
                            ' correspondiente a la obligación tributaria causada en el ejercicio fiscal fenecido."<br />', nota)
        elementos.append(txtArt1)

        elementos.append(Spacer(1, 5))
        txtArt2 = Paragraph('"<b>ARTICULO 66.-</b> Serán sancionados en la forma prevista en el artículo de los contribuyentes que:'+\
                            ' ..."d) No paguen, dentro de los plazos previstos en el artículo 24 de esta Ordenanza, la diferencia'+\
                            ' producto de la presentación de la declaración definitiva, con <b>multa equivalente a 10 Unidades'+\
                            ' Tributarias y cierre temporal del establecimiento</b>, hasta tanto cumpla con las obligaciones'+\
                            ' establecidas en dicho artículo."<br />', nota)
        elementos.append(txtArt2)

        elementos.append(Spacer(1, 5))
        txtNota2 = Paragraph('NOTA: La presente notificación no implica la<br />cancelación de años anteriores al %s' % liquid.ano, nota)
        elementos.append(txtNota2)

        elementos.append(Spacer(1, 10))
        styleSheet3 = getSampleStyleSheet()
        parrafo = styleSheet3['Normal']
        parrafo.fontSize = 7.5
        parrafo.fontName = 'Helvetica'
        parrafo.alignment = TA_CENTER

        elementos.append(Spacer(1, 15))
        txtNota3 = Paragraph('<b>Evite Sanciones... Cumpla con su Ciudad...!</b>', parrafo)
        elementos.append(txtNota3)

        styleSheet3 = getSampleStyleSheet()
        parrafo = styleSheet3['Normal']
        parrafo.fontSize = 7.5
        parrafo.rightIndent = -320
        parrafo.fontName = 'Helvetica'
        parrafo.alignment = TA_CENTER

        elementos.append(Spacer(1, -50))
        lineaStyle = [
            ('LINEABOVE', (0, 0), (-1, -1), 0.55, colors.black),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 2),
        ]
        linea = []
        linea.append([' '])

        l2 = Table(linea, colWidths=(8.0*cm))
        l2.setStyle(TableStyle(lineaStyle))
        l2.hAlign = 'RIGHT'
        elementos.append(l2)

        elementos.append(Spacer(1, -15))
        txtNota4 = Paragraph('<hr /><br />Directora x' +
                             '<br /><b>Directora</b>', parrafo)
        elementos.append(txtNota4)

        elementos.append(Spacer(1, 20))
        txtNota4 = Paragraph('<b>ALCALDIA</b>', parrafo)
        elementos.append(txtNota4)
        #---> Fin Notas <---

        elementos.append(Spacer(1, 10))
        linea = []
        linea.append([' '])

        l2 = Table(linea, colWidths=(20.0*cm))
        l2.setStyle(TableStyle(lineaStyle))
        elementos.append(l2)

    doc.build(elementos)
    return response
Beispiel #56
0
def liquidacion_report(request, liquidacion):
    liquid = Liquidacion2.objects.get(numero=liquidacion)
    pagos = Pago2.objects.filter(liquidacion=liquid.pk)

    nombre_reporte = "liquidacion"
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename='+nombre_reporte+'.pdf; pagesize=letter;'

    #Esta lista contendra todos los elementos que se dibujaran en el pdf
    elementos = []
    doc = SimpleDocTemplate(response, title=nombre_reporte, topMargin=5,
                            bottomMargin=5, rightMargin=15, leftMargin=15)

    for i in range(0, 3):
        #---> Encabezado <---
        styleSheet = getSampleStyleSheet()
        cabecera = styleSheet['Normal']
        cabecera.alignment = TA_CENTER
        cabecera.firstLineIndent = 0
        cabecera.fontSize = 7.5
        cabecera.fontName = 'Helvetica-Bold'
        cabecera.leftIndent = -370
        cabecera.leading = 7

        logo = Image(settings.STATIC_ROOT+'/reportes/escudo.jpg',
                    width=25, height=35)
        logo.hAlign = 'LEFT'
        elementos.append(logo)

        elementos.append(Spacer(1, -35))
        txtEncabezado = 'País'
        txtEncabezado += '<br />Estado'
        txtEncabezado += '<br />Alcaldía'
        txtEncabezado += '<br />Dirección de Rentas Municipales'
        txtEncabezado += '<br />RIF: x'
        encabezado = Paragraph(txtEncabezado, cabecera)
        elementos.append(encabezado)
        #---> Fin Encabezado <---

        #---> Datos Contribuyente <---
        styleSheet2 = getSampleStyleSheet()
        estilo_contrib = styleSheet2['BodyText']
        estilo_contrib.alignment = TA_CENTER
        estilo_contrib.fontSize = 7.5
        estilo_contrib.fontName = 'Times-Roman'
        estilo_contrib.leading = 6
        contrib_style = [
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ]

        elementos.append(Spacer(1, -37))

        contrib1 = Paragraph('<b>INFORMACION GENERAL DEL CONTRIBUYENTE</b>', estilo_contrib)
        contrib2 = Paragraph('%s' % liquid.contribuyente.nombre, estilo_contrib)
        contrib3 = Paragraph('<b>CI/RIF:</b> %s ' % (liquid.contribuyente.num_identificacion), estilo_contrib)
        contrib4 = Paragraph('%s' % liquid.contribuyente.direccion, estilo_contrib)

        tabla_contrib = []
        tabla_contrib.append([contrib1])
        tabla_contrib.append([contrib2])
        tabla_contrib.append([contrib3])
        tabla_contrib.append([contrib4])

        tabla_contrib = Table(tabla_contrib, colWidths=(12.0*cm))
        tabla_contrib.setStyle(TableStyle(contrib_style))
        tabla_contrib.hAlign = 'RIGHT'

        elementos.append(tabla_contrib)
        #---> Fin Datos Contrib <---

        #---> Tabla <---
        elementos.append(Spacer(1, 10))

        estilo_tabla = styleSheet['BodyText']
        estilo_tabla.alignment = TA_CENTER
        estilo_tabla.fontSize = 7.5
        estilo_tabla.leading = 7
        x = [
            ('BACKGROUND', (0, 0), (6, 0), colors.silver),
            ('BACKGROUND', (0, 2), (6, 2), colors.silver),
            ('BACKGROUND', (0, -2), (-1, -2), colors.silver),
            ('SPAN', (0, -2), (-6, -2)),
            ('SPAN', (0, -1), (-6, -1)),
            ('BOX', (0, 5), (6, 0), 0.50, colors.black),
            ('BOX', (0, 9), (6, 0), 0.50, colors.black),
            ('GRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 8),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]
        tabla = []

        # Headers de la tabla
        hdatos = Paragraph('<b>Fecha Emisión</b>', estilo_tabla)
        x.append(('SPAN', (0, 0), (1, 0))),  # Extendiendo columna
        x.append(('SPAN', (0, 1), (1, 1))),  # Extendiendo columna

        hdatos1 = Paragraph('<b>Fecha Vencimiento</b>', estilo_tabla)
        hdatos2 = Paragraph('<b>ID</b>', estilo_tabla)
        hdatos3 = Paragraph('<b>No. Liquidación</b>', estilo_tabla)

        hdatos4 = Paragraph('<b>No. Deposito</b>', estilo_tabla)
        x.append(('SPAN', (5, 0), (6, 0))),  # Extendiendo columna
        x.append(('SPAN', (5, 1), (6, 1))),  # Extendiendo columna

        hPagos = Paragraph('<b>DETALLE DE PAGO DE IMPUESTOS VARIOS</b>', estilo_tabla)
        x.append(('SPAN', (0, 2), (6, 2))),  # Extendiendo columna

        hpago= Paragraph('<b>Año</b>', estilo_tabla)
        hpago1 = Paragraph('<b>Codigo</b>', estilo_tabla)
        hpago2 = Paragraph('<b>Impuesto</b>', estilo_tabla)
        hpago3 = Paragraph('<b>Monto Impuesto o Tasa</b>', estilo_tabla)
        hpago4 = Paragraph('<b>Recargo</b>', estilo_tabla)
        hpago5 = Paragraph('<b>Intereses</b>', estilo_tabla)
        hpago6 = Paragraph('<b>Sub-Total</b>', estilo_tabla)

        hpago7 = Paragraph('<b>Credito Fiscal</b>', estilo_tabla)
        hpago8 = Paragraph('<b>Descuento</b>', estilo_tabla)
        hpago9 = Paragraph('<b>Total(Bs.)</b>', estilo_tabla)
        hpago10 = Paragraph('<b>Impuesto o Tasa</b>', estilo_tabla)
        # Fin Headers de la tabla

        tabla.append([hdatos, '', hdatos1, hdatos2, hdatos3, hdatos4, ''])
        tabla.append([liquid.emision, '', liquid.vencimiento, liquid.contribuyente.id_contrato, liquid.numero, liquid.deposito, ''])
        pos = 0
        recargo = 0
        intereses = 0
        cancelado = 0
        monto = 0
        for pago in pagos:
            if liquid.tipo=='EST':
                credito=pago.credito_fiscal
            else:
                credito=0
            if pos == 0:
                tabla.append([hPagos])
                tabla.append([hpago, hpago1, hpago2, hpago3, hpago4, hpago5, hpago6])
            tabla.append([liquid.ano, pago.impuesto.codigo, pago.impuesto.descripcion, round(pago.monto,2), round(pago.recargo,2), round(pago.intereses,2), round(pago.monto,2)])

            pos = pos + 1

            recargo = recargo + pago.recargo
            intereses = intereses + pago.intereses
            cancelado = cancelado + pago.cancelado
            monto = monto + round(pago.monto,2)

        tabla.append([hpago7, '', hpago8, hpago10, hpago4, hpago5, hpago9])
        tabla.append([credito, '', pago.descuento, pago.monto, pago.recargo, intereses, pago.cancelado])

        t = Table(tabla, colWidths=(2.0*cm, 2.0*cm, 3.5*cm, 3.5*cm, 3.5*cm, 2.0*cm, 2.2*cm))
        t.setStyle(TableStyle(x))
        elementos.append(t)
        #---> Fin Tabla <---

        #---> Notas <---
        styleSheetNota = getSampleStyleSheet()
        nota = styleSheetNota['Normal']
        nota.fontSize = 8
        nota.fontName = 'Helvetica'
        nota.alignment = TA_LEFT

        txtNota1 = Paragraph('<b>DETALLES:</b> <br /> <b>%s</b>' % liquid.observaciones, nota)
        elementos.append(txtNota1)

        elementos.append(Spacer(1, 10))
        styleSheet3 = getSampleStyleSheet()
        parrafo = styleSheet3['Normal']
        parrafo.fontSize = 7
        parrafo.rightIndent = -320
        parrafo.fontName = 'Helvetica'
        parrafo.alignment = TA_CENTER

        elementos.append(Spacer(1, -17))
        txtNota1 = Paragraph('Evite Sanciones...Cumpla con su Ciudad...!', parrafo)
        elementos.append(txtNota1)

        txtNota2 = Paragraph('Para más información dirijase a las oficinas de Rentas Municipales.'+
                             '<br />Atención: Directora x' +
                             '<br /><b>Directora</b>', parrafo)
        elementos.append(txtNota2)
        #---> Fin Notas <---

        #---> Firmas <---
        elementos.append(Spacer(1, -42))
        estilo_tabla2 = styleSheet['BodyText']
        estilo_tabla2.alignment = TA_CENTER
        estilo_tabla2.fontSize = 7
        y = [
            ('BOX', (0, 0), (-1, -1), 0.50, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
        ]
        hrecibi = Paragraph('VALIDACIÓN', estilo_tabla2)
        hsellos = Paragraph('SELLOS', estilo_tabla2)
        hautorizada = Paragraph('FIRMA FUNCIONARIO', estilo_tabla2)

        tabla2 = []
        tabla2.append([hrecibi, '', ''])
        tabla2.append(['', hsellos, hautorizada])

        t2 = Table(tabla2, colWidths=(3.0*cm, 3.0*cm, 4.0*cm))
        t2.setStyle(TableStyle(y))
        t2.hAlign = 'LEFT'
        elementos.append(t2)
        #---> Fin Firmas <---

        elementos.append(Spacer(1, 5))
        lineaStyle = [
            ('LINEABOVE', (0, 0), (-1, -1), 0.35, colors.black),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 2),
        ]
        linea = []
        linea.append([' '])

        l2 = Table(linea, colWidths=(20.0*cm))
        l2.setStyle(TableStyle(lineaStyle))
        elementos.append(l2)

    doc.build(elementos)
    return response
Beispiel #57
0
def boletin_liquid_estimada(request, liquidacion):
    liquid = Liquidacion2.objects.get(numero=liquidacion)
    pagos = Pago2.objects.filter(liquidacion=liquid.pk)

    nombre_reporte = "boletin_liquidacion"
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename='+nombre_reporte+'.pdf; pagesize=letter;'

    #Esta lista contendra todos los elementos que se dibujaran en el pdf
    elementos = []
    doc = SimpleDocTemplate(response, title=nombre_reporte, topMargin=5,
                            bottomMargin=5, rightMargin=15, leftMargin=15)

    for i in range(0, 2):
        #---> Encabezado <---
        styleSheet = getSampleStyleSheet()
        cabecera = styleSheet['Normal']
        cabecera.alignment = TA_CENTER
        cabecera.firstLineIndent = 0
        cabecera.fontSize = 7
        cabecera.fontName = 'Helvetica-Bold'
        cabecera.leftIndent = -350
        cabecera.leading = 7

        logo = Image(settings.STATIC_ROOT+'/reportes/escudo.jpg',
                    width=25, height=35)
        logo.hAlign = 'LEFT'
        elementos.append(logo)

        elementos.append(Spacer(1, -35))
        txtEncabezado = 'País'
        txtEncabezado += '<br />Estado'
        txtEncabezado += '<br />Alcaldía'
        txtEncabezado += '<br />Dirección de Rentas Municipales'
        txtEncabezado += '<br />RIF: '
        encabezado = Paragraph(txtEncabezado, cabecera)
        elementos.append(encabezado)
        #---> Fin Encabezado <---

        #---> Datos Contribuyente <---
        styleSheet2 = getSampleStyleSheet()
        estilo_contrib = styleSheet2['BodyText']
        estilo_contrib.alignment = TA_CENTER
        estilo_contrib.fontSize = 7
        estilo_contrib.fontName = 'Times-Roman'
        estilo_contrib.leading = 6
        contrib_style = [
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ]

        elementos.append(Spacer(1, -37))

        contrib1 = Paragraph(u'<b>BOLETIN DE NOTIFICACIÓN</b>', estilo_contrib)
        contrib2 = Paragraph(u'<b>%s</b>' % pagos[0].impuesto.descripcion, estilo_contrib)
        contrib3 = Paragraph(u'<b>PERIODO IMPOSITIVO: %s </b>' % (liquid.ano), estilo_contrib)
        contrib4 = Paragraph(u'<b>FECHA: %s </b>' % liquid.emision, estilo_contrib)

        tabla_contrib = []
        tabla_contrib.append([contrib1])
        tabla_contrib.append([contrib2])
        tabla_contrib.append([contrib3])
        tabla_contrib.append([contrib4])

        tabla_contrib = Table(tabla_contrib, colWidths=(8.0*cm))
        tabla_contrib.setStyle(TableStyle(contrib_style))
        tabla_contrib.hAlign = 'RIGHT'

        elementos.append(tabla_contrib)
        #---> Fin Datos Contrib <---

        #---> Tabla <---
        elementos.append(Spacer(1, 5))

        estilo_tabla = styleSheet['BodyText']
        estilo_tabla.alignment = TA_CENTER
        estilo_tabla.fontSize = 6
        estilo_tabla.leading = 6
        x = [
            ('BACKGROUND', (0, 0), (2, 0), colors.silver),
            ('BACKGROUND', (0, 2), (2, 2), colors.silver),
            ('BACKGROUND', (0, -1), (-1, -1), colors.silver),
            ('GRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 6.5),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
            ('TOPPADDING', (0, 0), (-1, -1), 2),
        ]
        tabla = []

        # Headers de la tabla
        hdatos = Paragraph('<b>R.I.F.</b>', estilo_tabla)
        hdatos1 = Paragraph('<b>RAZON SOCIAL</b>', estilo_tabla)
        hdatos2 = Paragraph('<b>ID</b>', estilo_tabla)

        hdatos3 = Paragraph('<b>DOMICILIO FISCAL</b>', estilo_tabla)
        x.append(('SPAN', (0, 2), (2, 2))),  # Extendiendo columna

        hdatos4 = Paragraph('<b>PERIODO FISCAL:</b>', estilo_tabla)
        hdatos5 = Paragraph('<b>INGRESOS BRUTOS ESTIMADOS</b>', estilo_tabla)
        hdatos6 = Paragraph('<b>IMPUESTO TOTAL ANUAL ESTIMADO</b>', estilo_tabla)
        # Fin Headers de la tabla

        tabla.append([hdatos, hdatos1, hdatos2])
        tabla.append([liquid.contribuyente.num_identificacion, liquid.contribuyente.nombre, liquid.contribuyente.id_contrato])

        # -- Direccion
        tabla.append([hdatos3])
        direccion = Paragraph('%s' % liquid.contribuyente.direccion, estilo_tabla)
        tabla.append([direccion])
        x.append(('SPAN', (0, 3), (2, 3))),  # Extendiendo columna

        # -- Periodo Fiscal
        periodo_fiscal = Paragraph('<b>01 DE ENERO DE %s AL 31 DE DICIEMBRE DE %s</b>' % (liquid.ano, liquid.ano), estilo_tabla)
        tabla.append([hdatos4, periodo_fiscal])
        x.append(('SPAN', (1, 4), (2, 4))),  # Extendiendo columna

        t = Table(tabla, colWidths=(3.5*cm, 11.5*cm, 3.5*cm))
        t.setStyle(TableStyle(x))
        elementos.append(t)
        elementos.append(Spacer(1, 5))

        tabl2 = [] # Tabla 2
        y = [
            ('BACKGROUND', (0, 0), (2, 0), colors.silver),
            ('BOX', (0, 5), (6, 0), 0.50, colors.black),
            ('BOX', (0, 9), (6, 0), 0.50, colors.black),
            ('GRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 6.5),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
            ('TOPPADDING', (0, 0), (-1, -1), 2),
        ]
        tabl2.append([hdatos5, hdatos6])
        montos = liquid.contribuyente.monto_set.filter(contribuyente=liquid.contribuyente, ano=liquid.ano)
        monto_anual = float(montos[0].estimado) * 12
        tabl2.append([montos[0].estimado, monto_anual])

        t2 = Table(tabl2, colWidths=(9.0*cm, 9.5*cm))
        t2.setStyle(TableStyle(y))
        elementos.append(t2)
        elementos.append(Spacer(1, 5))

        tabl3 = [] # Tabla 3
        z = [
            ('BACKGROUND', (0, 0), (7, 0), colors.silver),
            ('BOX', (0, 5), (6, 0), 0.50, colors.black),
            ('BOX', (0, 9), (6, 0), 0.50, colors.black),
            ('GRID', (0, 0), (-1, -1), 0.50, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 6.5),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
            ('TOPPADDING', (0, 0), (-1, -1), 2),
        ]

        titulo_tabl3 = Paragraph('<b>RESUMEN DEL IMPUESTO A PAGAR SEGUN EL MES CUANDO REALICE EL PAGO</b>', estilo_tabla)
        tDatos = Paragraph('<b>TRIMESTRE</b>', estilo_tabla)
        tDatos2 = Paragraph('<b>AÑO</b>', estilo_tabla)
        tDatos3 = Paragraph('<b>IMPUESTO TRIMESTRAL</b>', estilo_tabla)
        tDatos4 = Paragraph('<b>EXIGIBILIDAD</b>', estilo_tabla)
        tDatos5 = Paragraph('<b>RECARGO(10%)</b><br />Si Cancela en...', estilo_tabla)
        tDatos6 = Paragraph('<b>INTERESES ACUMULADOS</b><br />Si Cancela a partir de...', estilo_tabla)
        nota_especial = Paragraph('Se sumara 1% Adicional Mensual por Adelantado', estilo_tabla)

        tabl3.append([titulo_tabl3])
        z.append(('SPAN', (0, 0), (7, 0))),  # Extendiendo columna titulo_tabl3

        tabl3.append([tDatos, tDatos2, tDatos3, tDatos4, tDatos5, '', tDatos6, ''])
        z.append(('SPAN', (4, 1), (5, 1))),  # Extendiendo columna tDatos5
        z.append(('SPAN', (6, 1), (7, 1))),  # Extendiendo columna tDatos6
        z.append(('BACKGROUND', (0, 1), (7, 1), colors.silver)),

        monto_estimado = montos[0].estimado
        monto_trimestres = float(monto_estimado) / 4
        monto_recargo = float(monto_trimestres) * 0.10
        tabl3.append(['1', liquid.ano, monto_trimestres, 'ENERO', 'FEBRERO', monto_recargo, 'MARZO', nota_especial])
        tabl3.append(['2', liquid.ano, monto_trimestres, 'ABRIL', 'MAYO', monto_recargo, 'JUNIO', ''])
        tabl3.append(['3', liquid.ano, monto_trimestres, 'JULIO', 'AGOSTO', monto_recargo, 'SEPTIEMBRE', ''])
        tabl3.append(['4', liquid.ano, monto_trimestres, 'OCTUBRE', 'NOVIEMBRE', monto_recargo, 'DICIEMBRE', ''])
        z.append(('SPAN', (7, 2), (7, 5))),  # Extendiendo columna nota_especial
        z.append(('VALIGN', (7, 2), (7, 5), 'MIDDLE')),

        nota_est = Paragraph('<b>SI CANCELA TODO ANTES DEL 31 DE ENERO DEL AÑO EN CURSO TENDRA<br />UN DESCUENTO DEL 10% DEL MONTO DE SUS IMPUESTOS</b>', estilo_tabla)
        tabl3.append([nota_est])
        z.append(('SPAN', (0, 6), (7, 6))),  # Extendiendo columna nota_est
        z.append(('BACKGROUND', (0, 6), (7, 6), colors.silver)),

        t2 = Table(tabl3, colWidths=(1.9*cm, 1.7*cm, 3.7*cm, 3.5*cm, 2.0*cm, 2.0*cm, 2.0*cm, 2.0*cm))
        t2.setStyle(TableStyle(z))
        elementos.append(t2)
        #---> Fin Tabla <---

        #---> Notas <---
        styleSheetNota = getSampleStyleSheet()
        nota = styleSheetNota['Normal']
        nota.fontSize = 6
        nota.fontName = 'Helvetica'
        nota.alignment = TA_JUSTIFY

        elementos.append(Spacer(1, 5))
        txtNota1 = Paragraph('<b>Ordenanza de Impuesto sobre Actividades Económicas vigente:</b><br />', nota)
        elementos.append(txtNota1)

        txtArt1 = Paragraph('<b>ARTICULO 23.-</b> En el mes de Noviembre de cada año los sujetos pasivos obligados al pago de este impuesto'+\
                            ', presentan por ante la Dirección de Rentas Municipales o el ente que designe el Alcalde, una declaración'+\
                            ' estimada de los ingresos brutos que obtendrán en el ejercicio fiscal siguiente, que conformara la base de'+\
                            ' calculo para la determinación y liquidación del impuesto estimado correspondiente a la obligación tributaria'+\
                            ' que se causará en el transcurso del ejercicio fiscal gravable, la cual será ajustada con la declaración '+\
                            'definitiva de ingresos brutos obtenidos al cierre del ejercicio fiscal del que se trate.<br />', nota)
        elementos.append(txtArt1)

        elementos.append(Spacer(1, 5))
        txtArt2 = Paragraph('"<b>ARTICULO 66.-</b> Serán sancionados en la forma prevista en el artículo de los contribuyentes que:'+\
                            ' ..."d) No paguen, dentro de los plazos previstos en el artículo 24 de esta Ordenanza, la diferencia'+\
                            ' producto de la presentación de la declaración definitiva, con <b>multa equivalente a 10 Unidades'+\
                            ' Tributarias y cierre temporal del establecimiento</b>, hasta tanto cumpla con las obligaciones'+\
                            ' establecidas en dichos artículos."<br />', nota)
        elementos.append(txtArt2)

        elementos.append(Spacer(1, 5))
        txtNota2 = Paragraph('NOTA: La presente notificación no implica la<br />cancelación de años anteriores al %s' % liquid.ano, nota)
        elementos.append(txtNota2)

        elementos.append(Spacer(1, 10))
        styleSheet3 = getSampleStyleSheet()
        parrafo = styleSheet3['Normal']
        parrafo.fontSize = 7
        parrafo.fontName = 'Helvetica'
        parrafo.alignment = TA_CENTER

        elementos.append(Spacer(1, 5))
        txtNota3 = Paragraph('<b>Evite Sanciones... Cumpla con su Ciudad...!</b>', parrafo)
        elementos.append(txtNota3)

        styleSheet3 = getSampleStyleSheet()
        parrafo = styleSheet3['Normal']
        parrafo.fontSize = 7
        parrafo.rightIndent = -320
        parrafo.fontName = 'Helvetica'
        parrafo.alignment = TA_CENTER

        elementos.append(Spacer(1, -50))
        lineaStyle = [
            ('LINEABOVE', (0, 0), (-1, -1), 0.55, colors.black),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 2),
        ]
        linea = []
        linea.append([' '])

        l2 = Table(linea, colWidths=(8.0*cm))
        l2.setStyle(TableStyle(lineaStyle))
        l2.hAlign = 'RIGHT'
        elementos.append(l2)

        elementos.append(Spacer(1, -20))
        txtNota4 = Paragraph('<hr /><br />Directora x' +
                             '<br /><b>Directora</b>', parrafo)
        elementos.append(txtNota4)

        elementos.append(Spacer(1, 15))
        txtNota4 = Paragraph('<b>ALCALDIA</b>', parrafo)
        elementos.append(txtNota4)
        #---> Fin Notas <---

        elementos.append(Spacer(1, 5))
        linea = []
        linea.append([' '])

        l2 = Table(linea, colWidths=(20.0*cm))
        l2.setStyle(TableStyle(lineaStyle))
        elementos.append(l2)

    doc.build(elementos)
    return response
Beispiel #58
0
    def parse_parts(self, buffer):
        # prepare ReportLab
        self.styles = getSampleStyleSheet()
        self.style_stack.append(self.styles['Normal'])
        if self.out_buffer is None:
            self.out_buffer = StringIO()
        self.parts = []

        # prepare for parsing
        i = 0
        buffer_len = len(buffer)
        # Possible modes: 0 = normal, 1 = table row, 2 = insert object
        mode = 0
        new_line = True
        new_para = True
        cue = 0
        content = ''
        raw_table_data = ''
        self.reset_table()
        obj = None

        style_stack = self.style_stack

        paragraphs = split_ignore(buffer, '\n\n', '[[[block', ']]]')

        for p in paragraphs:
            lines = p.split('\n')
            content = ''
            for line in lines:
                c = line[:1]
                if c == '#':
                    debug_print('[comment]')
                elif c == '$':
                    self.parse_paragraph_style(line[1:])
                elif c == '~':
                    debug_print('[document element %s]' % line[1])
                    elem = line[1]
                    endpos = line.find(']', 2)
                    if elem == 'D':
                        self.handle_document_properties(line[3:endpos], line[endpos+1:])
                    elif elem == 'T':
                        if line[2] == '$':
                            # table style
                            raw_style = line[3:]
                            style = self.parse_table_style(raw_style)
                            self.table_styles.append(style)
                        else:
                            self.table_cols = list(float(n) * self.unit for n in line[3:endpos].split('|'))
                            align = line[endpos+1:endpos+2]
                            if align == '<':
                                self.table_align = 'LEFT'
                            elif align == '>':
                                self.table_align = 'RIGHT'
                    elif elem == 'B':
                        self.append_to_parts(PageBreak())
                    elif elem == 'S':
                        self.append_to_parts(Spacer(1, toLength(line[2:])))
                    elif elem == 'V':
                        svg_info_raw = line[3:endpos]
                        svg_info = svg_info_raw.split(';')[:7]
                        if len(svg_info) == 1:
                            mode = 2
                            obj = self.svg_dict[svg_info[0]]
                        else:
                            if len(svg_info) == 7:
                                svg_name, svg_scale, svg_w, svg_h, svg_path, svg_find, svg_replace = svg_info
                            else:
                                svg_name, svg_scale, svg_w, svg_h, svg_path = svg_info

                            svg_file = open(find(svg_path), 'rb')
                            svg_data = svg_file.read()
                            svg_file.close()

                            if len(svg_info) == 7:
                                svg_data = svg_data.replace(svg_find, svg_replace)

                            svg = xml.dom.minidom.parseString(svg_data).documentElement

                            svgRenderer = SvgRenderer()
                            svgRenderer.render(svg)
                            svg_obj = svgRenderer.finish()

                            #svg_obj = svg2rlg(settings.MEDIA_ROOT + svg_path)
                            svg_obj.scale(float(svg_scale), float(svg_scale))
                            svg_obj.asDrawing(float(svg_w) * self.unit, float(svg_h) * self.unit)
                            self.svg_dict[svg_name] = svg_obj
                    elif elem == 'I':
                        img_info_raw = line[3:endpos]
                        img_info = img_info_raw.split(';')[:4]
                        if len(img_info) == 1:
                            mode = 2
                            obj = self.img_dict[img_info[0]]
                        else:
                            img_name, img_w, img_h, img_path = img_info
                            img_obj = Image(find(img_path), width=self.unit*float(img_w), height=self.unit*float(img_h))
                            align = line[endpos+1:endpos+2]
                            if align == '<':
                                img_obj.hAlign = 'LEFT'
                            elif align == '>':
                                img_obj.hAlign = 'RIGHT'
                            self.img_dict[img_name] = img_obj
                    elif elem == 'C':
                        barcode_info_raw = line[3:endpos]
                        barcode_info = barcode_info_raw.split(';')[:6]
                        if len(barcode_info) == 1:
                            mode = 2
                            obj = self.img_dict[barcode_info[0]]
                        else:
                            barcode_name, barcode_type, barcode_scale, barcode_w, barcode_h, barcode_data = barcode_info
                            barcode_obj = Barcode(library=find('common/pdf_img/barcode.ps'),
                                                  width=self.unit * float(barcode_w),
                                                  height=self.unit * float(barcode_h),
                                                  data=barcode_data,
                                                  scale=float(barcode_scale),
                                                  type=barcode_type)
                            align = line[endpos+1:endpos+2]
                            if align == '<':
                                barcode_obj.hAlign = 'LEFT'
                            elif align == '>':
                                barcode_obj.hAlign = 'RIGHT'
                            self.img_dict[barcode_name] = barcode_obj
                    elif elem == 'F':
                        font_info_raw = line[3:endpos]
                        font_info = font_info_raw.split(';')[:2]
                        self.import_pdf_font(font_info[1], font_info[0])
                    elif elem == 'P':
                        if '[' in line:
                            self.parts_buffer = line[3:endpos]
                            self.parts_buffer_dict[self.parts_buffer] = []
                        else:
                            self.parts_buffer = None
                elif c == '[':
                    mode = 1
                    raw_table_data += line + '\n'
                elif c == '\n':
                    pass
                else:
                    if mode == 0:
                        content += line + '\n'
                    elif mode == 1:
                        raw_table_data += line + '\n'

            if mode == 0:
                if content != '':
                    self.append_to_parts(Paragraph(content, self.style_stack[-1] if len(self.style_stack) > 0 else self.styles['Normal']))
                content = ''

            if mode == 1:
                td = raw_table_data
                td_len = len(td)
                i = 0
                while i < td_len:
                    c = td[i]
                    c_1 = td[i-1:i]
                    if c == '[' and c_1 != '\\':
                        cue = i + 1
                    if (c == '|' or c == ']') and c_1 != '\\':
                        cell_content = td[cue:i]
                        pop_after_cell = False
                        if cell_content[:1] == '$':
                            if ' ' in cell_content:
                                style, cell_content = cell_content.split(None, 1)
                                style = style[1:]
                            else:
                                style = ''
                                cell_content = cell_content[1:]
                            self.parse_paragraph_style(style)
                        if cell_content[-1:] == '$':
                            cell_content = cell_content[:-1]
                            pop_after_cell = True
                        if cell_content[:2] == '~V':
                            svg_name = cell_content[2:]
                            self.table_row.append(self.svg_dict[svg_name])
                        elif cell_content[:2] == '~I':
                            img_name = cell_content[2:]
                            self.table_row.append(self.img_dict[img_name])
                        elif cell_content[:2] == '~P':
                            self.table_row.append(self.parts_buffer_dict[cell_content[2:]])
                        else:
                            self.table_row.append(Paragraph(cell_content, self.style_stack[-1] if len(self.style_stack) > 0 else self.styles['Normal']))

                        if pop_after_cell:
                            self.parse_paragraph_style('')

                        cue = i + 1
                        if c == ']':
                            self.table_data.append(self.table_row)
                            self.table_row = []

                    i += 1
                if len(self.table_data) > 0:
                    self.append_to_parts(Table(self.table_data, self.table_cols, hAlign=self.table_align, style=self.table_styles))
                self.reset_table()
                raw_table_data = ''

            if mode == 2:
                if obj is not None:
                    self.append_to_parts(obj)
                    obj = None

            mode = 0

        return self.parts