def fillReport(self, data):
            buffer = self.buffer
            doc = SimpleDocTemplate(buffer,
                                    rightMargin=72,
                                    leftMargin=72,
                                    topMargin=72,
                                    bottomMargin=72,
                                    headertext=self.headertext,
                                    footertext=self.footertext,
                                    pagesize=self.pagesize)

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

            # A large collection of style sheets pre-made for us
            styles = getSampleStyleSheet()
            #styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

            #Configure style and word wrap
            s = getSampleStyleSheet()
            s = s["BodyText"]
            s.wordWrap = 'CJK'
            #format the data table
            data2 = [[Paragraph(cell, s) for cell in row] for row in data]
            t=Table(data2, repeatRows=1)
            #Send the data and build the file
            elements.append(Paragraph('Report', styles['Heading2']))
            elements.append(t)

            doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer)

            # Get the value of the BytesIO buffer and write it to the response.
            pdf = buffer.getvalue()
            buffer.close()
            return pdf
Beispiel #2
0
    def make_report(self, sections_first=True, section_header_params=None):
        """Create the pdf document with name `self.name + '.pdf'`.

        Parameters
        ----------
        sections_first : bool
            If True (default), text and images with sections are presented first
            and un-sectioned content is appended afterword. If False, sectioned
            text and images will be placed before the sections.
        section_header_params : dict or None
            Optionally overwrite/extend the default formatting for the section
            headers. Default is None.
        """
        full_story = list(self._preformat_text(self.title, style='Title',
                                               fontsize=18, alignment='center'))

        # Set the default section header parameters
        if section_header_params is None:
            section_header_params = {'style': 'h1', 'fontsize': 14,
                                     'alignment': 'center'}

        # Merge the sections and the rest of the story.
        if sections_first:
            full_story += self._make_sections(**section_header_params)
            full_story += self.story
        else:
            full_story += self.story
            full_story += self._make_sections(**section_header_params)

        fname = self.name + '.pdf'
        doc = SimpleDocTemplate(fname, pagesize=letter,
                                rightMargin=72, leftMargin=72,
                                topMargin=72, bottomMargin=18)
        doc.build(full_story)
        return fname
Beispiel #3
0
    def handle_pageEnd(self):
        canvas = self.canv
        canvas.setFillColor(colors.black)
        canvas.setFont('Helvetica', 8)
        canvas.drawRightString(self.text_x, self.text_y, self.timestamp)

        SimpleDocTemplate.handle_pageEnd(self)
def GenPDF(tablename, head, result):

    stylesheet = getSampleStyleSheet()
    elements = []

    response = HttpResponse(content_type="application/octet-stream")
    response["Content-Disposition"] = 'attachment;filename="test.pdf"'

    doc = SimpleDocTemplate(response)
    headname = '<font name="hei">' + str(tablename) + "表格</font>"
    # headname = '<font name="hei">%s表格</font>' % tablename
    elements.append(Paragraph(headname, stylesheet["Title"]))
    elements.append(Spacer(1, 12))

    data = []
    data.append(head)

    for l in result:
        row = [l[key] for key in head]
        data.append(row)

    ts = [
        ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("FONT", (0, 0), (-1, -1), "hei"),
    ]
    table = Table(data, 6.3 / len(head) * inch, 0.24 * inch, ts)
    elements.append(table)
    doc.build(elements)

    return response
Beispiel #5
0
    def __init__(self, doc=None, story=None, pagesize = 'A4', printLandscape=False, title=None):

        if doc:
            self._doc = doc
        else:
            #create a new document
            #As the constructor of SimpleDocTemplate can take only a filename or a file object,
            #to keep the PDF data not in a file, we use a dummy file object which save the data in a string
            self._fileDummy = FileDummy()
            if printLandscape:
                self._doc = SimpleDocTemplate(self._fileDummy, pagesize = landscape(PDFSizes().PDFpagesizes[pagesize]))
            else:
                self._doc = SimpleDocTemplate(self._fileDummy, pagesize = PDFSizes().PDFpagesizes[pagesize])

        if title is not None:
            self._doc.title = title

        if story is not None:
            self._story = story
        else:
            #create a new story with a spacer which take all the first page
            #then the first page is only drawing by the firstPage method
            self._story = [PageBreak()]

        if printLandscape:
            self._PAGE_HEIGHT = landscape(PDFSizes().PDFpagesizes[pagesize])[1]
            self._PAGE_WIDTH = landscape(PDFSizes().PDFpagesizes[pagesize])[0]
        else:
            self._PAGE_HEIGHT = PDFSizes().PDFpagesizes[pagesize][1]
            self._PAGE_WIDTH = PDFSizes().PDFpagesizes[pagesize][0]

        self._canv = Canvas
        setTTFonts()
Beispiel #6
0
def buildTable(data):
  doc = SimpleDocTemplate("MOOSE_requirements_tracability.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18)
  doc.pagesize = landscape(A4)
  elements = []

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

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

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

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


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

  doc.build(elements)
Beispiel #7
0
def make_suggested_starts(phage_genes, phage_name, file_path):
    """
        Creates a PDF page of the suggested starts of a phage
        Genes are list in order
        {Gene Name} is a member of Pham {Number}: {Suggested Start Coordinates}
    """
    file_name = os.path.join(file_path, "%sSuggestedStarts.pdf" % (phage_name))
    if check_file(file_name):
        return
    doc = SimpleDocTemplate(file_name, pagesize=letter)
    story = []
    print "making suggested starts page"
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name="paragraph"))
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    text = '<font size=14> Suggested Start Coordinates</font>'
    story.append(Paragraph(text, styles['Center']))
    story.append(Spacer(1, 12))
    for gene_id in sorted(phage_genes.iterkeys()):
        phage_gene = phage_genes[gene_id]
        pham = phage_gene["pham_no"]
        gene = phage_gene["gene"]
        suggested_start = phage_gene["suggested_start"]
        if pham == None:
            text = '<font size=12> %s is not a member of an existing Pham </font>' % (gene.gene_id)
        else:
            text = '<font size=12> %s is a member of Pham %s:  %s </font>' % (gene.gene_id, pham, suggested_start)
        story.append(Paragraph(text, styles['Normal']))
    doc.build(story)
Beispiel #8
0
def generar_pdf_Producto(request):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "productos.pdf" 
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    productos = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Productos", styles['Heading1'])
    productos.append(header)
    headings = ('Proveedor','Nombre', 'Descripcion', 'Marca', 'Precio','Stock Actual')
    allproductos = [(p.prov_id, p.pro_nom, p.pro_des, p.pro_mar, p.pro_pre, p.pro_sto_act) for p in Producto.objects.all()]

    t = Table([headings] + allproductos)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (6, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    
    productos.append(t)
    doc.build(productos)
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #9
0
    def test():
        doc = SimpleDocTemplate("test.pdf")
        story = []

        style = Style(fontName="Helvetica", textIndent=24.0)
        fn = style["fontName"]
        fs = style["fontSize"]
        sampleText1 = createText(TEXT[:100], fn, fs)
        sampleText2 = createText(TEXT[100:], fn, fs)

        text = Text(sampleText1 + makeSpecial(fn, fs) + sampleText2)

        story.append(Paragraph(
            copy.copy(text),
            style,
            debug=0))

        if 0:
            for i in range(10):
                style = copy.deepcopy(style)
                style["textAlign"] = ALIGNMENTS[i % 4]
                text = createText(("(%d) " % i) + TEXT, fn, fs)
                story.append(Paragraph(
                    copy.copy(text),
                    style,
                    debug=0))

        doc.build(story)
    def generate_pdf_report(self, report_id, recipient):
        # setup
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72, leftMargin=72,
            topMargin=72, bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(
            api.NotificationApi.get_cover_page(
                report_id=report_id,
                recipient=recipient,
            ),
        )
        self.pdf_elements.extend(self.report_page(self.report))
        self.pdf_elements.append(
            Paragraph(
                "Report Questions",
                self.section_title_style))
        self.render_questions(self.report_data)

        # teardown
        doc.build(
            self.pdf_elements,
            onFirstPage=self.get_header_footer(recipient),
            onLaterPages=self.get_header_footer(recipient),
            canvasmaker=NumberedCanvas,
        )
        result = report_buffer.getvalue()
        report_buffer.close()
        return result
    def generate(cls, pdf_input_data: dict):
        # setup
        self = cls()
        reports = pdf_input_data.get('reports', [])
        matches = pdf_input_data.get('matches', [])
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72, leftMargin=72,
            topMargin=72, bottomMargin=72,
        )

        # content fill
        self.pdf_elements.extend(self.cover_page())
        self.pdf_elements.extend(self.report_pages(reports))
        self.pdf_elements.extend(self.match_pages_empty_identifier(matches))

        # teardown
        doc.build(
            self.pdf_elements,
            canvasmaker=NumberedCanvas,
        )
        result = report_buffer.getvalue()
        report_buffer.close()
        return result
Beispiel #12
0
def generar_pdf(request):
    print ("Genero el PDF");
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "proveedores.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    proveedores = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Proveedores", styles['Heading1'])
    proveedores.append(header)
    headings = ('No. Proveedor','Nombre','RFC','Giro','Direccion','Ciudad','Estado','Pais','Telefono','Correo','Comentario')
    allproveedores = [(p.num_proveedor, p.nombre, p.RFC ,p.giro ,p.direccion ,p.ciudad ,p.estado ,p.pais ,p.telefono ,p.correo ,p.comentario) for p in Proveedor.objects.all()]
    print (allproveedores);

    t = Table([headings] + allproveedores)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (12, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    proveedores.append(t)
    doc.build(proveedores)
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #13
0
def outputtopdf(outputfile,title,labels,db,resdb):
    import logging
    log = logging.getLogger('outputtopdf')
    try:
            from reportlab.platypus import TableStyle, Table, SimpleDocTemplate, Paragraph
            from reportlab.lib import colors
            from reportlab.lib.styles import getSampleStyleSheet
            from reportlab.pdfgen import canvas
    except ImportError:
            log.error('Reportlab was not found. To export to pdf you need to have reportlab installed. Check out www.reportlab.org')
            return
    log.debug('ok reportlab library found')
    styles = getSampleStyleSheet()
    rows=list()
    rows.append(labels)
    for k in db.keys():
        cols = [k,db[k]]
        if resdb is not None:
            if resdb.has_key(k):
                cols.append(resdb[k])
            else:
                cols.append('N/A')
        rows.append(cols)    
    t=Table(rows)
    mytable = TableStyle([('BACKGROUND',(0,0),(-1,0),colors.black),
                            ('TEXTCOLOR',(0,0),(-1,0),colors.white)])
    t.setStyle(mytable)
    doc = SimpleDocTemplate(outputfile)
    elements = []
    style = styles["Heading1"]
    Title = Paragraph(title,style)
    elements.append(Title)
    elements.append(t)
    doc.build(elements)
Beispiel #14
0
def print_assignment(request, assignment_id=None):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("Elections")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response)
    doc.title = None
    story = []
    
    if assignment_id is None:  #print all applications
        title = config_get("assignment_pdf_title")
        story.append(Paragraph(title, stylesheet['Heading1']))
        preamble = config_get("assignment_pdf_preamble")
        if preamble:
            story.append(Paragraph("%s" % preamble.replace('\r\n','<br/>'), stylesheet['Paragraph']))
        story.append(Spacer(0,0.75*cm))
        # List of assignments
        for assignment in Assignment.objects.order_by('name'):
            story.append(Paragraph(assignment.name, stylesheet['Heading3']))
        # Assignment details (each assignment on single page)
        for assignment in Assignment.objects.order_by('name'):
            story.append(PageBreak())
            story = get_assignment(assignment, story)
    else:  # print selected assignment
        assignment = Assignment.objects.get(id=assignment_id)
        filename = u'filename=%s-%s.pdf;' % (_("Assignment"), assignment.name.replace(' ','_'))
        response['Content-Disposition'] = filename.encode('utf-8')
        story = get_assignment(assignment, story)

    doc.build(story, onFirstPage=firstPage, onLaterPages=firstPage)
    return response
Beispiel #15
0
    def __init__(self, invoice_path, pdf_info=None):
        if not pdf_info:
            pdf_info = self.default_pdf_info

        SimpleDocTemplate.__init__(
            self,
            invoice_path,
            pagesize=letter,
            rightMargin=inch,
            leftMargin=inch,
            topMargin=inch,
            bottomMargin=inch,
            **pdf_info.__dict__
        )

        self._defined_styles = getSampleStyleSheet()
        self._defined_styles.add(
            ParagraphStyle('RightHeading1', parent=self._defined_styles.get('Heading1'), alignment=TA_RIGHT)
        )
        self._defined_styles.add(
            ParagraphStyle('TableParagraph', parent=self._defined_styles.get('Normal'), alignment=TA_CENTER)
        )

        self.invoice_info = None
        self.service_provider_info = None
        self.client_info = None
        self.is_paid = False
        self._items = []
        self._item_tax_rate = None
        self._transactions = []
        self._story = []
        self._bottom_tip = None
        self._bottom_tip_align = None
Beispiel #16
0
def make_note(outfile, headers, paragraphs, **kw):
    """Builds a pdf file named outfile based on headers and
    paragraphs, formatted according to parameters in kw.

    :param outfile: outfile name
    :param headers: <OrderedDict> of headers
    :param paragraphs: <OrderedDict> of paragraphs
    :param kw: keyword arguments for formatting
    """
    story = [Paragraph(x, headers[x]) for x in headers.keys()]

    for headline, paragraph in paragraphs.items():
        story.append(Paragraph(headline, paragraph.get("style", h3)))
        if not paragraph.has_key("tpl"):
            for sub_headline, sub_paragraph in paragraph.items():
                story.append(Paragraph(sub_headline, paragraph.get("style", h4)))
                story.append(Paragraph(sub_paragraph.get("tpl").render(**kw),  p))
        else:
            if isinstance(paragraph.get("tpl"), Template):
                story.append(Paragraph(paragraph.get("tpl").render(**kw), p))
            elif isinstance(paragraph.get("tpl"), Table):
                story.append(Spacer(1, 0.2 * inch))
                story.append(paragraph.get("tpl"))
                story.append(Spacer(1, 0.2 * inch))
            else:
                pass

    doc = SimpleDocTemplate(outfile)
    doc.build(story, onFirstPage=formatted_page, onLaterPages=formatted_page)
    return doc
Beispiel #17
0
def print_agenda(request):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("Agenda")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response)
    story = [Spacer(1,3*cm)]

    doc.title = _("Agenda")
    # print item list
    items = children_list(Item.objects.filter(parent=None).order_by('weight'))
    for item in items:
        if item.hidden is False:
            # print all items"
            if item.parents:
                space = ""
                counter = 0
                for p in item.parents:
                    if counter != 0:
                        space += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                    counter += 1
                story.append(Paragraph(space+item.title, stylesheet['Subitem']))
            else:
                story.append(Paragraph(item.title, stylesheet['Item']))

    doc.build(story, onFirstPage=firstPage, onLaterPages=laterPages)
    return response
Beispiel #18
0
def generar_pdf_Usuario(request):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "usuarios.pdf"
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    usuarios = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Usuarios", styles['Heading1'])
    usuarios.append(header)
    headings = ('Cedula', 'Nombres', 'Apellidos', 'Sexo','Direccion', 'Telefono', 'Email')
    allusuarios = [(p.usu_ced, p.usu_nom, p.usu_ape, p.usu_sex, p.usu_dir, p.usu_tel, p.usu_ema) for p in Usuario.object.all()]

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

    usuarios.append(t)
    doc.build(usuarios)
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #19
0
def PrintPdf(projectNo, probeInf, holelist, index=None):
    import os
    from config import basedir
    cptPath = os.path.join(basedir, 'app', 'static', 'download')

    if not os.path.exists(cptPath):
        os.makedirs(cptPath)
    doc = SimpleDocTemplate(cptPath,
                            pagesize=A4,
                            rightMargin=10,
                            leftMargin=20,
                            topMargin=30,
                            bottomMargin=20
                            )
    doc.pagesize = portrait(A4)
    filename = ''
    elements = []
    for i in range(len(holelist)):
        if index is not None:
            i = index
            filename = projectNo + '__' + holelist[i].holeName + '.pdf'
            # Attenion:where elments.extend must be used,but not elements.append
            elements.extend(Cpt2Pdf(holelist[i], probeInf))
            break;
        else:
            filename = projectNo + '__' + 'all.pdf'
            # Attenion:where elments.extend must be used,but not elements.append
            elements.extend(Cpt2Pdf(holelist[i], probeInf))
    doc.filename = os.path.join(cptPath, filename)
    print("dd" + doc.filename)
    doc.build(elements)
    # url='/'.join(['download',projectNo,filename])
    # os.path.join('download',projectNo,filename)将返回download\projectNo\filename,浏览器无法识别
    return doc.filename
Beispiel #20
0
 def lag(self):
     dok = SimpleDocTemplate(self.filnavn,pagesize = A4)
     #dok.setAuthor("%s (Fryktelig Fin Faktura)" % self.info.firma.kontaktperson)
     #dok.setTitle("Fakturaer hos %s" % self.info.firma.firmanavn)
     #canvas.setSubject("How to Generate PDF files using the ReportLab modules")
     dok.build(self.flow)
     self.oppdatert = True
Beispiel #21
0
def generar_pdf_Factura(request):
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "facturas.pdf" 
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
        )
    facturas = []
    styles = getSampleStyleSheet()
    header = Paragraph("Listado de Facturas", styles['Heading1'])
    facturas.append(header)
    headings = ('Numero de Factura', 'Cliente', 'Fecha', 'Total')
    allfacturas = [(p.fac_num, p.cli_id, p.fac_fec, p.fac_tot) for p in Factura.objects.order_by('fac_num')]

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

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

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

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

        data.append([title_left, title_right])
        t = Table(data, colWidths=[column_width]*2, hAlign=TA_LEFT)
        t.setStyle(
            TableStyle(
                [
                    ('SIZE', (0, 0), (-1, -1), 9),
                    ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                    ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                    ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                    ('LINEABOVE', (0, 0), (-1, -1), 0.5, colors.black),
                    ('LINEBELOW', (0, -1), (-1, -1), 0.5, colors.black),
                ]
            )
        )
        self.flowable.append(t)
Beispiel #25
0
    def _render(self):
        self.result = StringIO()
        parser = xml.dom.minidom.parseString(self.xml)

        title = parser.documentElement.tagName
        doc = SimpleDocTemplate(self.result, pagesize=A4, title=title,
          author='ERP, Fabien Pinckaers', leftmargin=10*mm, rightmargin=10*mm)

        styles = reportlab.lib.styles.getSampleStyleSheet()
        title_style = copy.deepcopy(styles["Heading1"])
        title_style.alignment = reportlab.lib.enums.TA_CENTER
        story = [ Paragraph(title, title_style) ]
        style_level = {}
        nodes = [ (parser.documentElement,0) ]
        while len(nodes):
            node = nodes.pop(0)
            value = ''
            n=len(node[0].childNodes)-1
            while n>=0:
                if node[0].childNodes[n].nodeType==3:
                    value += node[0].childNodes[n].nodeValue
                else:
                    nodes.insert( 0, (node[0].childNodes[n], node[1]+1) )
                n-=1
            if not node[1] in style_level:
                style = copy.deepcopy(styles["Normal"])
                style.leftIndent=node[1]*6*mm
                style.firstLineIndent=-3*mm
                style_level[node[1]] = style
            story.append( Paragraph('<b>%s</b>: %s' % (node[0].tagName, value), style_level[node[1]]))
        doc.build(story)
        return self.result.getvalue()
Beispiel #26
0
def get_output_one_pham(pham, pham_no, config):
    """
        Creates a PDF Report for the specific pham.
        From Start sites statisitics
    """
    output_dir = config['intermediate_file_dir']
    doc = SimpleDocTemplate("%s%sPham%sText.pdf" % (output_dir, phage+one_or_all, pham_no), pagesize=letter)
    story = []
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name="paragraph"))
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    text = '<font size=14> Pham %s Report </font>' % pham_no
    story.append(Paragraph(text, styles['Center']))
    story.append(Spacer(1, 12))
    output = pham.output_start_sites()
    for line in output:
        if line == '':
            story.append(Spacer(1, 12))
        text = '<font size=12> %s </font>' % line
        story.append(Paragraph(text, styles['Normal']))
    suggested_start = pham.output_suggested_starts()
    story.append(Spacer(1, 12))
    for line in suggested_start:
        text = '<font size=12>%s</font>' % line
        story.append(Paragraph(text, styles["Normal"]))
    doc.build(story)
Beispiel #27
0
	def drawPage(meta):
		"""
		Creates cover page
		"""

		def coverPage(canvas, doc):
			"""
			Cover page format
			"""
			canvas.saveState()
			canvas.setFont('Times-Bold',16)
			canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108, Title)
			canvas.setFont('Times-Roman',9)
			canvas.restoreState()

		# PDF Parameters
		PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]
		styles = getSampleStyleSheet()
		Title = 'FITS Summary'

		# Create cover page
		doc = SimpleDocTemplate('%s%s_meta.pdf' %(outDir, filename))
		content = [Spacer(1,2*inch)]
		style = styles["Normal"]
		for key in sorted(meta.keys()):
			text = ("%s: %s \n" % (key, meta[key]))
			p = Paragraph(text, style)
			content.append(p)
		doc.build(content, onFirstPage = coverPage)
Beispiel #28
0
def generar_pdforden(request):
    print "Genero el PDF"
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "ordenes.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    productos = []
    styles = getSampleStyleSheet()
    header = Paragraph("     Listado de Ordenes de Trabajo", styles['Heading1'])
    productos.append(header)
    headings = ('Cliente','Numero','Fecha Recepcion','Fecha Entrega','Tipo','Precio', 'Estado')
    allproductos = [(p.cli_cedula, p.ord_numero, p.ord_fechar, p.ord_fechae,p.ord_tipo,p.ord_precio,p.ord_estado) for p in OrdenTrabajo.objects.all()]
    print allproductos

    t = Table([headings] + allproductos)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (9, -1), 1, colors.springgreen),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.springgreen),
            ('BACKGROUND', (0, 0), (-1, 0), colors.springgreen)
        ]
    ))
    productos.append(t)
    doc.build(productos)
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #29
0
def txt2PDF(path):

    pdfmetrics.registerFont(TTFont('song', 'SURSONG.TTF'))
    pdfmetrics.registerFont(TTFont('hei', 'SIMHEI.TTF'))
    fonts.addMapping('song', 0, 0, 'song')
    fonts.addMapping('song', 0, 1, 'song')
    fonts.addMapping('song', 1, 0, 'hei')
    fonts.addMapping('song', 1, 1, 'hei')

    f=file(path)
    content = f.read()
    contentList = content.split('\n')
    #print contentList

    stylesheet=getSampleStyleSheet()
    normalStyle = copy.deepcopy(stylesheet['Normal'])
    ###设置PDF中文字字体
    normalStyle.fontName ='hei' #字体为黑体
    normalStyle.fontSize = 14.5 #字体大小
    normalStyle.leading = 30    #行间距
    normalStyle.firstLineIndent = 32    #首行缩进
    story = []
    for text in contentList:
        #story.append(Paragraph(unicode(text, "utf-8" ), normalStyle))
        #story.append(Paragraph(text.decode('utf-8'), normalStyle))
        story.append(Paragraph(text.decode('gbk'), normalStyle))
    pdfPath = path.split('.')[0] + '.pdf'
    txtName = path.split('.')[0].split('/')[-1]
    doc = SimpleDocTemplate(pdfPath,
                            rightMargin=20,leftMargin=20,
                            topMargin=20,
                            bottomMargin=20)
    doc.build(story)
Beispiel #30
0
def reporte_detalle_compra(request):
    print ("Genero el PDF");
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Detalle compra.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
                            )
    detalles = []
    styles = getSampleStyleSheet()
    header = Paragraph("Detalle de compra", styles['Heading1'])
    detalles.append(header)
    headings = ('Numero de compra','Producto','Cantidad','Precio','Subtotal')
    alldetalles = [(d.compra,d.producto,d.cantidad,d.precio,d.subtotal) for d in DetalleCompra.objects.all()]
    print (alldetalles);

    t = Table([headings] + alldetalles)
    t.setStyle(TableStyle(
        [
            ('GRID', (0, 0), (12, -1), 1, colors.dodgerblue),
            ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
            ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
        ]
    ))
    detalles.append(t)
    doc.build(detalles)
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #31
0
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Spacer, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
import datetime
import os

styles = getSampleStyleSheet()
i = datetime.datetime.now()
filename = './Modules/Reports/' + i.isoformat()

if not os.path.isdir('./Modules/Reports/'):
    os.system('mkdir ./Modules/Reports/')
    #~ print 'path is created'

doc = SimpleDocTemplate(str(filename) + ".pdf", pagesize=letter)
parts = []


class create_pdf:
    def add_pdf_text(self, finding_name, phase, findings, risk_level,
                     category_level, PoC_notes):

        data = [
            [
                Paragraph(finding_name, styles["Normal"]),
                Paragraph(phase, styles["Normal"])
            ],
            [
                Paragraph(findings, styles["Normal"]),
                Paragraph('Risk Level', styles["Normal"]),
Beispiel #32
0
    def export_sheet(self, filename, data):
        styleSheet = getSampleStyleSheet()
        doc = SimpleDocTemplate(filename, pagesize=A4)
        elements = []

        current_os = platform.system().lower()
        if current_os == 'windows':
            pdfmetrics.registerFont(TTFont('Arial', 'arial.ttf'))
            font_name = 'Arial'
        elif current_os == 'linux':
            pdfmetrics.registerFont(TTFont('Ubuntu', 'Ubuntu-R.ttf'))
            font_name = 'Ubuntu'
        else:
            font_name = 'Helvetica'

        elements.append(Paragraph("Skeleton form - adult inventory",
                                  styleSheet['Title']))
        elements.append(Spacer(0, 10 * mm))

        p_site = Paragraph('''<b>SITE</b>''', styleSheet["BodyText"])
        p_location = Paragraph('''<b>LOCATION</b>''', styleSheet["BodyText"])
        p_skeleton = Paragraph('''<b>SKELETON</b>''', styleSheet["BodyText"])
        p_observer = Paragraph('''<b>OBSERVER</b>''', styleSheet["BodyText"])
        p_date = Paragraph('''<b>DATE</b>''', styleSheet["BodyText"])

        tdata = [
            [p_site, data['site'], '', ''],
            [p_location, data['location'], p_skeleton, data['skeleton']],
            [p_date, data['obs_date'], p_observer, data['observer']]
        ]

        t = Table(tdata)
        t.setStyle(TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                               ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                               ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                               ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                               ('SPAN', (1, 0), (3, 0)),
                               ('FONTNAME', (0, 0), (-1, -1), font_name)
                               ]))

        t._argW[0] = 25 * mm
        t._argW[1] = 63 * mm
        t._argW[2] = 25 * mm
        t._argW[3] = 63 * mm

        elements.append(t)

        # Skull
        elements.append(Spacer(0, 2 * mm))
        custom_style = styleSheet['Heading2']
        custom_style.alignment = 1
        elements.append(Paragraph("Skull inventory", custom_style))
        elements.append(Spacer(0, 2 * mm))

        row1 = ['Bone', 'L', 'R', 'Bone', 'L', 'R', 'Bone', 'L', 'R', 'Vomer', '']

        row2 = ['Frontal',
                data['frontal'],
                '',
                'Sphenoid',
                data['sphenoid'],
                '',
                'Mandible',
                data['mandible'],
                '',
                'Ethmoid',
                data['ethmoid']
                ]

        row3 = ['Parietal',
                data['parietal_l'],
                data['parietal_r'],
                'Nasal',
                data['nasal_l'],
                data['nasal_r'],
                'Palatine',
                data['palatine_l'],
                data['palatine_r'],
                'Thyroid',
                data['thyroid']
                ]

        row4 = ['Occipital',
                data['occipital'],
                '',
                'Maxilla',
                data['maxilla_l'],
                data['maxilla_r'],
                'Lacrimal',
                data['lacrimal_l'],
                data['lacrimal_r'],
                'Hyoid',
                data['hyoid']
                ]

        row5 = ['Temporal',
                data['temporal_l'],
                data['temporal_r'],
                'Zygomatic',
                data['zygomatic_l'],
                data['zygomatic_r'],
                'Orbit',
                data['orbit_l'],
                data['orbit_r'],
                'Calotte',
                data['calotte']
                ]

        sdata = [
            row1,
            row2,
            row3,
            row4,
            row5
        ]

        s = Table(sdata)

        s.setStyle(TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                               ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                               ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                               ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                               ('FONTNAME', (0, 0), (-1, -1), font_name),
                               ('SPAN', (1, 1), (2, 1)),
                               ('SPAN', (4, 1), (5, 1)),
                               ('SPAN', (7, 1), (8, 1)),
                               ('SPAN', (1, 3), (2, 3)),
                               ('ALIGN', (0, 0), (8, 0), 'CENTER'),
                               ('ALIGN', (1, 1), (2, 4), 'CENTER'),
                               ('ALIGN', (4, 1), (5, 4), 'CENTER'),
                               ('ALIGN', (7, 1), (8, 4), 'CENTER'),
                               ('ALIGN', (10, 1), (10, 4), 'CENTER'),
                               ]))

        s._argW[0] = 23 * mm
        s._argW[1] = 12 * mm
        s._argW[2] = 12 * mm
        s._argW[3] = 23 * mm
        s._argW[4] = 12 * mm
        s._argW[5] = 12 * mm
        s._argW[6] = 23 * mm
        s._argW[7] = 12 * mm
        s._argW[8] = 12 * mm
        s._argW[9] = 24 * mm
        s._argW[10] = 12 * mm

        elements.append(s)

        # prepare SVG
        template = 'skull_small.svg'
        self.create_svg(template, "skull_tmp", data)

        # add svg to report
        drawing = svg2rlg("skull_tmp.svg")
        drawing.hAlign = 'CENTER'
        elements.append(Spacer(0, 5 * mm))
        elements.append(drawing)

        # write the document to disk
        try:
            doc.build(elements)
        except Exception as e:
            result = '{}, {}'.format(e.message, e.args)
        else:
            result = ''
        finally:
            if os.path.exists('skull_tmp.svg'):
                os.remove('skull_tmp.svg')

        return result
Beispiel #33
0
        print(detalleFactura)
        facturas.append(list(detalleFactura))
        detalleFactura.clear()

        #except dbapi2.OperationalError as err :
        #    print("Erroro operacprint (detalleFactura)ional: consultaFactura")
    print(facturas)
    print(facturas[0])

finally:

    print("Pechando cursor e conexión base datos")
    cursor.close()
    bbdd.close()

doc = SimpleDocTemplate("exemploTaboas.pdf", pagesize=A4)
guion = []

for factura in facturas:

    taboa = Table(factura, colWidths=80, rowHeights=30)
    taboa.setStyle(
        TableStyle([('TEXTCOLOR', (0, 0), (-1, 0), colors.blue),
                    ('TEXTCOLOR', (0, 1), (-1, -1), colors.green),
                    ('BACKGROUND', (0, 3), (-1, -1), colors.lightcyan),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('BOX', (0, 3), (-1, -1), 1, colors.black),
                    ('INNERGRID', (0, 3), (-1, -1), 0.5, colors.grey)]))

    guion.append(taboa)
    guion.append(Spacer(0, 20))
Beispiel #34
0
def export_pdf_log(request,
                   pk,
                   images=False,
                   comments=False,
                   uidb64=None,
                   token=None):
    """
    Show the workout schedule
    """
    user = request.user

    comments = bool(int(comments))
    images = bool(int(images))

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

    # Create the HttpResponse object with the appropriate PDF headers.
    # and use it to the create the PDF using it as a file like object
    response = HttpResponse(content_type='application/pdf')
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            leftMargin=cm,
                            rightMargin=cm,
                            topMargin=0.5 * cm,
                            bottomMargin=0.5 * cm,
                            title=_('Workout'),
                            author='wger Workout Manager',
                            subject='Schedule for {0}'.format(
                                request.user.username))

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

    # Set the title
    p = Paragraph('<para align="center">{0}</para>'.format(schedule),
                  styleSheet["HeaderBold"])
    elements.append(p)
    elements.append(Spacer(10 * cm, 0.5 * cm))

    # Iterate through the Workout and render the training days
    for step in schedule.schedulestep_set.all():
        p = Paragraph('<para>{0} {1}</para>'.format(step.duration, _('Weeks')),
                      styleSheet["HeaderBold"])
        elements.append(p)
        elements.append(Spacer(10 * cm, 0.5 * cm))

        for day in step.workout.canonical_representation['day_list']:
            elements.append(
                render_workout_day(day,
                                   images=images,
                                   comments=comments,
                                   nr_of_weeks=7))
            elements.append(Spacer(10 * cm, 0.5 * cm))

    # Footer, date and info
    elements.append(Spacer(10 * cm, 0.5 * cm))
    url = reverse('manager:schedule:view', kwargs={'pk': schedule.id})
    elements.append(render_footer(request.build_absolute_uri(url)))

    # write the document and send the response to the browser
    doc.build(elements)
    response[
        'Content-Disposition'] = 'attachment; filename=Schedule-{0}-log.pdf'.format(
            pk)
    response['Content-Length'] = len(response.content)
    return response
Beispiel #35
0
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors

follaEstilo = getSampleStyleSheet()

guion = []

cabeceira = follaEstilo['Heading4']
cabeceira.pageBreakBefore = 1
cabeceira.keepWithNext = 3
cabeceira.backColor = colors.lightgrey

paragrafo = Paragraph("Cabeceira do documento", cabeceira)
guion.append(paragrafo)

cadea = "Cadea de texto para encher o contido do documento. " * 400

estilo = follaEstilo['BodyText']
paragrafo2 = Paragraph(cadea, estilo)
guion.append(paragrafo2)

guion.append(Spacer(0, 20))
fich_imaxe = '/home/dam2/Documentos/RecursosVarios/carta1.jpg'
imaxe_logo = Image(os.path.realpath(fich_imaxe))
guion.append(imaxe_logo)

doc = SimpleDocTemplate("exemploInformePlatypus.pdf",
                        pagesize=A4,
                        showBoundary=1)

doc.build(guion)
import reportlab
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter

import io

buf = io.BytesIO()

# Setup the document with paper size and margins
doc = SimpleDocTemplate(
    buf,
    rightMargin=inch / 2,
    leftMargin=inch / 2,
    topMargin=inch / 2,
    bottomMargin=inch / 2,
    pagesize=letter,
)

# Styling paragraphs
styles = getSampleStyleSheet()

# Write things on the document
paragraphs = []
paragraphs.append(Paragraph('This is a paragraph', styles['Normal']))
paragraphs.append(Paragraph('This is another paragraph', styles['Normal']))
doc.build(paragraphs)

# Write the PDF to a file
with open('/tmp/test.pdf', 'w') as fd:
Beispiel #37
0
    def Imprimer(self, Event=None):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.pagesizes import A4
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        
        hauteur_page = A4[0]
        largeur_page = A4[1]
            
        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("SYNTHESE_IMPAYES", "pdf")
        if sys.platform.startswith("win") : nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, pagesize=(largeur_page, hauteur_page), topMargin=30, bottomMargin=30, leftMargin=40, rightMargin=40)
        story = []
        
        # Création du titre du document
        dataTableau = []
        largeursColonnes = ( (largeur_page-175, 100) )
        dateDuJour = DateEngFr(str(datetime.date.today()))
        dataTableau.append( (_(u"Synthèse des impayés"), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour)) )
        style = TableStyle([
                ('BOX', (0,0), (-1,-1), 0.25, colors.black), 
                ('VALIGN', (0,0), (-1,-1), 'TOP'), 
                ('ALIGN', (0,0), (0,0), 'LEFT'), 
                ('FONT',(0,0),(0,0), "Helvetica-Bold", 16), 
                ('ALIGN', (1,0), (1,0), 'RIGHT'), 
                ('FONT',(1,0),(1,0), "Helvetica", 6), 
                ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 10))       
        
        # Intro
        styleA = ParagraphStyle(name="A", fontName="Helvetica", fontSize=6, spaceAfter=20)
        story.append(Paragraph(self.labelParametres, styleA))       
        
        # Tableau
        dataTableau = []
        largeursColonnes = [160,]
        for x in range(0, len(self.dictImpression["entete"])-1):
            largeursColonnes.append(45)
        
        # Entetes labels
        dataTableau.append(self.dictImpression["entete"])
        
        # Contenu du tableau
        listeRubriques = ("contenu", "total")
        for rubrique in listeRubriques :
            listeLignes = self.dictImpression[rubrique]
            
            for ligne in listeLignes :
                dataTableau.append(ligne)
        
        positionLigneTotal = len(self.dictImpression["contenu"]) + 1
        listeStyles = [
            ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), # Centre verticalement toutes les cases
            
            ('FONT',(0,0),(-1,-1), "Helvetica", 7), # Donne la police de caract. + taille de police 
            ('GRID', (0,0), (-1,-1), 0.25, colors.black), # Crée la bordure noire pour tout le tableau
            ('ALIGN', (0,0), (-1,-1), 'CENTRE'), # Centre les cases
                    
##            ('ALIGN', (0,1), (-1,1), 'CENTRE'), # Ligne de labels colonne alignée au centre
##            ('FONT',(0,1),(-1,1), "Helvetica", 6), # Donne la police de caract. + taille de police des labels
##            
##            ('SPAN',(0,0),(-1,0)), # Fusionne les lignes du haut pour faire le titre du groupe
##            ('FONT',(0,0),(0,0), "Helvetica-Bold", 10), # Donne la police de caract. + taille de police du titre de groupe
            ('BACKGROUND', (0,0), (-1,0), (0.6, 0.6, 0.6) ), # Donne la couleur de fond du label
            ('BACKGROUND', (0, positionLigneTotal), (-1, positionLigneTotal), (0.6, 0.6, 0.6) ), # Donne la couleur de fond du label
            ]
            
        # Formatage des lignes "Activités"
        for indexColoration in self.dictImpression["coloration"] :
            listeStyles.append( ('FONT', (0, indexColoration+1), (-1, indexColoration+1), "Helvetica-Bold", 7) )
            listeStyles.append( ('BACKGROUND', (0, indexColoration+1), (-1, indexColoration+1), (0.8, 0.8, 0.8)) ) 
                
        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)
        story.append(Spacer(0,20))
            
        # Enregistrement du PDF
        doc.build(story)
        
        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
    def Apercu(self):
        """ Impression tableau de données """
        if self.GetNumberRows() == 0 or self.GetNumberCols() == 0:
            dlg = wx.MessageDialog(self, _(u"Il n'y a rien à imprimer !"),
                                   "Erreur", wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return None

        avecCouleurs = True

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

        def ConvertCouleur(couleur):
            r, g, b = couleur[0], couleur[1], couleur[2]
            return r / 255.0, g / 255.0, b / 255.0

        # Récupération des données du tableau
        tableau = self
        nbreColonnes = tableau.GetNumberCols()
        nbreLignes = tableau.GetNumberRows()

        # Initialisation du tableau
        story = []
        dataTableau = []
        listeCouleurs = []

        # Création des colonnes
        largeursColonnes = []
        largeurColonne = 45
        largeurColonneLabel = 90
        for col in range(0, nbreColonnes + 1):
            if col == 0: largeursColonnes.append(largeurColonneLabel)
            else: largeursColonnes.append(largeurColonne)

        listeStyles = [
            ('GRID', (0, 0), (-1, -1), 0.25,
             colors.black),  # Crée la bordure noire pour tout le tableau
            ('VALIGN', (0, 0), (-1, -1),
             'MIDDLE'),  # Centre verticalement toutes les cases
            ('ALIGN', (0, 0), (-1, 0),
             'CENTRE'),  # Centre les labels de colonne
            ('ALIGN', (1, 1), (-1, -1), 'CENTRE'),  # Valeurs à gauche
            ('ALIGN', (0, 1), (0, -1),
             'CENTRE'),  # Colonne Label Ligne centrée
            (
                'FONT', (0, 0), (-1, -1), "Helvetica", 6
            ),  # Donne la police de caract. + taille de police de la ligne de total
            (
                'FONT', (0, 0), (-1, 0), "Helvetica-Bold", 6
            ),  # Donne la police de caract. + taille de police de la ligne de total
        ]

        # Création de l'entete
        style_label_col = ParagraphStyle(name="label",
                                         fontName="Helvetica",
                                         alignment=1,
                                         fontSize=6,
                                         spaceAfter=0,
                                         leading=8,
                                         spaceBefore=0)
        valeursLigne = [
            "",
        ]
        for numColonne in range(0, nbreColonnes):
            labelColonne = tableau.GetColLabelValue(numColonne)
            valeursLigne.append(Paragraph(labelColonne, style_label_col))
        dataTableau.append(valeursLigne)

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

            dataTableau.append(valeursLigne)

        # Style du tableau
        style = TableStyle(listeStyles)

        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes, hAlign='LEFT')
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 20))

        # Calcul du format de la page
        tailleMarge = 20
        if sum(largeursColonnes) > A4[0] - (tailleMarge * 2):
            hauteur, largeur = A4
        else:
            largeur, hauteur = A4

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

        # Insertion du label Paramètres
        styleA = ParagraphStyle(name="A",
                                fontName="Helvetica",
                                fontSize=6,
                                spaceAfter=20)
        story.insert(2, Paragraph(self.labelParametres, styleA))

        # Enregistrement du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("SYNTHESE_CONSO", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc,
                                pagesize=(largeur, hauteur),
                                leftMargin=tailleMarge,
                                rightMargin=tailleMarge,
                                topMargin=tailleMarge,
                                bottomMargin=tailleMarge)
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
def create_report(fname, report):
    def add_text_to_doc(text, style="Normal", fontsize=12):
        Story.append(Spacer(1, 12))
        ptext = "<font size={}>{}</font>".format(fontsize, text)
        Story.append(Paragraph(ptext, styles[style]))
        Story.append(Spacer(1, 12))

    styles = getSampleStyleSheet()
    doc = SimpleDocTemplate(fname,
                            pagesize=letter,
                            rightMargin=inch / 2,
                            leftMargin=inch / 2,
                            topMargin=72,
                            bottomMargin=18)
    # Title section
    Story = []
    Story.append(Spacer(1, 200))
    add_text_to_doc(REPORT_TITLE, style="Title", fontsize=24)
    add_text_to_doc(REPORT_SUBTITLE, style="Title", fontsize=24)
    add_text_to_doc("Report generated on " + REPORT_DATE,
                    style="Title",
                    fontsize=14)

    # Nothing to report
    if not report.get("suspiciousCommunications"):
        add_text_to_doc("No suspicious beaconing communications found :)")

    # Reporting for every suspicious communication
    image_buffers = []
    hist_size = (4.5 * inch, 2.7 * inch)
    for comm in report.get("suspiciousCommunications"):
        Story.append(PageBreak())
        # subtitle describing the communication IP -> IP (port number)
        comm_description = "%s -> %s (port %s)" % (
            comm["srcIp"], comm["dstIp"], comm["dstPort"])
        add_text_to_doc(comm_description, style="Title", fontsize=14)
        histograms = comm["histograms"]
        # plotting delta time
        hist = get_list_from_histogram(histograms["communicationDeltaTime"])
        plot = plot_hist(hist, "Delta time (s)", "Frequency",
                         "Delta time between consecutive communications")
        image_buffers.append(plot)
        im = Image(image_buffers[-1], hist_size[0], hist_size[1])
        Story.append(im)
        # plotting packets
        hist = get_list_from_histogram(histograms["packets"])
        plot = plot_hist(hist, "Number of packets sent", "Frequency",
                         "Packets sent distribution", (1, .5, 0))
        image_buffers.append(plot)
        im = Image(image_buffers[-1], hist_size[0], hist_size[1])
        Story.append(im)
        # plotting bytes
        hist = get_list_from_histogram(histograms["bytes"])
        plot = plot_hist(hist, "Number of bytes sent", "Frequency",
                         "Bytes sent distribution", 'm')
        image_buffers.append(plot)
        im = Image(image_buffers[-1], hist_size[0], hist_size[1])
        Story.append(im)

    doc.build(Story)
    for image_buffer in image_buffers:
        image_buffer.close()
Beispiel #40
0
def genera_orden_compra(datos):
    ubicacion_archivo = dialogo_guardar()

    if ubicacion_archivo is not None:
        # Si no tiene la terminación .pdf se le agrega
        if ubicacion_archivo[-4:].lower() != ".pdf":
            ubicacion_archivo += ".pdf"

        story = []
        cabecera = cabecera_style()
        texto = tabla_celda_just_izquierdo()
        titulo = tabla_celda_just_derecho()

        parrafo = Paragraph("Orden de Compra Nº " + datos[0], cabecera)
        story.append(parrafo)
        story.append(Spacer(0, 20))

        # Generar datos del encabezado
        tabla = Table([[
            Paragraph("<b>Proveedor:</b>", titulo),
            Paragraph(datos[1][0] + ", " + datos[1][1], texto)
        ],
                       [
                           Paragraph("<b>Dirección:</b>", titulo),
                           Paragraph(datos[1][2], texto)
                       ],
                       [
                           Paragraph("<b>Nro. Telefónico:</b>", titulo),
                           Paragraph(datos[1][3], texto)
                       ],
                       [
                           Paragraph("<b>Forma de Pago:</b>", titulo),
                           Paragraph(datos[2], texto)
                       ]], [100, 300])
        tabla.setStyle([
            ('ALIGN', (0, 0), (0, -1),
             'RIGHT'),  # Alineación de la Primera Columna
            ('ALIGN', (1, 1), (-1, -1),
             'LEFT'),  # Alineación de Otras Columnas
            ('VALIGN', (0, 0), (-1, -1),
             'MIDDLE'),  # Alineación Vertical de la Tabla
            ('TOPPADDING', (0, 0), (-1, -1), 1),  # Espacio Arriba
            ('BOTTOMPADDING', (0, 0), (-1, -1), 3),  # Espacio Abajo
            ('LEFTPADDING', (0, 0), (-1, -1), 3),  # Espacio a la Izquierda
            ('RIGHTPADDING', (0, 0), (-1, -1), 3),  # Espacio a la Derecha
        ])
        story.append(tabla)
        story.append(Spacer(0, 20))

        # Generar Tabla de Órdenes de Compra
        tabla = Table(datos[3], [70, 125, 150, 75])
        tabla = tabla_style(tabla)
        story.append(tabla)

        doc = SimpleDocTemplate(
            ubicacion_archivo,
            pagesize=A4,  # Tamaño de Página (landscape(A4) hoja horizontal)
            leftMargin=3 * cm,  # Margen Izquierdo
            rightMargin=3 * cm,  # Margen Derecho
            topMargin=2.5 * cm,  # Margen Superior
            bottomMargin=2.5 * cm,  # Margen Inferior
            allowSplitting=1,
            title="Orden de Compra Nro. " + datos[0],
            author="Sistema Distribuidora")

        try:  # Generar Archivo
            doc.build(story)
            popen(ubicacion_archivo)
        except PermissionError as e:
            error_permiso_archivo(str(e))
Beispiel #41
0
    def OnBoutonApercu(self, event): 
        if self.ValidationSaisie() == False :
            return
        
        typeImpression = self.ctrl_type.GetType() 
        
        # Récupération des paramètres
        tracks = self.ctrl_factures.GetTracksCoches() 
        date_emission = self.ctrl_date.GetDate()
        code_col = self.ctrl_code_coll.GetValue()
        code_nat = self.ctrl_code_nat.GetValue()
        code_rec = self.ctrl_code_rec.GetValue()
        exercice = self.ctrl_exercice.GetValue()
        num_role = self.ctrl_num_role.GetValue()
        
        listeIDfactures = []
        montantTotal = 0.0 
        for track in tracks :
            listeIDfactures.append(track.IDfacture)
            montantTotal += -track.solde

        if len(listeIDfactures) == 0 : conditionFactures = "()"
        elif len(listeIDfactures) == 1 : conditionFactures = "(%d)" % listeIDfactures[0]
        else : conditionFactures = str(tuple(listeIDfactures))

        DB = GestionDB.DB() 
        req = """
        SELECT prestations.IDprestation, prestations.IDfacture, prestations.label, prestations.montant, 
        prestations.IDindividu, individus.nom, individus.prenom,
        prestations.IDactivite, activites.nom
        FROM prestations
        LEFT JOIN individus ON prestations.IDindividu = individus.IDindividu
        LEFT JOIN activites ON activites.IDactivite = prestations.IDactivite
        WHERE prestations.IDfacture IN %s
        GROUP BY prestations.IDprestation
        ORDER BY prestations.date
        ;""" % conditionFactures
        DB.ExecuterReq(req)
        listePrestations = DB.ResultatReq() 
        DB.Close() 
        dictPrestations = {}
        dictIndividus = {}
        dictActivites = {}
        dictTotaux = {}
        for IDprestation, IDfacture, label, montant, IDindividu, nom, prenom, IDactivite, nomActivite in listePrestations :

            if dictActivites != None and dictActivites.has_key(IDactivite) == False :
                dictActivites[IDactivite] = nomActivite

            if IDindividu != None and dictIndividus.has_key(IDindividu) == False and prenom != None :
                dictIndividus[IDindividu] = u"%s %s" % (nom, prenom)
            
            if dictPrestations.has_key(IDfacture) == False :
                dictPrestations[IDfacture] = {}
            if dictPrestations[IDfacture].has_key(IDindividu) == False :
                dictPrestations[IDfacture][IDindividu] = {}
            if dictPrestations[IDfacture][IDindividu].has_key(label) == False :
                dictPrestations[IDfacture][IDindividu][label] = {"quantite" : 0, "montant" : 0.0, "IDactivite" : IDactivite}
            
            if dictTotaux.has_key(IDactivite) == False :
                dictTotaux[IDactivite] = {}
            if dictTotaux[IDactivite].has_key(label) == False :
                dictTotaux[IDactivite][label] = {"quantite" : 0, "montant" : 0.0}
            
            dictTotaux[IDactivite][label]["quantite"] += 1
            dictTotaux[IDactivite][label]["montant"] += montant

            dictPrestations[IDfacture][IDindividu][label]["quantite"] += 1
            dictPrestations[IDfacture][IDindividu][label]["montant"] += montant

        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]
        
        # Initialisation du PDF
        PAGE_WIDTH, PAGE_HEIGHT=defaultPageSize
        nomDoc = FonctionsPerso.GenerationNomDoc("ROLMRE", "pdf")
        if sys.platform.startswith("win") : nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30)
        story = []
        
        largeurContenu = 520
        
        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ( (420, 100) )
            dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
            dataTableau.append( (_(u"Rôle n°%s-%s") % (exercice, num_role), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour)) )
            style = TableStyle([
                    ('BOX', (0,0), (-1,-1), 0.25, colors.black), 
                    ('VALIGN', (0,0), (-1,-1), 'TOP'), 
                    ('ALIGN', (0,0), (0,0), 'LEFT'), 
                    ('FONT',(0,0),(0,0), "Helvetica-Bold", 16), 
                    ('ALIGN', (1,0), (1,0), 'RIGHT'), 
                    ('FONT',(1,0),(1,0), "Helvetica", 6), 
                    ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 20))       
        
        # Insère un header
        Header() 
        
        couleurFond1 = (0.8, 0.8, 1) # Vert -> (0.5, 1, 0.2)
        couleurFond2 = (0.9, 0.9, 1) # Vert -> (0.5, 1, 0.2)
        styleLabel = ParagraphStyle(name="label", fontName="Helvetica", alignment=1, fontSize=5, spaceAfter=0, leading=8, spaceBefore=0)
        styleTexte = ParagraphStyle(name="label", fontName="Helvetica", alignment=0, fontSize=7, spaceAfter=0, leading=8, spaceBefore=0)
        styleTexte2 = ParagraphStyle(name="label", fontName="Helvetica", alignment=1, fontSize=7, spaceAfter=0, leading=8, spaceBefore=0)
        styleMontant = ParagraphStyle(name="label", fontName="Helvetica", alignment=2, fontSize=7, spaceAfter=0, leading=8, spaceBefore=0)

        # Intro
        story.append(Paragraph(_(u"Date d'émission : %s | Code Collectivité : %s | Code Nature : %s | Code Recette : %s") % (UTILS_Dates.DateDDEnFr(date_emission), code_col, code_nat, code_rec), styleTexte))
        story.append(Spacer(0, 20))
        
        # Factures
        if typeImpression in ("detail", "simple") :
            
            for track in tracks :
                
                # Numéro de facture
                dataTableau = []
                largeursColonnes = [100, 100, largeurContenu-100-100]
                dataTableau.append((
                    _(u"Facture n°%s") % track.numero, 
                    u"%.2f %s" % (-track.solde, SYMBOLE),
                    _(u"Edité le %s | Echéance le %s | Période du %s au %s") % (UTILS_Dates.DateDDEnFr(track.date_edition), UTILS_Dates.DateDDEnFr(track.date_echeance), UTILS_Dates.DateDDEnFr(track.date_debut), UTILS_Dates.DateDDEnFr(track.date_fin)),
                    ))
                tableau = Table(dataTableau, largeursColonnes)
                listeStyles = [
                    ('FONT', (0, 0), (1, -1), "Helvetica-Bold", 7),
                    ('FONT', (2, -1), (2, -1), "Helvetica", 6),
                    ('BACKGROUND', (0, 0), (-1, -1), couleurFond1),
                    ('ALIGN', (2, -1), (2, -1), 'RIGHT'),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                    ]
                tableau.setStyle(TableStyle(listeStyles))
                story.append(tableau)
                
                # Famille
                if track.prelevement == True :
                    textePrelevement = _(u"N° Compte : %s | Etab : %s | Guichet : %s | Clé : %s | Titulaire : %s") % (track.prelevement_numero, track.prelevement_etab, track.prelevement_guichet, track.prelevement_cle, track.prelevement_payeur)
                else :
                    textePrelevement = u""
                
                if track.adresse_famille["rue"] != None : rue = track.adresse_famille["rue"]
                else : rue = u""
                if track.adresse_famille["cp"] != None : cp = track.adresse_famille["cp"]
                else : cp = u""
                if track.adresse_famille["ville"] != None : ville = track.adresse_famille["ville"]
                else : ville = u""
                
                dataTableau = [(Paragraph(_(u"Famille"), styleLabel), Paragraph(_(u"Adresse"), styleLabel), Paragraph(_(u"Prélèvement bancaire"), styleLabel)),]
                largeursColonnes = [180, 140, largeurContenu-320]
                dataTableau.append((
                    Paragraph(track.nomsTitulaires, styleTexte), 
                    (Paragraph(rue, styleTexte), Paragraph(u"%s %s" % (cp, ville), styleTexte)),
                    Paragraph(textePrelevement, styleTexte),
                    ))
                tableau = Table(dataTableau, largeursColonnes)
                listeStyles = [
                    ('TOPPADDING', (0, 0), (-1, 0), 0), 
                    ('BOTTOMPADDING',(0, 0), (-1, 0), -1), 
                    ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                    ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                    ('BOX', (0, 1), (-1, 1), 0.25, colors.black),
                    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                    ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                    ]
                tableau.setStyle(TableStyle(listeStyles))
                story.append(tableau)
                
                # Détail des prestations
                if typeImpression == "detail" and dictPrestations.has_key(track.IDfacture) :
                    
                    dataTableau = [(Paragraph(_(u"Individu"), styleLabel), Paragraph(_(u"Activité"), styleLabel), Paragraph(_(u"Prestation"), styleLabel), Paragraph(_(u"Quantité"), styleLabel), Paragraph(_(u"Montant total"), styleLabel)),]
                    largeursColonnes = [130, 120, 185, 35, 50]
                    
                    for IDindividu, dictLabels in dictPrestations[track.IDfacture].iteritems() :
                        
                        if dictIndividus.has_key(IDindividu) :
                            labelIndividu = dictIndividus[IDindividu]
                        else :
                            labelIndividu = u""

                        listeActivites = []
                        listeLabels = []
                        listeQuantites = []
                        listeMontants = []
                        for labelPrestation, dictTemp in dictLabels.iteritems() :

                            if dictTemp["IDactivite"] != None and dictActivites.has_key(dictTemp["IDactivite"]) :
                                labelActivite = dictActivites[dictTemp["IDactivite"]]
                            else :
                                labelActivite = u""
                            
                            listeActivites.append(Paragraph(labelActivite[:35], styleTexte2)) 
                            listeLabels.append(Paragraph(labelPrestation[:40], styleTexte2)) 
                            listeQuantites.append(Paragraph(str(dictTemp["quantite"]), styleTexte2)) 
                            listeMontants.append(Paragraph(u"%.2f %s" % (dictTemp["montant"], SYMBOLE), styleMontant))
                        
                        dataTableau.append((
                            Paragraph(labelIndividu, styleTexte2), 
                            listeActivites,
                            listeLabels,
                            listeQuantites,
                            listeMontants,
                            ))
                            
                    tableau = Table(dataTableau, largeursColonnes)
                    listeStyles = [
                        ('TOPPADDING', (0, 0), (-1, 0), 0), 
                        ('BOTTOMPADDING',(0, 0), (-1, 0), -1), 
                        ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                        ]
                    tableau.setStyle(TableStyle(listeStyles))
                    story.append(tableau)
                    
                story.append(Spacer(0, 10))
        
        # Totaux        
        dictTotaux[IDactivite][label]["montant"]

        dataTableau = [
            (_(u"Totaux par activités et prestations"), "", "", ""),
            (Paragraph(_(u"Activités"), styleLabel), Paragraph(_(u"Prestations"), styleLabel), Paragraph(_(u"Quantité"), styleLabel), Paragraph(_(u"Montant"), styleLabel)),
            ]
        largeursColonnes = [200, 240, 30, 50]

        for IDactivite, dictLabels in dictTotaux.iteritems() :
            
            if IDactivite == None :
                nomActivite = _(u"Prestations familiales")
            else :
                nomActivite = dictActivites[IDactivite]
                
            listeLabels = []
            listeQuantites = []
            listeMontants = []
            quantiteActivite = 0
            totalActivite = 0.0
            for label, dictTemp in dictLabels.iteritems() :
                listeLabels.append(Paragraph(label, styleTexte2)) 
                listeQuantites.append(Paragraph(str(dictTemp["quantite"]), styleTexte2)) 
                listeMontants.append(Paragraph(u"%.2f %s" % (dictTemp["montant"], SYMBOLE), styleMontant))
                quantiteActivite += dictTemp["quantite"]
                totalActivite += dictTemp["montant"]
            
            listeLabels.append(Paragraph(_(u"<b><i>Total de l'activité</i></b>"), styleTexte2)) 
            listeQuantites.append(Paragraph("<b><i>%d</i></b>" % quantiteActivite, styleTexte2)) 
            listeMontants.append(Paragraph(u"<b><i>%.2f %s</i></b>" % (totalActivite, SYMBOLE), styleMontant))
            
            dataTableau.append((
                Paragraph(nomActivite, styleTexte2), 
                listeLabels,
                listeQuantites,
                listeMontants,
                ))

        tableau = Table(dataTableau, largeursColonnes)
        listeStyles = [
            ('TOPPADDING', (0, 1), (-1, 1), 0), 
            ('BOTTOMPADDING',(0, 1), (-1, 1), -1), 
            ('FONT', (1, -1), (-1, -1), "Helvetica", 7),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 7),
            ('BOX', (0, 0), (-1, 0), 0.25, colors.black),
            ('GRID', (0, 1), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
            ('BACKGROUND', (0, 0), (-1, 0), couleurFond1),
            ('BACKGROUND', (0, 1), (-1, 1), couleurFond2),
            ]
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)

        story.append(Spacer(0, 10))

        story.append(Paragraph(_(u"%d factures | Montant total : %.2f %s") % (len(tracks), montantTotal, SYMBOLE), styleTexte))

        # Enregistrement et ouverture du PDF
        try :
            doc.build(story)
        except Exception, err :
            print "Erreur dans ouverture PDF :", err
            if "Permission denied" in err :
                dlg = wx.MessageDialog(None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return False
Beispiel #42
0
def export_pdf(request, id, uidb64=None, token=None):
    '''
    Generates a PDF with the contents of a nutrition plan

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

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

    plan_data = plan.get_nutritional_values()

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

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

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

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

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

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

        meal_markers.append(len(data))

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

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

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

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

    # Set general table styles
    table_style = []

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

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

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

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

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

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

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

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

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

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

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

    response[
        'Content-Disposition'] = 'attachment; filename=nutritional-plan.pdf'
    response['Content-Length'] = len(response.content)
    return response
Beispiel #43
0
    def __init__(self, nom_doc, orientation, dictCategories, dictGroupes,
                 dictLignes, listePresences, dictPresences, coordLigne,
                 hauteur_barre, ecart_lignes, mode_texte):
        # Paramètres du PDF
        self.nom_doc = nom_doc
        if "win" in sys.platform:
            self.nom_doc = self.nom_doc.replace("/", "\\")

        # Initialisation des valeurs
        global DICT_CATEGORIES, HAUTEUR_BARRE, ECART_LIGNES, MODE_TEXTE, COORD_LIGNE
        DICT_CATEGORIES = dictCategories
        HAUTEUR_BARRE = hauteur_barre
        ECART_LIGNES = ecart_lignes
        MODE_TEXTE = mode_texte
        COORD_LIGNE = coordLigne

        # Initialisation du PDF
        global HAUTEUR_PAGE, LARGEUR_PAGE
        if orientation == "portrait":
            taillePage = portrait(A4)
            HAUTEUR_PAGE = defaultPageSize[1]
            LARGEUR_PAGE = defaultPageSize[0]
        else:
            taillePage = landscape(A4)
            HAUTEUR_PAGE = defaultPageSize[0]
            LARGEUR_PAGE = defaultPageSize[1]

        doc = SimpleDocTemplate(self.nom_doc, pagesize=taillePage)
        story = []

        # Création des lignes
        for IDgroupe, valeurs in dictGroupes.items():
            titreGroupe, posY_debut, posY_fin, nbreLignes, listeLignes = valeurs

            # Création du titre du groupe
            styleSheet = getSampleStyleSheet()
            labelGroupe = LabelGroupe(0, 30, titreGroupe)
            story.append(labelGroupe)
            story.append(Spacer(0, 10))

            # Création des lignes du groupe
            for IDpersonneLigne, dateLigne, xxx, labelLigne in listeLignes:
                # Recherche des barres de la ligne
                listeBarresLigne = []
                for IDpresence, IDpersonne, date, heureDebut, heureFin, IDcategorie, intitule, posG, posD, posYhaut, posYbas in listePresences:
                    if (IDpersonne == IDpersonneLigne) and (date == dateLigne):
                        # Création de la barre
                        listeBarresLigne.append(
                            (IDpresence, IDpersonne, date, heureDebut,
                             heureFin, IDcategorie, intitule, posG, posD,
                             posYhaut, posYbas))

                ligne = Ligne(0, HAUTEUR_BARRE - 3 + ECART_LIGNES, labelLigne,
                              listeBarresLigne)
                story.append(ligne)

            # Espace après le groupe
            story.append(Spacer(0, 20))

        # Légendes des catégories
        story.append(Spacer(0, 10))
        nbre_legendes = 0
        total_heures = 0
        for key, valeurs in dictCategories.items():
            nom, IDcat_parent, ordre, couleur, nbreHeures = valeurs
            if nbreHeures != 0:
                legende = Legende(0, 15, nom, couleur, nbreHeures)
                story.append(legende)
                nbre_legendes += 1
                total_heures += nbreHeures
        if nbre_legendes > 1:
            # Ajoute un total d'heures
            legende = Legende(0, 15, _(u"Total"), None, total_heures)
            story.append(legende)

        # Enregistrement du PDF
        doc.build(story)
Beispiel #44
0
def generate_statistics_pdf(activities=None, start_date=None, all_years=False, year=None):
    """ Accepts EighthActivity objects and outputs a PDF file. """
    if activities is None:
        activities = EighthActivity.objects.all().order_by("name")
    if year is None:
        year = current_school_year()

    if not isinstance(activities, list):
        activities = activities.prefetch_related("rooms").prefetch_related("sponsors")

    pdf_buffer = BytesIO()

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

    elements = []

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name="Indent", leftIndent=15))

    empty_activities = []

    for act in activities:
        lelements = []
        relements = []
        act_stats = calculate_statistics(act, start_date=start_date, all_years=all_years, year=year)
        if act_stats["total_blocks"] == 0:
            empty_activities.append(act.name)
            continue
        elements.append(Paragraph(act.name, styles["Title"]))
        sponsor_str = (", ".join([x.name for x in act.sponsors.all()])) if act.sponsors.count() > 0 else "None"
        lelements.append(Paragraph("<b>Default Sponsors:</b> " + sponsor_str, styles["Normal"]))
        lelements.append(Spacer(0, 0.025 * inch))
        room_str = (", ".join([str(x) for x in act.rooms.all()])) if act.rooms.count() > 0 else "None"
        relements.append(Paragraph("<b>Default Rooms:</b> " + room_str, styles["Normal"]))
        relements.append(Spacer(0, 0.025 * inch))

        relements.append(Paragraph("<b>Total blocks:</b> {}".format(act_stats["total_blocks"]), styles["Normal"]))
        relements.append(Paragraph("<b>Scheduled blocks:</b> {}".format(act_stats["scheduled_blocks"]), styles["Indent"]))
        relements.append(Paragraph("<b>Empty blocks:</b> {}".format(act_stats["empty_blocks"]), styles["Indent"]))
        relements.append(Paragraph("<b>Cancelled blocks:</b> {}".format(act_stats["cancelled_blocks"]), styles["Indent"]))

        lelements.append(Paragraph("<b>Total signups:</b> {}".format(act_stats["total_signups"]), styles["Normal"]))
        lelements.append(Paragraph("<b>Average signups per block:</b> {}".format(act_stats["average_signups"]), styles["Indent"]))
        lelements.append(Paragraph("<b>Average signups per student:</b> {}".format(act_stats["average_user_signups"]), styles["Indent"]))
        lelements.append(
            Paragraph("<b>Unique students:</b> {}, <b>Capacity:</b> {}".format(act_stats["students"], act_stats["capacity"]), styles["Normal"])
        )

        elements.append(
            Table(
                [[lelements, relements]],
                style=[("LEFTPADDING", (0, 0), (-1, -1), 0), ("RIGHTPADDING", (0, 0), (-1, -1), 0), ("VALIGN", (0, 0), (-1, -1), "TOP")],
            )
        )

        parsed_members = [[x.username, y] for x, y in act_stats["members"]]
        parsed_members = list(chunks(parsed_members, 30))[:3]
        if parsed_members:
            parsed_members = [[["Username", "Signups"]] + x for x in parsed_members]
            parsed_members = [
                Table(x, style=[("FONT", (0, 0), (1, 0), "Helvetica-Bold"), ("ALIGN", (1, 0), (1, -1), "RIGHT")]) for x in parsed_members
            ]
            elements.append(Table([parsed_members], style=[("VALIGN", (-1, -1), (-1, -1), "TOP")]))
            if act_stats["students"] - 90 > 0:
                elements.append(Paragraph("<b>{}</b> students were not shown on this page. ".format(act_stats["students"] - 90), styles["Normal"]))
        else:
            elements.append(Spacer(0, 0.20 * inch))

        if start_date is not None:
            elements.append(
                Paragraph(
                    "<b>{}</b> block(s) are past the start date and are not included on this page.".format(act_stats["past_start_date"]),
                    styles["Normal"],
                )
            )
        elements.append(
            Paragraph(
                "<b>{}</b> block(s) not in the {}-{} school year are not included on this page.".format(act_stats["old_blocks"], year - 1, year),
                styles["Normal"],
            )
        )

        elements.append(PageBreak())

    if empty_activities:
        empty_activities = [x[:37] + "..." if len(x) > 40 else x for x in empty_activities]
        empty_activities = [[x] for x in empty_activities]
        empty_activities = list(chunks(empty_activities, 35))
        empty_activities = [[["Activity"]] + x for x in empty_activities]
        empty_activities = [
            Table(x, style=[("FONT", (0, 0), (-1, 0), "Helvetica-Bold"), ("LEFTPADDING", (0, 0), (-1, -1), 0)]) for x in empty_activities
        ]
        for i in range(0, len(empty_activities), 2):
            elements.append(Paragraph("Empty Activities (Page {})".format(i // 2 + 1), styles["Title"]))
            if all_years:
                elements.append(Paragraph("The following activities have no 8th period blocks assigned to them.", styles["Normal"]))
            else:
                elements.append(
                    Paragraph(
                        "The following activities have no 8th period blocks assigned to them for the {}-{} school year.".format(year - 1, year),
                        styles["Normal"],
                    )
                )
            elements.append(Spacer(0, 0.10 * inch))
            ea = [empty_activities[i]]
            if i + 1 < len(empty_activities):
                ea.append(empty_activities[i + 1])
            elements.append(
                Table(
                    [ea],
                    style=[("LEFTPADDING", (0, 0), (-1, -1), 0), ("RIGHTPADDING", (0, 0), (-1, -1), 0), ("VALIGN", (0, 0), (-1, -1), "TOP")],
                    hAlign="LEFT",
                )
            )
            elements.append(PageBreak())

    def first_page(canvas, _):
        if len(activities) == 1:
            canvas.setTitle("{} Statistics".format(activities[0].name))
        else:
            canvas.setTitle("8th Period Activity Statistics")
        canvas.setAuthor("Generated by Ion")

    doc.build(elements, onFirstPage=first_page)

    pdf_buffer.seek(0)

    return pdf_buffer
Beispiel #45
0
def get_apply_table(apply_id):
    """
    生成申请审批表
    :param apply_id: 审批表编号
    :return: 生成的pdf路径
    """
    wl = "select apply_id, tenant_name, sex, tenant_IDcode, marital_status, tenant_unit, tenant_unit_address, " + \
         "unit_property, unit_pro_business, unit_pro_office, unit_pro_employment, unit_pro_retire, unit_pro_other, " + \
         "pro_graduate, pro_outside, pro_gov_talent, pro_difficult, pro_cheap, pro_economy, card_address, " + \
         "now_address, minimum_living_no, member_name_1, member_relation_1, member_ID_1, member_unit_1, " + \
         "member_income_1, member_name_2, member_relation_2, member_ID_2, member_unit_2, member_income_2, " + \
         "member_name_3, member_relation_3, member_ID_3, member_unit_3, member_income_3, member_name_4, " + \
         "member_relation_4, member_ID_4, member_unit_4, member_income_4, member_name_5, member_relation_5, " + \
         "member_ID_5, member_unit_5, member_income_5, income_avg, income_all, member_name_11, member_address_11, " + \
         "member_con_area_11, member_door_pro_11, member_name_12, member_address_12, member_con_area_12, " + \
         "member_door_pro_12, is_transfer, transfer_address_1, transfer_con_area_1, is_remove, remove_address_1, " + \
         "remove_con_area_1, con_area_avg, user_name, occur_date, community_name, street_name, remark, " + \
         "transfer_pro_1, remove_pro_1 " + \
         "FROM t_public_doors_apply where apply_id = '" + apply_id + "'"
    db = DB()
    apply, re_s = db.get_data_by_sql(wl)
    if len(apply) == 0:
        return 'not found'
    pdfmetrics.registerFont(TTFont('simsun', 'SimSun.ttf'))
    pdfmetrics.registerFont(TTFont('simhei', 'SimHei.ttf'))
    style_sheet = getSampleStyleSheet()
    # 标题
    title_style = style_sheet['Title']
    title_style.fontName = 'simhei'
    title_style.fontSize = 22
    elements = [Paragraph('立山区公共租赁租房(申请)审批表', title_style)]
    elements.append(Spacer(0, 0.3 * cm))
    # 标题下一行小字
    doc_style = ParagraphStyle(name='rightstyle',
                               fontName='simsun',
                               fontSize=10,
                               alignment=TA_CENTER)
    line0 = Paragraph('编号:' + apply_id + '\0' * 30 + '单位:平方米,人,元', doc_style)
    elements.append(line0)
    elements.append(Spacer(0, 0.3 * cm))
    # 创建画布,画表格
    width, height = 19 * cm, 25 * cm
    # 第一页开画
    d1 = Drawing(width, height)
    d1.background = Rect(0,
                         0,
                         width,
                         height,
                         strokeWidth=1,
                         strokeColor="#000000",
                         fillColor=None)  # 边框颜色
    d1.add(Line(1.2 * cm, 24 * cm, width, 24 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 23 * cm, width, 23 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 22 * cm, width, 22 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 21 * cm, width, 21 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 19.5 * cm, width, 19.5 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 18 * cm, width, 18 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 17 * cm, width, 17 * cm, strokeWidth=0.5))
    d1.add(Line(0 * cm, 16 * cm, width, 16 * cm, strokeWidth=0.8))
    d1.add(Line(1.2 * cm, 25 * cm, 1.2 * cm, 8.8 * cm, strokeWidth=0.5))
    d1.add(Line(3.5 * cm, 25 * cm, 3.5 * cm, 0 * cm, strokeWidth=0.5))
    d1.add(Line(6.5 * cm, 25 * cm, 6.5 * cm, 24 * cm, strokeWidth=0.5))
    d1.add(Line(8.0 * cm, 25 * cm, 8.0 * cm, 24 * cm, strokeWidth=0.5))
    d1.add(Line(10 * cm, 25 * cm, 10 * cm, 24 * cm, strokeWidth=0.5))
    d1.add(Line(12 * cm, 25 * cm, 12 * cm, 24 * cm, strokeWidth=0.5))
    d1.add(Line(10 * cm, 23 * cm, 10 * cm, 22 * cm, strokeWidth=0.5))
    d1.add(Line(12 * cm, 23 * cm, 12 * cm, 22 * cm, strokeWidth=0.5))
    d1.add(get_label(x=2.25 * cm, y=24.5 * cm, text='姓名', size=10))
    d1.add(
        get_label(x=5 * cm, y=24.5 * cm, text=apply[0]['tenant_name'],
                  size=10))
    d1.add(get_label(x=7.25 * cm, y=24.5 * cm, text='性别', size=10))
    d1.add(get_label(x=9 * cm, y=24.5 * cm, text=apply[0]['sex'], size=10))
    d1.add(get_label(x=11 * cm, y=24.5 * cm, text='身份证', size=10))
    d1.add(
        get_label(x=14.5 * cm,
                  y=24.5 * cm,
                  text=apply[0]['tenant_IDcode'],
                  size=10))
    d1.add(get_label(x=2.25 * cm, y=23.5 * cm, text='婚姻状况', size=10))
    d1.add(
        get_label(x=4.5 * cm,
                  y=23.5 * cm,
                  text=apply[0]['marital_status'],
                  size=10))
    d1.add(get_label(x=2.25 * cm, y=22.5 * cm, text='工作单位', size=10))
    d1.add(
        get_label(x=6.5 * cm,
                  y=22.5 * cm,
                  text=apply[0]['tenant_unit'],
                  size=10))
    d1.add(get_label(x=11 * cm, y=22.5 * cm, text='单位地址', size=10))
    d1.add(
        get_label(x=15.5 * cm,
                  y=22.5 * cm,
                  text=apply[0]['tenant_unit_address'],
                  size=10))
    d1.add(get_label(x=2.25 * cm, y=21.5 * cm, text='单位性质', size=10))
    unit_pro = ''
    if int(apply[0]['unit_pro_business']) == 1:
        unit_pro += '企业 '
    if int(apply[0]['unit_pro_office']) == 1:
        unit_pro += '机关 '
    if int(apply[0]['unit_pro_employment']) == 1:
        unit_pro += '个体 '
    if int(apply[0]['unit_pro_retire']) == 1:
        unit_pro += '退休 '
    if int(apply[0]['unit_pro_other']) == 1:
        unit_pro += '其它'
    d1.add(get_label(x=10 * cm, y=21.5 * cm, text=unit_pro, size=10))
    d1.add(get_label(x=2.25 * cm, y=20.25 * cm, text='申请人类型', size=10))
    tenant_pro = ''
    if int(apply[0]['pro_graduate']) == 1:
        tenant_pro += '新就业普通高校毕业生'
    if int(apply[0]['pro_outside']) == 1:
        tenant_pro += '外来务工人员'
    if int(apply[0]['pro_gov_talent']) == 1:
        tenant_pro += '政府引进特殊人才'
    if int(apply[0]['pro_difficult']) == 1:
        tenant_pro += '困难家庭'
    if int(apply[0]['pro_cheap']) == 1:
        tenant_pro += '廉租房保障家庭'
    if int(apply[0]['pro_economy']) == 1:
        tenant_pro += '经济房保障家庭'
    d1.add(get_label(x=10 * cm, y=20.25 * cm, text=tenant_pro, size=10))
    d1.add(get_label(x=2.25 * cm, y=18.75 * cm, text='户口所在\n\0地址', size=10))
    d1.add(
        get_label(x=10 * cm,
                  y=18.75 * cm,
                  text=apply[0]['card_address'],
                  size=10))
    d1.add(get_label(x=2.25 * cm, y=17.5 * cm, text='现居住地址', size=10))
    d1.add(
        get_label(x=10 * cm,
                  y=17.5 * cm,
                  text=apply[0]['now_address'],
                  size=10))
    d1.add(get_label(x=2.25 * cm, y=16.5 * cm, text='低保证号', size=10))
    d1.add(
        get_label(x=10 * cm,
                  y=16.5 * cm,
                  text=apply[0]['minimum_living_no'],
                  size=10))
    d1.add(
        get_label(x=0.5 * cm,
                  y=20.5 * cm,
                  text='申\n请\n人\n基\n本\n情\n况\n及\n申\n请\n公\n共\n租\n赁\n住\n房\n情\n况',
                  size=10))
    d1.add(Line(1.2 * cm, 14.8 * cm, width, 14.8 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 13.6 * cm, width, 13.6 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 12.4 * cm, width, 12.4 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 11.2 * cm, width, 11.2 * cm, strokeWidth=0.5))
    d1.add(Line(1.2 * cm, 10 * cm, width, 10 * cm, strokeWidth=0.5))
    d1.add(Line(0 * cm, 8.8 * cm, width, 8.8 * cm, strokeWidth=0.8))
    d1.add(Line(6 * cm, 16 * cm, 6 * cm, 8.8 * cm, strokeWidth=0.5))
    d1.add(Line(11 * cm, 16 * cm, 11 * cm, 7.3 * cm, strokeWidth=0.5))
    d1.add(Line(16.5 * cm, 16 * cm, 16.5 * cm, 8.8 * cm, strokeWidth=0.5))
    d1.add(Line(0 * cm, 7.3 * cm, width, 7.3 * cm, strokeWidth=0.8))
    d1.add(Line(13.5 * cm, 8.8 * cm, 13.5 * cm, 7.3 * cm, strokeWidth=0.5))
    d1.add(
        get_label(x=0.5 * cm,
                  y=12.5 * cm,
                  text='申\n请\n人\n家\n庭\n收\n入\n情\n况',
                  size=10))
    d1.add(get_label(x=2.25 * cm, y=15.4 * cm, text='与申请\n人关系', size=10))
    d1.add(
        get_label(x=2.25 * cm,
                  y=14.2 * cm,
                  text=apply[0]['member_relation_1'],
                  size=10))
    d1.add(
        get_label(x=2.25 * cm,
                  y=13 * cm,
                  text=apply[0]['member_relation_2'],
                  size=10))
    d1.add(
        get_label(x=2.25 * cm,
                  y=11.8 * cm,
                  text=apply[0]['member_relation_3'],
                  size=10))
    d1.add(
        get_label(x=2.25 * cm,
                  y=10.6 * cm,
                  text=apply[0]['member_relation_4'],
                  size=10))
    d1.add(
        get_label(x=2.25 * cm,
                  y=9.4 * cm,
                  text=apply[0]['member_relation_5'],
                  size=10))
    d1.add(get_label(x=4.75 * cm, y=15.4 * cm, text='姓名', size=10))
    d1.add(
        get_label(x=4.75 * cm,
                  y=14.2 * cm,
                  text=apply[0]['member_name_1'],
                  size=10))
    d1.add(
        get_label(x=4.75 * cm,
                  y=13 * cm,
                  text=apply[0]['member_name_2'],
                  size=10))
    d1.add(
        get_label(x=4.75 * cm,
                  y=11.8 * cm,
                  text=apply[0]['member_name_3'],
                  size=10))
    d1.add(
        get_label(x=4.75 * cm,
                  y=10.6 * cm,
                  text=apply[0]['member_name_4'],
                  size=10))
    d1.add(
        get_label(x=4.75 * cm,
                  y=9.4 * cm,
                  text=apply[0]['member_name_5'],
                  size=10))
    d1.add(get_label(x=8.5 * cm, y=15.4 * cm, text='身份证', size=10))
    d1.add(
        get_label(x=8.5 * cm,
                  y=14.2 * cm,
                  text=apply[0]['member_ID_1'],
                  size=10))
    d1.add(
        get_label(x=8.5 * cm, y=13 * cm, text=apply[0]['member_ID_2'],
                  size=10))
    d1.add(
        get_label(x=8.5 * cm,
                  y=11.8 * cm,
                  text=apply[0]['member_ID_3'],
                  size=10))
    d1.add(
        get_label(x=8.5 * cm,
                  y=10.6 * cm,
                  text=apply[0]['member_ID_4'],
                  size=10))
    d1.add(
        get_label(x=8.5 * cm,
                  y=9.4 * cm,
                  text=apply[0]['member_ID_5'],
                  size=10))
    d1.add(get_label(x=13.75 * cm, y=15.4 * cm, text='工作单位', size=10))
    d1.add(
        get_label(x=13.75 * cm,
                  y=14.2 * cm,
                  text=apply[0]['member_unit_1'],
                  size=10))
    d1.add(
        get_label(x=13.75 * cm,
                  y=13 * cm,
                  text=apply[0]['member_unit_2'],
                  size=10))
    d1.add(
        get_label(x=13.75 * cm,
                  y=11.8 * cm,
                  text=apply[0]['member_unit_3'],
                  size=10))
    d1.add(
        get_label(x=13.75 * cm,
                  y=10.6 * cm,
                  text=apply[0]['member_unit_4'],
                  size=10))
    d1.add(
        get_label(x=13.75 * cm,
                  y=9.4 * cm,
                  text=apply[0]['member_unit_5'],
                  size=10))
    d1.add(get_label(x=17.75 * cm, y=15.4 * cm, text='年收入', size=10))
    d1.add(
        get_label(x=17.75 * cm,
                  y=14.2 * cm,
                  text=str(apply[0]['member_income_1']),
                  size=10))
    d1.add(
        get_label(x=17.75 * cm,
                  y=13 * cm,
                  text=str(apply[0]['member_income_2']),
                  size=10))
    d1.add(
        get_label(x=17.75 * cm,
                  y=11.8 * cm,
                  text=str(apply[0]['member_income_3']),
                  size=10))
    d1.add(
        get_label(x=17.75 * cm,
                  y=10.6 * cm,
                  text=str(apply[0]['member_income_4']),
                  size=10))
    d1.add(
        get_label(x=17.75 * cm,
                  y=9.4 * cm,
                  text=str(apply[0]['member_income_5']),
                  size=10))
    d1.add(get_label(x=1.8 * cm, y=8.1 * cm, text='家庭人均月收入', size=10))
    d1.add(
        get_label(x=4.8 * cm,
                  y=8.1 * cm,
                  text=str(apply[0]['income_avg']),
                  size=10))
    d1.add(get_label(x=12.25 * cm, y=8.1 * cm, text='家庭成员\n年收入合计', size=10))
    d1.add(
        get_label(x=14.5 * cm,
                  y=8.1 * cm,
                  text=str(apply[0]['income_all']),
                  size=10))
    d1.add(get_label(x=1.8 * cm, y=4.1 * cm, text='家庭收入\n认定意见', size=10))
    d1.add(get_label(x=11.8 * cm, y=4.1 * cm, text='经办人', size=10))
    d1.add(get_label(x=15.8 * cm, y=4.1 * cm, text='认定部门(盖章)', size=10))
    d1.add(get_label(x=15.8 * cm, y=1.1 * cm, text='年\0\0\0月\0\0\0日', size=10))
    elements.append(d1)
    # 第二页 开画
    d2 = Drawing(width, height)
    d2.background = Rect(0,
                         0,
                         width,
                         height,
                         strokeWidth=1,
                         strokeColor="#000000",
                         fillColor=None)  # 边框颜色
    d2.add(Line(1.2 * cm, 25 * cm, 1.2 * cm, 17.5 * cm, strokeWidth=0.5))
    d2.add(Line(1.2 * cm, 23.5 * cm, width, 23.5 * cm, strokeWidth=0.5))
    d2.add(Line(1.2 * cm, 22 * cm, width, 22 * cm, strokeWidth=0.5))
    d2.add(Line(1.2 * cm, 20.5 * cm, width, 20.5 * cm, strokeWidth=0.5))
    d2.add(Line(1.2 * cm, 19 * cm, width, 19 * cm, strokeWidth=0.5))
    d2.add(Line(0 * cm, 17.5 * cm, width, 17.5 * cm, strokeWidth=0.5))
    d2.add(Line(0 * cm, 16 * cm, width, 16 * cm, strokeWidth=0.8))
    d2.add(Line(5.2 * cm, 25 * cm, 5.2 * cm, 16 * cm, strokeWidth=0.5))
    d2.add(Line(13.2 * cm, 25 * cm, 13.2 * cm, 17.5 * cm, strokeWidth=0.5))
    d2.add(Line(16.2 * cm, 25 * cm, 16.2 * cm, 17.5 * cm, strokeWidth=0.5))
    d2.add(Line(0 * cm, 11 * cm, width, 11 * cm, strokeWidth=0.8))
    d2.add(Line(0 * cm, 6 * cm, width, 6 * cm, strokeWidth=0.8))
    d2.add(Line(9.5 * cm, 16 * cm, 9.5 * cm, 11 * cm, strokeWidth=0.8))
    d2.add(
        get_label(x=0.5 * cm,
                  y=21.5 * cm,
                  text='申\n请\n人\n家\n庭\n成\n员\n住\n房\n情\n况',
                  size=10))
    d2.add(get_label(x=3.25 * cm, y=24.2 * cm, text='产权人或承租人', size=10))
    d2.add(
        get_label(x=3.25 * cm,
                  y=22.8 * cm,
                  text=apply[0]['member_name_11'],
                  size=10))
    d2.add(
        get_label(x=3.25 * cm,
                  y=21.2 * cm,
                  text=apply[0]['member_name_12'],
                  size=10))
    d2.add(get_label(x=9.25 * cm, y=24.2 * cm, text='房屋坐落', size=10))
    d2.add(
        get_label(x=9.25 * cm,
                  y=22.8 * cm,
                  text=apply[0]['member_address_11'],
                  size=10))
    d2.add(
        get_label(x=9.25 * cm,
                  y=21.2 * cm,
                  text=apply[0]['member_address_12'],
                  size=10))
    d2.add(get_label(x=14.75 * cm, y=24.2 * cm, text='建筑面积', size=10))
    d2.add(
        get_label(x=14.75 * cm,
                  y=22.8 * cm,
                  text=str(apply[0]['member_con_area_11']),
                  size=10))
    d2.add(
        get_label(x=14.75 * cm,
                  y=21.2 * cm,
                  text=str(apply[0]['member_con_area_12']),
                  size=10))
    d2.add(get_label(x=17.55 * cm, y=24.2 * cm, text='住房性质', size=10))
    d2.add(
        get_label(x=17.55 * cm,
                  y=22.8 * cm,
                  text=apply[0]['member_door_pro_11'],
                  size=10))
    d2.add(
        get_label(x=17.55 * cm,
                  y=21.2 * cm,
                  text=apply[0]['member_door_pro_12'],
                  size=10))
    d2.add(get_label(x=3.25 * cm, y=19.75 * cm, text='近五年转让\n房屋情况', size=10))
    d2.add(
        get_label(x=9.25 * cm,
                  y=19.75 * cm,
                  text=apply[0]['transfer_address_1'],
                  size=10))
    d2.add(
        get_label(x=14.75 * cm,
                  y=19.75 * cm,
                  text=str(apply[0]['transfer_con_area_1']),
                  size=10))
    d2.add(
        get_label(x=17.55 * cm,
                  y=19.75 * cm,
                  text=str(apply[0]['transfer_pro_1']),
                  size=10))
    d2.add(get_label(x=3.25 * cm, y=18.25 * cm, text='近五年拆迁\n房屋情况', size=10))
    d2.add(
        get_label(x=9.25 * cm,
                  y=18.25 * cm,
                  text=apply[0]['remove_address_1'],
                  size=10))
    d2.add(
        get_label(x=14.75 * cm,
                  y=18.25 * cm,
                  text=str(apply[0]['remove_con_area_1']),
                  size=10))
    d2.add(
        get_label(x=17.55 * cm,
                  y=18.25 * cm,
                  text=str(apply[0]['remove_pro_1']),
                  size=10))
    d2.add(get_label(x=2.25 * cm, y=16.75 * cm, text='家庭人均建筑面积', size=10))
    d2.add(
        get_label(x=9.25 * cm,
                  y=16.75 * cm,
                  text=str(apply[0]['con_area_avg']),
                  size=10))
    d2.add(get_label(x=2 * cm, y=15.25 * cm, text='所在社区意见:', size=10))
    d2.add(get_label(x=1.45 * cm, y=13.5 * cm, text='负责人:', size=10))
    d2.add(get_label(x=1.45 * cm, y=12.5 * cm, text='经办人:', size=10))
    d2.add(get_label(x=7.45 * cm, y=12.5 * cm, text='公章', size=10))
    d2.add(get_label(x=7.45 * cm, y=11.5 * cm, text='年\0\0\0月\0\0\0日',
                     size=10))
    d2.add(get_label(x=11.9 * cm, y=15.25 * cm, text='所在街道办事处意见:', size=10))
    d2.add(get_label(x=10.75 * cm, y=13.5 * cm, text='负责人:', size=10))
    d2.add(get_label(x=10.75 * cm, y=12.5 * cm, text='经办人:', size=10))
    d2.add(get_label(x=16.75 * cm, y=12.5 * cm, text='公章', size=10))
    d2.add(
        get_label(x=16.75 * cm, y=11.5 * cm, text='年\0\0\0月\0\0\0日', size=10))
    d2.add(get_label(x=3.25 * cm, y=10.25 * cm, text='区县(市)住房保障部门意见:',
                     size=10))
    d2.add(get_label(x=1.45 * cm, y=8.75 * cm, text='负责人:', size=10))
    d2.add(get_label(x=1.45 * cm, y=7.75 * cm, text='经办人:', size=10))
    d2.add(get_label(x=16.75 * cm, y=7.75 * cm, text='公章', size=10))
    d2.add(get_label(x=16.75 * cm, y=6.5 * cm, text='年\0\0\0月\0\0\0日',
                     size=10))
    d2.add(get_label(x=3.25 * cm, y=5 * cm, text='市保障性住房管理办公室意见:', size=10))
    d2.add(get_label(x=16.75 * cm, y=1 * cm, text='年\0\0\0月\0\0\0日', size=10))
    elements.append(Spacer(0, 1.75 * cm))
    elements.append(d2)
    report_name = report_path + apply_id + ".pdf"
    doc = SimpleDocTemplate(main_path + report_name,
                            topMargin=0.6 * cm,
                            leftMargin=0.7 * cm,
                            rightMargin=0.6 * cm,
                            bottomMargin=0 * cm,
                            title=apply_id)
    doc.build(elements)
    return report_name
Beispiel #46
0
    def CreaPdfTest (self, testName, ValorMedioPrestazioniParams, ValorMedioPrestazioniDims, 
        MigliorRisultatoParams, MigliorRisultatoDims, PeggiorRisultatoParams, PeggiorRisultatoDims,
        ltestp, ltestd):
        
        #per prima cosa carico i grafici ottenuti

        graphParams = os.path.normpath(self.folderGrafici + testName + self.filenameGraphParams)
        graphDims = os.path.normpath(self.folderGrafici + testName + self.filenameGraphDim)
        
        #creo l'oggetto immagine dei grafici
        graphParams = Image(graphParams, 20*cm, 15*cm)
        graphDims = Image(graphDims, 20*cm, 15*cm)
        #carico le immagini standard
        imgLogoUni = Image(self.filenameLogoUni, 5*cm, 5*cm)
        
        #Inizo a creare il documento pdf
        testPdfFilename = self.folderPdfs + testName + u".pdf"
        
        doc = SimpleDocTemplate(testPdfFilename, pagesize=A4,
                                rightMargin=72,leftMargin=72,
                                topMargin=72,bottomMargin=18)
        documento = list ()
        
        documento.append(imgLogoUni)             
        documento.append(Spacer(1,17)) 
        
        styles=getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Justify', alignment=TA_RIGHT))
        ptext = "TEST: %s"% testName
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7))
        ptext = "Risultati Ottenuti dai test:"
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,17))
        ptext = "Media prestazioni test sulla tipologia PARAMS : %f \n"% ValorMedioPrestazioniParams 
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7))
        ptext =  "Media prestazioni test sulla tipologia DIMS   : %f \n"%  ValorMedioPrestazioniDims
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7)) 
        ptext = "Miglior risultato \n"
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7))
        ptext = "Prestazione migliore test in condizioni %s sulla tipologia PARAMS %f: \n"% MigliorRisultatoParams
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7))
        ptext = "Prestazione migliore test in condizioni %s sulla tipologia DIMS   %f: \n"%  MigliorRisultatoDims
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7))
        ptext =  "peggior risultato \n"
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7))
        ptext =  "Prestazione peggiore test in condizioni %s sulla tipologia PARAMS %f: \n"%  PeggiorRisultatoParams
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7))
        ptext =  "Prestazione peggiore test in condizioni %s sulla tipologia DIMS   %f: \n"%  PeggiorRisultatoDims
        documento.append(Paragraph(ptext, styles["Normal"]))
        documento.append(Spacer(1,7))
        
        
        if len(ltestp) > 0:
            documento.append(Spacer(1,7))
            ptext =  "parametri di costruzione corpus:"
            documento.append(Paragraph(ptext, styles["Normal"]))
            documento.append(Spacer(1,7))
            ptext =  "Risultati identici si ottengono anche parametrizzando il tokenizzatore con i seguenti parametri:"
            documento.append(Paragraph(ptext, styles["Normal"]))
            documento.append(Spacer(1,7))
            for ele in ltestp:
                txt = ""
                if type (ele) == type(dict ()):
                    for k in ele.keys():
                        txt = txt + k + u" " + unicode(ele[k]) + u" "
                else:
                    raise ValueError ("Attenzione caso non ancora gestito!")
                ptext =  "%s" % txt #ele.viewitems().__str__()
                documento.append(Paragraph(ptext, styles["Normal"]))
                documento.append(Spacer(1,7))
                
                
            for ele in ltestd:
                txt = ""
                if type (ele) == type(dict ()):
                    for k in ele.keys():
                        txt = txt + k + u" " + unicode(ele[k]) + u" "
                else:
                    raise ValueError ("Attenzione caso non ancora gestito!")
                ptext =  "%s" % txt# ele.viewitems().__str__()
                documento.append(Paragraph(ptext, styles["Normal"]))
                documento.append(Spacer(1,7))

        documento.append(graphParams)  
        styles=getSampleStyleSheet()
        
        documento.append(Spacer(1,7))
        
        documento.append(graphDims)  
        
        doc.build(documento)                    
Beispiel #47
0
    def receipt(self, message):

        receipt = []

        styles = getSampleStyleSheet()

        styles.add(
            ParagraphStyle(
                name="pizza-title",
                fontName="roboto",
                fontSize=16,
                leading=18,
                alignment=TA_CENTER,
            )
        )
        styles.add(
            ParagraphStyle(
                name="pizza-center",
                fontName="roboto",
                fontSize=10,
                leading=12,
                alignment=TA_CENTER,
            )
        )

        styles.add(
            ParagraphStyle(
                name="pizza-normal",
                fontName="roboto",
                fontSize=10,
                leading=14,
                alignment=TA_JUSTIFY,
            )
        )

        text = "Receipt {}".format(message["receipt_id"])
        receipt.append(Paragraph(text, styles["pizza-title"]))
        receipt.append(Spacer(1, 25))

        text = "Thanks for using {}. This PDF is the receipt for your purchase. No payment is due.".format(
            message["product_name"]
        )
        receipt.append(Paragraph(text, styles["pizza-center"]))
        receipt.append(Spacer(1, 25))

        pizza_image = "{}/{}".format(settings.MEDIA_ROOT, message["image"])
        receipt.append(Image(pizza_image))
        receipt.append(Spacer(1, 25))

        hash_object = hashlib.md5(message["receipt_id"].encode())
        file_name = "receipt/{}.pdf".format(hash_object.hexdigest())

        doc = SimpleDocTemplate(
            "{}/{}".format(settings.MEDIA_ROOT, file_name),
            pagesize=A4,
            rightMargin=40,
            leftMargin=40,
            topMargin=150,
            bottomMargin=0,
        )
        doc.build(receipt)

        self.receipt_url = "http://127.0.0.1:8000/media/{}".format(file_name)

        return self.receipt_url
Beispiel #48
0
def workout_log(request,
                id,
                images=False,
                comments=False,
                uidb64=None,
                token=None):
    """
    Generates a PDF with the contents of the given workout

    See also
    * http://www.blog.pythonlibrary.org/2010/09/21/reportlab
    * http://www.reportlab.com/apis/reportlab/dev/platypus.html
    """
    comments = bool(int(comments))
    images = bool(int(images))

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

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

    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(
        response,
        pagesize=A4,
        # pagesize = landscape(A4),
        leftMargin=cm,
        rightMargin=cm,
        topMargin=0.5 * cm,
        bottomMargin=0.5 * cm,
        title=_('Workout'),
        author='wger Workout Manager',
        subject=_('Workout for %s') % request.user.username)

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

    # Add site logo
    elements.append(get_logo())
    elements.append(Spacer(10 * cm, 0.5 * cm))

    # Set the title
    p = Paragraph(
        f'<para align="center"><strong>{workout.name}</strong></para>',
        styleSheet["HeaderBold"])
    elements.append(p)
    elements.append(Spacer(10 * cm, 0.5 * cm))
    if workout.description:
        p = Paragraph(f'<para align="center">{workout.description}</para>')
        elements.append(p)
        elements.append(Spacer(10 * cm, 1.5 * cm))

    # Iterate through the Workout and render the training days
    for day in workout.day_set.all():
        elements.append(
            render_workout_day(day, images=images, comments=comments))
        elements.append(Spacer(10 * cm, 0.5 * cm))

    # Footer, date and info
    elements.append(Spacer(10 * cm, 0.5 * cm))
    elements.append(
        render_footer(request.build_absolute_uri(workout.get_absolute_url())))

    # write the document and send the response to the browser
    doc.build(elements)

    # Create the HttpResponse object with the appropriate PDF headers.
    response[
        'Content-Disposition'] = 'attachment; filename=Workout-{0}-log.pdf'.format(
            id)
    response['Content-Length'] = len(response.content)
    return response
    def coord(self, x, y, unit=1):
        """
        http://stackoverflow.com/questions/4726011/wrap-text-in-a-table-reportlab
        Helper class to help position flowables in Canvas objects
        """
        x, y = x * unit, self.height - y * unit
        return x, y

    #----------------------------------------------------------------------
    def draw(self):
        """
        Draw the shape, text, etc
        """
        self.canv.rect(self.x, self.y, self.width, self.height)
        self.canv.line(self.x, 0, 500, 0)

        p = Paragraph(self.text, style=self.styles["Normal"])
        p.wrapOn(self.canv, self.width, self.height)
        p.drawOn(self.canv, *self.coord(self.x + 2, 10, mm))


doc = SimpleDocTemplate("test3.pdf", pagesize=letter)
story = []

box = BoxyLine(text="foo")
story.append(box)
story.append(Spacer(0, 1 * inch))
box = BoxyLine(text="bar")
story.append(box)

doc.build(story)
Beispiel #50
0
def create_pdf_page(full_name, address_parts, metin):

    doc = SimpleDocTemplate(str(full_name + "_" + address_parts[0] + ".pdf"),
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

    Story = []
    logo = "python.png"

    print("create pdf page")
    formatted_time = time.ctime()

    im = Image(logo, 2 * inch, 2 * inch)
    Story.append(im)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    ptext = '<font size=12>%s</font>' % formatted_time

    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    # Create return address
    ptext = '<font size=12>%s</font>' % full_name
    Story.append(Paragraph(ptext, styles["Normal"]))
    for part in address_parts:
        ptext = '<font size=12>%s</font>' % part.strip()
        Story.append(Paragraph(ptext, styles["Normal"]))

    Story.append(Spacer(1, 12))
    # ptext = '<font size=12>Dear %s:</font>' % full_name.split()[0].strip()
    ptext = " "
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))
    ##paragraf_N
    for i in range(len(metin)):
        #metin
        ptext = '<font size=9>' + str(metin["text"][i]) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 12))
        ##link

        link_pdf = 'http://kbora.xyz/' + str(metin.pdf_link[i])
        print(link_pdf)
        ptext = '<link href="' + link_pdf + '">' + link_pdf + '</link>'

        Story.append(Paragraph(ptext, styles["Code"]))
        Story.append(Spacer(1, 10))

    ##sabit page##
    ##paragraf_3
    ptext = '<font size=9>Thank you very much and we look forward to serving you.</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))
    ##paragraf_4
    ptext = '<font size=9>Sincerely,</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 48))

    ptext = '<font size=9>Howard.ai</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))
    print("story oluşturuyuluyor")
    doc.build(Story)

    return str(full_name + "_" + address_parts[0] + ".pdf")
import os
import time

from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, PageBreak
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import A4
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.lib import colors
from reportlab.lib.units import inch

from reportlab.graphics.shapes import Drawing, Rect, String, Group, Line
from reportlab.graphics.widgets.markers import makeMarker

from shutil import rmtree

doc = SimpleDocTemplate('GraficosWin.pdf', pagesize=A4)
story = []
estilo = getSampleStyleSheet()

gatos_dir = 'C:/Users/TRIGUN/Desktop/TrabajoWIN/garfield'
contenido = os.listdir(gatos_dir)
rmtree('C:/Users/TRIGUN/Desktop/TrabajoWIN/garfield_Procesado')
os.mkdir('C:/Users/TRIGUN/Desktop/TrabajoWIN/garfield_Procesado')
tim_to_gray = []
tim_to_hist = []
imgs = []

for fichero in contenido:
    if os.path.isfile(os.path.join(gatos_dir,
                                   fichero)) and fichero.endswith('.jpg'):
        nombre = str(fichero)
Beispiel #52
0
def generar_pdf(request, ubigeo, zonal, aeut):
    print "Se va a generar el PDF de Ubigeo: "+ str(ubigeo)+ " de zona: " + str(zonal) + " y AE: "+str(aeut)
    MARGIN_SIZE = 17 * mm
    PAGE_SIZE = A4
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = "attachment; filename=" + ubigeo + "001" + str(aeut) + ".pdf"
    # response['Content-Disposition'] = "attachment; filename="+ubigeo+"001"+".pdf"
    pdf_name = "clientes.pdf"
    styles = getSampleStyleSheet()
    stylesTitle = getSampleStyleSheet()
    stylesCabe = getSampleStyleSheet()

    styleTitle = stylesTitle["Normal"]
    styleTitle.alignment = TA_CENTER
    styleBH = styles["Normal"]
    styleBH.alignment = TA_LEFT
    styleCa = stylesCabe["Normal"]
    styleCa.alignment = TA_CENTER

    buff = BytesIO()
    # destino = "Lista/" + str(ubigeo)+"00100"+ str(aeut)+ ".pdf"
    #
    # doc2 = SimpleDocTemplate(destino, pagesize=A4,
    #                          rightMargin=70,
    #                          leftMargin=70,
    #                          topMargin=0.5 *cm,
    #                          bottomMargin=0.5 *cm, )
    doc = SimpleDocTemplate(buff,
                            pagesize=A4,
                            rightMargin=65,
                            leftMargin=65,
                            topMargin=0.5 *cm,
                            bottomMargin=0.5 *cm,
                            )

    h_sub_tile = PS(
        name='Heading1',
        fontSize=10,
        leading=14,
        alignment=TA_CENTER
    )

    h_sub_tile_2 = PS(
        name='Heading1',
        fontSize=11,
        leading=14,
        alignment=TA_CENTER
    )

    h_center = PS(
        name='Heading1',
        fontSize=7,
        leading=8,
        alignment=TA_CENTER
    )

    h1 = PS(
        name='Heading1',
        fontSize=7,
        leading=8
    )

    h11 = PS(
        name='Heading1',
        fontSize=7,
        leading=8,
        alignment=TA_CENTER
    )

    h2 = PS(
        name='Normal',
        fontSize=6,
        leading=16
    )

    h3 = PS(
        name='Normal',
        fontSize=7,
        leading=14,
        alignment=TA_CENTER)

    h4 = PS(
        name='Normal',
        fontSize=6,
        leading=16
    )

    h5 = PS(
        name='Normal',
        fontSize=8,
        leading=16,
        alignment=TA_CENTER
    )

    h_obser = PS(
        name='Normal',
        fontSize=8,
        leading=16
    )

    h_bar = PS(
        name='Normal',
        fontSize=7,
        leading=14,
        alignment=TA_CENTER
    )

    story = []

    distrito = Distrito.objects.get(ubigeo=ubigeo)  # ubigeo

    # vivi = ViviendaUrbana.objects.get(ubigeo=distrito.ubigeo, zona='00100', aeu_final=aeut)



    # cond_viv = Aeus.objects.filter(ubigeo=distrito.ubigeo, zona='00100', aeu_final=aeut)

    # total = Aeus.objects.filter(ubigeo=distrito.ubigeo, zona='00100', aeu_final=aeut).count()

    # viv_u = ViviendaU.objects.filter(ubigeo=ubigeo)

    rango_equivalencia = [[1, 'A'], [2, 'B'], [3, 'C'], [4, 'D'], [5, 'E'], [6, 'F'], [7, 'G'], [8, 'H'], [9, 'I'],
                          [10, 'J'], [11, 'K'], [12, 'L'], [13, 'M'], [14, 'N'], [15, 'O'], [16, 'P'], [17, 'Q'], [18, 'R'],
                          [19, 'S'], [20, 'T'], [21, 'U'], [22, 'V'], [23, 'W'], [24, 'X'], [25, 'Y'], [26, 'Z']
                          ]

    Z1 = Paragraph("<strong>OBSERVACIONES: .............................................................................."
                   "....................................................................................................."
                   "....................................................................................................."
                   "....................................................................................................."
                   "....................................................................................................."
                   "....................................................................................................."
                   "................................................................................</strong>", h_obser)

    # table_obs = Table(
    #     data=[
    #         [Z1]
    #     ],
    #     colWidths=[18.8 * cm],
    #     rowHeights=[2 * cm],
    #     style=[
    #         ('GRID', (0, 0), (-1, -1), 1, colors.black)
    #     ]
    # )

    Z2 = Paragraph("<strong>EMPADRONADOR</strong>", h5)

    Z3 = Paragraph("<strong>Todas las viviendas que estén dentro de los límites de tu A.E.U. deben ser empadronadas. Debes tener<br/>cuidado de no omitir ninguna vivienda</strong>",h5)

    table_empa_cuerp = Table(
        data=[
            [Z2],
            [Z3]
        ],
        colWidths=[18.8 * cm],
        rowHeights=[0.7 * cm, 1.5 * cm],
        style=[
            ('GRID', (0, 0), (0, 0), 1, colors.black),
            ('GRID', (0, 1), (0, 1), 1, colors.black),
            ('ALIGN', (0, 0), (0, 0), 'CENTER')
        ]
    )
    cond =v_ReporteCabViviendasTab.objects.filter(ubigeo=ubigeo, zona=zonal, aeu_final=aeut)
    x = 0

    lista_zonas = []
    for aeu in cond:
        x = x + 1
        y = x

        secc = str(aeu.seccion).zfill(3)
        aeus = str(aeu.aeu_final).zfill(3)
        aeut_conv = str(aeu.aeu_final).zfill(3)

        lista_distritos = []
        lista_distritos.append(ubigeo)
        listin = []
        tam_dis = 1
        for ubigein in range(tam_dis):

            if os.path.exists("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein])) == False:
                os.mkdir("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]))

            total_zonas = int(str(Esp_Aeus.objects.filter(ubigeo=lista_distritos[ubigein]).values_list('zona',flat=True).distinct().count()))
            total_zonales = Esp_Aeus.objects.filter(ubigeo=lista_distritos[ubigein]).values_list('zona', flat=True)
            cuchi = list(set(total_zonales))
            lista_zonas.append(total_zonas)

            for zona_t in range(total_zonas):
                #zoner = str(zona_t + 1).zfill(3) + "00"
                listin.append(str(lista_distritos[ubigein]) + ": " + cuchi[zona_t] + "<br/>")
                if os.path.exists("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]) + "\\" + cuchi[zona_t]) == False:
                    os.mkdir("\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]) + "\\" + cuchi[zona_t])
                    # destino = "\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(lista_distritos[ubigein]) + "\\" + zoner+ "\\" + str(ubigeo) + zonal + str(secc)+str(aeut) + ".pdf"
                    #
                    #
                    #
                    # doc2 = SimpleDocTemplate(destino, pagesize=A4,
                    #                                        rightMargin=70,
                    #                                        leftMargin=70,
                    #                                        topMargin=0.5 * cm,
                    #                                        bottomMargin=0.5 * cm, )

        destino = "\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(ubigeo) + "\\" + zonal+ "\\" + str(ubigeo) + zonal + str(secc) + str(aeut_conv) + ".pdf"
        doc2 = SimpleDocTemplate(destino, pagesize=A4,
                                          rightMargin=70,
                                          leftMargin=70,
                                          topMargin=0.5 * cm,
                                          bottomMargin=0.5 * cm,)
        # destino =  "\\\srv-fileserver\\CPV2017\\list_segm_tab\\" + str(ubigeo) + zonal + str(secc)+str(aeut) + ".pdf"
        #
        # doc2 = SimpleDocTemplate(destino, pagesize=A4,
        #                          rightMargin=70,
        #                          leftMargin=70,
        #                          topMargin=0.5 * cm,
        #                          bottomMargin=0.5 * cm, )

        p = Paragraph(str(1) + " - " + str(1), h2)
        extra = Paragraph("-", h2)
        p_page = Table(
            data=[
                [extra, p]
            ],
            colWidths=[17 * cm, 2.3 * cm],
            style=[
                ('GRID', (0, 0), (-1, -1), 1, colors.white),
                ('ALIGN', (0, 0), (1, 0), 'RIGHT'),
            ]
        )
        string = str(ubigeo)+zonal+str(secc)+str(aeut)
        st = code39.Extended39(string)
        bar_string = Paragraph(string, h_bar)
        pi = Paragraph("-", h2)
        st_b = st
        table_bar = Table(
            data = [
                [pi, st_b],
                ['', bar_string]
            ],
            colWidths= [13 * cm, 5 * cm],
            style=[
                ('ALIGN', (0, 0), (-1, -1),'CENTER')
            ]
        )
        #story.append(table_bar)
        # zona_temp = aeu.zona[0:3]
        # zona_int = int(aeu.zona[3:])
        # zona_int_eq = ""
        # for el in rango_equivalencia:
        #     if (el[0] == zona_int):
        #         zona_int_eq = el[1]
        # zona_temp = zona_temp + str(zona_int_eq)
        data = [
            ['', '', '', '', '', Paragraph('<strong>Doc. CPV</strong>', h4)],
            [Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h11), '', '', '',
             Paragraph('<strong>B. UBICACION CENSAL</strong>', h11), ''],
            [Paragraph('<strong>DEPARTAMENTO</strong>', h1),Paragraph(str(aeu.ccdd), h_center),
             Paragraph(str(aeu.departamento), h1), '',
             Paragraph('<strong>ZONA Nº</strong>', h1),Paragraph(aeu.zona_convert, h_center)],
            [Paragraph('<strong>PROVINCIA</strong>', h1), Paragraph(aeu.ccpp, h_center),
             Paragraph(str(aeu.ccdi).decode('latin-1'), h1), '', Paragraph(str('<strong>SECCION Nº</strong>'), h1), Paragraph(aeu.seccion, h_center)],
            [Paragraph('<strong>DISTRITO</strong>', h1), Paragraph(aeu.ccdi, h_center), Paragraph(aeu.distrito, h1),
             '', Paragraph('<strong>A.E.U. Nº</strong>', h1), Paragraph(aeus, h_center)],
            [Paragraph('<strong>CENTRO POBLADO</strong>', h1), Paragraph(aeu.nomccpp, h1), '', '', '', ''],
            [Paragraph('<strong>CATEGORIA DEL CENTRO POBLADO</strong>', h1), Paragraph('CIUDAD', h1), '', '',
             Paragraph('<strong>TOTAL DE VIVIENDAS<br/>DEL A.E.U.</strong>', h1),Paragraph(str(aeu.cant_viv), h_center)],
        ]
        tables = Table(data, colWidths=[3.7 * cm, 1 * cm, 8.1 * cm, 0.3 * cm, 4.7 * cm, 2 * cm],
                       rowHeights=[0.4 * cm, 0.4  * cm, 0.4  * cm, 0.4  * cm, 0.4  * cm, 0.4  * cm, 0.7  * cm])
        tables.setStyle(TableStyle([
            ('TEXTCOLOR', (0, 0), (5, 0), colors.black),
            ('ALIGN', (4, 0), (5, 0), 'RIGHT'),
            ('ALIGN', (1, 2), (1, 4), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 1), (2, 6), 1, colors.black),
            ('GRID', (4, 1), (5, 4), 1, colors.black),
            ('GRID', (-2, -1), (-1, -1), 1, colors.black),
            ('SPAN', (0, 1), (2, 1)),
            ('SPAN', (4, 1), (5, 1)),
            ('SPAN', (1, 5), (2, 5)),
            ('SPAN', (1, 6), (2, 6)),
            ('BACKGROUND', (0, 1), (0, 6), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (0, 1), (2, 1), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 1), (5, 1), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 1), (4, 4), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 6), (4, 6), colors.Color(219.0/255,229.0/255,241.0/255))
        ]))
        t1 = Paragraph("CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA<br/>Y III DE COMUNIDADES INDÍGENAS",h_sub_tile)
        t1_sub = Paragraph("<strong>LISTADO DE VIVIENDAS DEL AREA DE EMPADRONAMIENTO URBANO</strong>", h_sub_tile_2)
        #fichero_imagen_inei = 'Reporte/Img/inei.png'
        #imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei), width=50, height=50)
        #P2 = Paragraph('', styleBH)
        #fichero_imagen = 'Reporte/Img/escudo.png'
        #imagen_logo = Image(os.path.realpath(fichero_imagen), width=50, height=50)
        #t1_croq = Paragraph("<strong>CROQUIS DEL ÁREA DE EMPADRONAMIENTO URBANO</strong>", h_sub_tile_2)
        # t = Table(
        #     data=[
        #         # ['', t1, ''],
        #         [[imagen_logo, P2], t1, [imagen_logo_inei, P2]],
        #         ['', t1_croq, '']
        #     ],
        #     colWidths=[2 * cm, 14 * cm, 2 * cm],
        #     style=[
        #         ('GRID', (1, 1), (-2, -2), 1, colors.white),
        #         # ('SPAN', (0, 1), (2, 1)),
        #         # ('BOX', (0, 0), (1, -1), 2, colors.black),
        #         # ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
        #         # ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
        #         # ('BACKGROUND', (0, 0), (0, 1), colors.pink),
        #         # ('BACKGROUND', (1, 1), (1, 2), colors.lavender),
        #         # ('BACKGROUND', (2, 2), (2, 3), colors.orange),
        #         # ('BOX', (0, 0), (-1, -1), 2, colors.black),
        #         ('GRID', (0, 0), (-1, -1), 0.5, colors.white),
        #         # ('VALIGN', (3, 0), (3, 0), 'BOTTOM'),
        #         # ('BACKGROUND', (3, 0), (3, 0), colors.limegreen),
        #         # ('BACKGROUND', (3, 1), (3, 1), colors.khaki),
        #         # ('ALIGN', (3, 1), (3, 1), 'CENTER'),
        #         # ('BACKGROUND', (3, 2), (3, 2), colors.beige),
        #         # ('ALIGN', (3, 2), (3, 2), 'LEFT'),
        #     ]
        # )
        obs_data = [
            [Paragraph(e, h3) for e in ["<strong>Viv Nº</strong>",
                                        "<strong>Mz Nº</strong>",
                                        "<strong>Or Reg</strong>",
                                        "<strong>Frent. Nº</strong>",
                                        "<strong>DIRECCION DE LA VIVIENDA</strong>",
                                        "", "", "", "", "", "", "", "",
                                        "<strong>Nombres y Apellidos del JEFE DEL HOGAR</strong>"]],
            [Paragraph(e, h3) for e in ["", "", "", "",
                                        "<strong>Tipo de Via</strong>",
                                        "<strong>Nombre de Via</strong>",
                                        "<strong>Nº de Puerta</strong>",
                                        "<strong>Block</strong>",
                                        "<strong>Man-<br/>zana Nº</strong>",
                                        "<strong>Lote Nº</strong>",
                                        "<strong>Piso Nº</strong>",
                                        "<strong>Inter. Nº</strong>",
                                        "<strong>Km. Nº</strong>",
                                        ""]],
            [Paragraph(e, h3) for e in ["<strong>(1)</strong>",
                                        "<strong>(2)</strong>",
                                        "<strong>(3)</strong>",
                                        "<strong>(4)</strong>",
                                        "<strong>(5)</strong>",
                                        "<strong>(6)</strong>",
                                        "<strong>(7)</strong>",
                                        "<strong>(8)</strong>",
                                        "<strong>(9)</strong>",
                                        "<strong>(10)</strong>",
                                        "<strong>(11)</strong>",
                                        "<strong>(12)</strong>",
                                        "<strong>(13)</strong>",
                                        "<strong>(14)</strong>"]],
         ]
        c = Table(obs_data,
                  colWidths=[0.8 * cm, 0.9 * cm, 1 * cm, 1.2 * cm, 1.2 * cm, 2.5 * cm, 1.2 * cm, 1.1 * cm, 1 * cm, 1 * cm,
                             1 * cm, 1.1 * cm, 0.9 * cm, 4.9 * cm])
        c.setStyle(TableStyle(
            [
                ('GRID', (1, 1), (-2, -2), 1, colors.black),
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
                # ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('FONTSIZE', (0, 0), (-1, -1), 7),
                ('BACKGROUND', (0, 0), (-1, 0), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('BACKGROUND', (0, 0), (-1, 1), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
                ('SPAN', (4, 0), (12, 0)),
                ('SPAN', (0, 0), (0, 1)),
                ('SPAN', (1, 0), (1, 1)),
                ('SPAN', (2, 0), (2, 1)),
                ('SPAN', (3, 0), (3, 1)),
                ('SPAN', (13, 0), (13, 1)),
                ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
                ('BACKGROUND', (0, 0), (13, 2), colors.Color(219.0 / 255, 229.0 / 255, 241.0 / 255)),
            ]
        ))
        # viviendas = ViviendaUrbana.objects.filter(ubigeo=distrito.ubigeo, zona=aeu.zona, aeu_final=aeu.aeu_final).order_by('manzana','id_reg_or')
        # viviendas = ViviendaUrbana.objects.filter(
        #     Q(ubigeo=distrito.ubigeo), Q(zona=aeu.zona), Q(aeu_final=aeu.aeu_final)
        #     # Q(ubigeo='020601'), Q(zona='001'), Q(aeu_final='001')
        # ).order_by('ubigeo', 'zona', 'manzana', 'id_reg_or', 'uso_local')
        # vivi = ViviendaUrbana.objects.get(ubigeo=distrito.ubigeo, zona=aeu.zona,).values('id_reg_or', flat=True).distinct().order_by('manzana')
        # for viv in ViviendaUrbana.objects.values('or_viv_aeu').filter(
        #        Q(ubigeo=distrito.ubigeo), Q(zona= aeu.zona), Q(aeu_final= aeu.aeu_final)
        # ).distinct().order_by('or_viv_aeu'):
        i=0
        equi_pta = [[1, 'PF de:'], [2, 'PG de:'], [3, 'PB de:'], [4, 'PC de:'], [5, 'Frente, pared corrida'], [6, 'Frente sin construir'], [7, 'Otro'], [8, 'Sin Edificación']]
        # Bloque Croquis
        data_croq = [
            ['', '', '', '', '', Paragraph('<strong>Doc. CPV</strong>', h4)],
            [Paragraph('<strong>A. UBICACION GEOGRAFICA</strong>', h1), '', '', '',
             Paragraph('<strong>B. UBICACION CENSAL</strong>', h1), ''],
            [Paragraph('<strong>DEPARTAMENTO</strong>', h1),Paragraph(str(aeu.ccdd), h1),
             Paragraph(str(aeu.departamento), h1), '',
             Paragraph('<strong>ZONA Nº</strong>', h1),Paragraph(aeu.zona_convert, h1)],
            [Paragraph('<strong>PROVINCIA</strong>', h1), Paragraph(aeu.ccpp, h1),
             Paragraph(str(aeu.provincia).decode('latin-1'), h1), '', Paragraph(str('<strong>SECCION Nº</strong>'), h1), aeu.seccion],
            [Paragraph('<strong>DISTRITO</strong>', h1), Paragraph(aeu.ccdi, h1), Paragraph(aeu.distrito, h1),
             '', Paragraph('<strong>A.E.U. Nº</strong>', h1), aeu.aeu_final],
            [Paragraph('<strong>CENTRO POBLADO</strong>', h1), Paragraph(aeu.nomccpp, h1), '', '', '', ''],
            [Paragraph('<strong>CATEGORIA DEL<br/>CENTRO POBLADO</strong>', h1), Paragraph('CIUDAD', h1), '', '',
             Paragraph('<strong>TOTAL DE VIVIENDAS DEL A.E.U.</strong>', h1),Paragraph(str(int(aeu.cant_viv)), h1)],
        ]
        tables_croq = Table(data_croq, colWidths=[3.7 * cm, 1 * cm, 8.3 * cm, 0.3 * cm, 4.7 * cm, 1 * cm])
        tables_croq.setStyle(TableStyle([
            ('TEXTCOLOR', (0, 0), (5, 0), colors.black),
            ('ALIGN', (4, 0), (5, 0), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('ALIGN', (1, 2), (1, 4), 'CENTER'),
            ('GRID', (0, 1), (2, 6), 1, colors.black),
            ('GRID', (4, 1), (5, 4), 1, colors.black),
            ('GRID', (-2, -1), (-1, -1), 1, colors.black),
            ('SPAN', (0, 1), (2, 1)),
            ('SPAN', (4, 1), (5, 1)),
            ('SPAN', (1, 5), (2, 5)),
            ('SPAN', (1, 6), (2, 6)),
            ('BACKGROUND', (4, 1), (5, 5), colors.white),
            ('BACKGROUND', (0, 1), (-1, 1), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (0, 1), (0, 6), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 1), (4, 4), colors.Color(219.0/255,229.0/255,241.0/255)),
            ('BACKGROUND', (4, 6), (4, 6), colors.Color(219.0/255,229.0/255,241.0/255))
        ]))
        fichero_imagen_inei = 'Reporte/Img/inei.png'
        imagen_logo_inei = Image(os.path.realpath(fichero_imagen_inei), width=50, height=40)
        P2 = Paragraph('', styleBH)
        fichero_imagen = 'Reporte/Img/escudo.png'
        imagen_logo = Image(os.path.realpath(fichero_imagen), width=50, height=50)
        # t = Table(
        #     data=[
        #         [[imagen_logo, P2], t1, [imagen_logo_inei, P2]],
        #         ['', t1_croq, '']
        #     ],
        #     colWidths=[2 * cm, 14 * cm, 2 * cm],
        #     style=[
        #         ('GRID', (1, 1), (-2, -2), 1, colors.white),
        #         ('GRID', (0, 0), (-1, -1), 0.5, colors.white),
        #     ]
        # )
        t_croq = Table(
            data=[
                [[imagen_logo, P2], t1, [imagen_logo_inei, P2]],
                ['',t1_sub, '']
            ],
            colWidths=[2 * cm, 14 * cm, 2 * cm],
            style=[
                ('GRID', (1, 1), (-2, -2), 1, colors.white),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.white),
            ]
        )
        # story.append(t)
        # story.append(Spacer(0, 1 * mm))
        # story.append(tables)
        # story.append(Spacer(0, 1 * mm))
        # viv_urb = ViviendaUrbana.objects.filter(Q(ubigeo=distrito.ubigeo), Q(zona=aeu.zona),Q(aeu_final=aeu.aeu_final)).order_by('or_viv_aeu')
        fichero_imagen = 'Reporte/Croquis/Zona' + ubigeo + '00100' + '/Croquis' + ubigeo + '00100' + str(aeut) + '.png'
        imagen_croquis = Image(os.path.realpath(fichero_imagen), width=18.8 * cm, height=18 * cm)
        # data_img = [
        #     [Paragraph(e, h3) for e in ["<strong>Imagen de Croquis</strong>"]],
        # ]
        # croq = Table(
        #     data=[
        #         [imagen_croquis]
        #     ],
        #     colWidths=[18.8 * cm],
        #     rowHeights=[18.8 * cm],
        #     style=[
        #         ('GRID', (1, 1), (-2, -2), 1, colors.black),
        #         ('ALIGN', (0, 0), (0, 0), 'CENTER'),
        #         ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        #     ]
        # )
        # story.append(croq)
        # story.append(Spacer(0, 1 * mm))
        # story.append(table_obs)
        # story.append(PageBreak())
        # story.append(table_bar)
        story.append(t_croq)
        story.append(Spacer(0, 2 * mm))
        story.append(tables)
        story.append(Spacer(0, 3 * mm))
        story.append(c)
        # viviendas = ViviendaUrbana.objects.filter(Q(ubigeo=distrito.ubigeo), Q(zona=aeu.zona), Q(aeu_final=aeu.aeu_final)
        #     # Q(ubigeo='020601'), Q(zona='001'), Q(aeu_final='001')
        # ).order_by('ubigeo', 'zona', 'manzana', 'id_reg_or', 'uso_local')[0:32]
        viviendas = v_ReporteViviendas_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonal), Q(aeu_final=aeut)).order_by('manzana', 'id_reg_or')[0:18]

        toti_viv = int(v_ReporteViviendas_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonal), Q(aeu_final=aeut)).count())
        for vivienda in viviendas:
            i=i+1
            pep = vivienda.p29_a
            for el in equi_pta:
                if (el[0] == pep):
                    pta_f = el[1]
            jefe_hogar = ""
            if vivienda.p29 == 1 or vivienda.p29 == 3:
                jefe_hogar = vivienda.p32
            # elif vivienda.id_viv.p29 == 2 or vivienda.id_viv.p29 == 5:
            elif vivienda.p29 == 5:
                if vivienda.p29_a in (1, 2, 3, 4):
                    jefe_hogar = str(pta_f) + "" + vivienda.p29_p
                elif vivienda.p29_a in (5, 6):
                    jefe_hogar = str(pta_f)
                elif vivienda.p29_a == 7:
                    jefe_hogar = vivienda.p29_o
                elif vivienda.p29_a == 8:
                    jefe_hogar = vivienda.p29_8_o
            elif vivienda.p29 == 2 or vivienda.p29 == 4:
                jefe_hogar = vivienda.p35
            else:
                print "No idea u.u"
            # Bloque Listado
            if(vivienda.p22_a==None):
                p22_a = ''
            else:
                p22_a = vivienda.p22_a
            if(vivienda.p22_b==None):
                p22_b = ''
            else:
                p22_b = vivienda.p22_b
            if(vivienda.p24==None):
                p24 = ''
            else:
                p24 = vivienda.p24
            if (vivienda.p25 == None):
                p25 = ''
            else:
                p25 = vivienda.p25
            if (vivienda.p26 == None):
                p26 = ''
            else:
                p26 = vivienda.p26

            if vivienda.or_viv_aeu == 0:
                id_reg_or = ''
            else:
                id_reg_or = vivienda.id_reg_or

            len_viviendap21 = len(vivienda.p21) - 1

            if ' ' not in vivienda.p21:
                p21 = vivienda.p21
            else:
                firstblank_viviendap21 = (vivienda.p21).index(' ')
                p21 = vivienda.p21[:firstblank_viviendap21] + '\n' + vivienda.p21[len_viviendap21 - firstblank_viviendap21:]

            table2 = [(vivienda.or_viv_aeu if not vivienda.or_viv_aeu == 0 or vivienda.or_viv_aeu == '0'  else '' ,
                       vivienda.manzana,
                       id_reg_or,
                       vivienda.frente_ord,
                       vivienda.p20_nombre if vivienda.p20 else "",
                       p21,
                       p22_a + p22_b,
                       vivienda.p23 if vivienda.p23 == 0 else "",
                       p24,
                       p25,
                       p26,
                       vivienda.p27_a if not vivienda.p27_a == None else '' + vivienda.p27_b if not vivienda.p27_b == None else '',
                       # 1 if a > b else -1
                       vivienda.p28 if vivienda.p28 == 0 else "",
                       jefe_hogar if not jefe_hogar == None else '')
                      ]
            u = Table(table2,
                      colWidths=[0.8 * cm, 0.9 * cm, 1 * cm, 1.2 * cm, 1.2 * cm, 2.5 * cm, 1.2 * cm, 1.1 * cm, 1 * cm, 1 * cm,
                                 1 * cm, 1.1 * cm, 0.9 * cm, 4.9 * cm],
                      rowHeights=[1 *cm])
            u.setStyle(TableStyle(
                [
                    ('GRID', (1, 1), (-2, -2), 1, colors.black),
                    ('GRID', (0, 0), (-1, -1), 1, colors.black),
                    ('GRID', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTSIZE', (0, 0), (13, 0), 7),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ]
            ))
            story.append(u)
        viviendas_second =v_ReporteViviendas_Tab.objects.filter(Q(ubigeo=ubigeo), Q(zona=zonal), Q(aeu_final=aeut)).order_by('manzana', 'id_reg_or')[18:]

        if toti_viv>19:
            story.append(c)
            for vivienda in viviendas_second:
                i = i + 1

                pep2 = vivienda.p29_a

                for el in equi_pta:
                    if (el[0] == pep2):
                        pta_f = el[1]

                jefe_hogar = ""
                if vivienda.p29 == 1 or vivienda.p29 == 3:
                    jefe_hogar = vivienda.p32
                elif vivienda.p29 == 5:
                    if vivienda.p29_a in (1, 2, 3, 4):
                        jefe_hogar = str(pta_f) + "" + vivienda.p29_p
                    elif vivienda.p29_a in (5, 6):
                        jefe_hogar = str(pta_f)
                    elif vivienda.p29_a == 7:
                        jefe_hogar = vivienda.p29_o
                    elif vivienda.p29_a == 8:
                        jefe_hogar = vivienda.p29_8_o
                elif vivienda.p29 == 2 or vivienda.p29 == 4:
                    jefe_hogar = vivienda.p35
                else:
                    print "No idea u.u"
                # Bloque Listado
                if (vivienda.p22_a == None):
                    p22_a = ''
                else:
                    p22_a = vivienda.p22_a
                if (vivienda.p22_b == None):
                    p22_b = ''
                else:
                    p22_b = vivienda.p22_b
                if (vivienda.p24 == None):
                    p24 = ''
                else:
                    p24 = vivienda.p24
                if (vivienda.p25 == None):
                    p25 = ''
                else:
                    p25 = vivienda.p25
                if (vivienda.p26 == None):
                    p26 = ''
                else:
                    p26 = vivienda.p26

                if vivienda.or_viv_aeu == 0:
                    id_reg_or = ''
                else:
                    id_reg_or = vivienda.id_reg_or
                table2 = [(vivienda.or_viv_aeu if not vivienda.or_viv_aeu == 0 or vivienda.or_viv_aeu == '0'  else '' ,
                       vivienda.manzana,
                       id_reg_or,
                       vivienda.frente_ord,
                       vivienda.p20_nombre if vivienda.p20 else "",
                       vivienda.p21,
                       p22_a + p22_b,
                       vivienda.p23 if vivienda.p23 == 0 else "",
                       p24,
                       p25,
                       p26,
                       vivienda.p27_a if not vivienda.p27_a == None else '' + vivienda.p27_b if not vivienda.p27_b == None else '',
                       vivienda.p28 if vivienda.p28 == 0 else "",
                       jefe_hogar if not jefe_hogar == None else '')
                      ]
                u_second = Table(table2,
                          colWidths=[0.8 * cm, 0.9 * cm, 1 * cm, 1.2 * cm, 1.2 * cm, 2.5 * cm, 1.2 * cm, 1.1 * cm, 1 * cm, 1 * cm,
                                     1 * cm, 1.1 * cm, 0.9 * cm, 4.9 * cm],
                          rowHeights=[1 * cm])

                u_second.setStyle(TableStyle(
                    [
                        ('GRID', (1, 1), (-2, -2), 1, colors.black),
                        ('GRID', (0, 0), (-1, -1), 1, colors.black),
                        ('GRID', (0, 0), (-1, -1), 1, colors.black),
                        ('FONTSIZE', (0, 0), (13, 0), 7),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ]
                ))
                story.append(u_second)
        # if(PageBreak()):
        #     story.append(Spacer(0, 22 * cm))
        #     story.append(table_obs)
        #     story.append(Spacer(0, 1 * mm))
        #     story.append(table_empa_cuerp)
        # else:
        story.append(Spacer(0, 1 * cm))
        #story.append(table_obs)
        story.append(Spacer(0, 1 * mm))
        story.append(table_empa_cuerp)
        # Z_obs = Paragraph("<strong>OBSERVACIONES: ...................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    "..........................................................................................."
        #                    ".............................1</strong>", h_obser)
        #
        # table_obser = Table(
        #         data=[
        #             [Z_obs]
        #         ],
        #         colWidths=[18.3 * cm],
        #         style=[
        #             ('GRID', (0, 0), (-1, -1), 1, colors.black)
        #         ]
        # )
        # if (PageBreak()):
        # story.append(Spacer(0, 1.3 * cm))
        # story.append(Spacer(0, 1 * mm))
        # story.append(table_empa_cuerp)
        story.append(Spacer(0, 1 * mm))
        story.append(p_page)
        # else:
        #     story.append(Spacer(0, 21 * cm))
        #     story.append(table_obs)
        #     story.append(Spacer(0, 1 * mm))
        #     sory.append(table_empa_cuerp)
        #     story.append(Spacer(0, 1 * mm))
        #     story.append(p_page)

    doc2.build(story)
    doc.build(story)
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #53
0
def sanofi():
    doc = SimpleDocTemplate('test.pdf', pagasize=A4)
    story = Story()

    some_space = Spacer(1, 10)

    data_header = {
        '_title': 'Titolo centrale',
        '_session': 'Sessione di prova'
    }
    h = HeaderView(**data_header)

    rendered_fields = h.render()
    story.add(rendered_fields)

    story.add(some_space)

    data_session = {
        "_session_type": "Session One",
        "_s1": "Bullet1",
        "_s2": "Bullet2",
        "_s3": "Bullet3",
        "_session_title": "This is a session title",
        "_session_id": "1234 session",
        "_version": "1.0",
        "_language": "English",
        "_start_date": "01/01/2017",
        "_end_date": "01/07/2017",
        "_duration": "1h20m"
    }

    s = SessionView(**data_session)
    rendered_fields = s.render()
    story.add(rendered_fields)

    story.add(some_space)

    data_student = {
        "_course_title": "This is a course title",
        "_start_date": "01/01/2017",
        "_start_time": "10:00",
        "_end_date": "01/01/2017",
        "_end_time": "11:00"
    }

    u = StudentView(**data_student)
    students_data = [
        ['Mario', 'Rossi', '', '', '', ''],
        ['Marco', 'Bianchi', '', '', '', ''],
        ['Giuseppe', 'Verdi', '', '', '', ''],
        ['', '', '', '', '', ''],
    ]

    rendered_fields = u.render(students_data)
    story.add(rendered_fields)

    story.add(some_space)

    data_instructor = {
        "_instructor": "Mario Neri",
        "_internal_bullet": "Internal Instructor",
        "_external_bullet": "External Instructor",
        "_instructor_infos": "bla bla bla ..."
    }

    i = InstructorView(**data_instructor)
    rendered_fields = i.render()
    story.add(rendered_fields)

    doc.build(story.get())
Beispiel #54
0
    def print_kulukorvaukset(self):
        """Generates a pdf file from submitted form data."""
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
                                rightMargin=72,
                                leftMargin=72,
                                topMargin=18,
                                bottomMargin=18)

        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name="Justify", alignment=TA_JUSTIFY))
        styles.add(ParagraphStyle(name="Center", alignment=TA_CENTER))

        # General data
        formatted_time = format(timezone.now(), "D, j M Y H:i:s")
        model_perustiedot = self.model_perustiedot

        # Extract data from model
        created_by = model_perustiedot.created_by
        email = model_perustiedot.email
        phone_number = model_perustiedot.phone_number
        bank_number = model_perustiedot.bank_number
        bic = model_perustiedot.get_bic_display()
        additional_info = model_perustiedot.additional_info

        # Container to hold table elements
        elements = []

        # Setup table data
        t_basic_info = [
            [_("Name"), created_by],
            [_("Email"), email],
            [_("Phone number"), phone_number],
            [_("Account number (IBAN)"), bank_number],
            ["BIC", bic],
            [_("Additional info"), "\n".join(wrap(additional_info, 80))],
        ]

        t_kulu = []
        # Loop Kulukorvaus models and append to t_kulu
        for model in self.models_kulukorvaukset:
            fields = model._meta.get_fields()
            for field in fields:
                if field.name not in ["id", "created_at", "info"]:
                    verbose_name = field.verbose_name
                    value = getattr(model, field.name)
                    if type(value) == str:
                        value = "\n".join(wrap(value, 80))
                    if field.name == "receipt":
                        receipt = self.handle_receipt(value.file.read())
                        value = receipt
                    t_kulu.append([verbose_name, value])

        # Styling for the table
        t_style = [
            ("GRID", (0, 0), (-1, -1), 0.01 * cm, (0, 0, 0)),
            ("FONT", (0, 0), (-1, -1), "Raleway Medium"),
            ("TEXTCOLOR", (0, 0), (0, -1), colors.gray),
            ("VALIGN", (0, 0), (0, -1), "TOP"),
        ]

        Img = self.get_image(
            staticfiles_storage.open(
                "images/logos/prodeko-logo-text-blue.png"),
            width=10 * cm,
        )
        s05cm = Spacer(width=0, height=0.5 * cm)
        ptime = f"<font name='Raleway Medium' size=8>{formatted_time}</font>"
        PTIME = Paragraph(ptime, styles["Center"])

        text_info = _(
            "Your reimbursement claim has been received. The claim will be processed in the next Prodeko board meeting."
        )
        text_errors = _(
            "If you notice any errors in the information below, contact Prodeko's treasurer immediately at [email protected]."
        )

        ptext = f"""<font name='Raleway Medium' size=10>{text_info}
        <br />
        <br />
        {text_errors}
        </font>
        """

        # Setup paragraph of text before the table as well as the table
        P1 = Paragraph(ptext, styles["Normal"])
        T_basic = Table(t_basic_info)
        T_kulu = Table(t_kulu)
        T_basic.setStyle(TableStyle(t_style))
        T_kulu.setStyle(TableStyle(t_style))

        # Append pdf elements (time, image, spacers, paragraph, table)
        # to the container
        elements.append(PTIME)
        elements.append(Img)
        elements.append(s05cm)
        elements.append(HRFlowable(width=20 * cm))
        elements.append(s05cm)
        elements.append(P1)
        elements.append(s05cm)
        elements.append(T_basic)
        elements.append(s05cm)
        elements.append(T_kulu)

        doc.build(elements)

        # Get the value of the BytesIO buffer
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
Beispiel #55
0
def incidencia_justificar_estudiante_incidencia(request, id_estudiante,
                                                id_incidencia):
    now = datetime.datetime.now()
    if (now.weekday() == 0 or now.weekday() == 1):
        dias = datetime.timedelta(days=4)
    elif (now.weekday() == 6):
        dias = datetime.timedelta(days=3)
    else:
        dias = datetime.timedelta(days=2)

    incidencia = get_object_or_404(Incidencia,
                                   fecha__range=(now - dias, now),
                                   id=id_incidencia,
                                   estado=False)
    estudiante = incidencia.asignaturaestudiante.estudiante
    asignatura = incidencia.asignaturaestudiante.asignatura.asignatura
    # horario = Horario.objects.get(cursoasignatura=incidencia.asignaturaestudiante.asignatura, dia=incidencia.fecha.weekday())

    if request.method == 'POST':
        form = JustificarForm(request.POST, instance=incidencia)
        if form.is_valid():
            incidencia = form.save(commit=False)
            incidencia.estado = True
            incidencia.save()

            estiloHoja = getSampleStyleSheet()
            cabecera = estiloHoja['Title']
            cabecera.pageBreakBefore = 0
            cabecera.keepWithNext = 0
            cabecera.textColor = colors.red
            estilo = estiloHoja['BodyText']

            salto = Spacer(0, 10)

            pagina = []

            pagina.append(salto)
            pagina.append(
                Paragraph("Unidad Educativa Particular Emanuel", cabecera))

            cabecera.textColor = colors.black
            pagina.append(Paragraph("" + "Justificación", cabecera))
            pagina.append(salto)
            pagina.append(salto)

            pagina.append(
                Paragraph(
                    "Estudiante: " + estudiante.nombre + " " +
                    estudiante.apellido, estilo))
            pagina.append(
                Paragraph("Fecha: " + incidencia.fecha.strftime('%m/%d/%Y'),
                          estilo))
            pagina.append(
                Paragraph("Hora: " + incidencia.hora.get_hora_display(),
                          estilo))
            pagina.append(Paragraph("Asignatura: " + asignatura.nombre,
                                    estilo))

            estilo.fontName = tt2ps('Times-Roman', 1, 0)

            pagina.append(Paragraph("" + "Justificación: ", estilo))
            estilo.fontName = tt2ps('Times-Roman', 0, 0)
            pagina.append(Paragraph("" + incidencia.justificacion, estilo))
            pagina.append(salto)
            pagina.append(salto)
            pagina.append(salto)
            pagina.append(salto)

            pagina.append(
                Paragraph("" + estudiante.representante.nombres_completos(),
                          estilo))
            estilo.fontName = tt2ps('Times-Roman', 1, 0)
            pagina.append(Paragraph("REPRESENTANTE", estilo))
            pagina.append(salto)
            pagina.append(salto)
            pagina.append(salto)
            estilo.fontName = tt2ps('Times-Roman', 0, 0)
            pagina.append(
                Paragraph(incidencia.revisado_por.user.get_full_name(),
                          estilo))
            estilo.fontName = tt2ps('Times-Roman', 1, 0)
            pagina.append(Paragraph("INSPECTOR", estilo))
            nombreArchivo = "justificante-" + incidencia.fecha.strftime(
                '%m-%d-%Y') + ".pdf"
            documento = SimpleDocTemplate(nombreArchivo,
                                          pagesize=A6,
                                          showBoundary=1,
                                          displayDocTitle=1,
                                          leftMargin=2,
                                          rightMargin=2,
                                          topMargin=2,
                                          bottomMargin=2,
                                          title="Justificante")

            documento.build(pagina)

            salida = open(nombreArchivo)
            response = HttpResponse(salida, content_type='application/pdf')
            response[
                'Content-Disposition'] = 'inline; filename=' + nombreArchivo
            return response

        # return HttpResponseRedirect(reverse('incidencia_justificar_estudiante', args=(estudiante.id,))+"?mensaje=correcto")
    else:
        form = JustificarForm(instance=incidencia)

    return render(request,
                  'incidencia/justificar/justificar.html', {
                      'form': form,
                      'estudiante': estudiante,
                      'asignatura': asignatura,
                      'incidencia': incidencia
                  },
                  context_instance=RequestContext(request))
Beispiel #56
0
def Assemble_PDF(data_plots, posterior_plots, heatmaps, annotation_plot, output):
    DPI = 100
    
    # save posterior plot
    posterior_plots.set_size_inches(8, 4) 
    posterior_plots.savefig('posterior_plots.png', format='png', dpi=DPI, transparent=True, bbox_inches='tight')

    # save annotation plots
    for i,plot in enumerate(annotation_plot):
        plot.set_size_inches(6.9, 0.2)
        plot.savefig('annotation_plot'+str(i)+'.png', format='png', dpi=DPI, transparent=True, bbox_inches='tight')

    # save data plot
    for i,plot in enumerate(data_plots):
        plot[0].set_size_inches(8, 4) 
        plot[0].savefig('value_plots'+str(i)+'.png', format='png', dpi=DPI, transparent=True, bbox_inches='tight')

    # save heatmap
    for i,heatmap in enumerate(heatmaps):
        plot = heatmap[0]
        plot.set_size_inches(np.sqrt(32), np.sqrt(32)) 
        plot.savefig('heatmap'+str(i)+'.png', format='png', dpi=DPI, transparent=True, bbox_inches='tight')

    # colorbar
    colorbar_h = heatmap[1]
    colorbar_h.set_size_inches(4, .5)
    colorbar_h.savefig('colorbar_h.png', format='png', dpi=DPI, transparent=True, bbox_inches='tight')

    colorbar = data_plots[0][1]
    colorbar.set_size_inches(4, .5)
    colorbar.savefig('colorbar.png', format='png', dpi=DPI, transparent=True, bbox_inches='tight')

    # start pdf doc
    doc = SimpleDocTemplate(output+".pdf", pagesize=(10*inch,18*inch+0.5*len(annotation_plot)*inch), rightMargin=0, leftMargin=0, topMargin=0, bottomMargin=0)

    # list for figures
    Story = []

    # add posterior plot
    Story.append(Image('posterior_plots.png'))

    # loop through annotations adding an indent to each one
    for i in range(0,len(annotation_plot)):
        Story.append(Indenter(left=.6*inch))
        Story.append(Image('annotation_plot'+str(i)+'.png'))

    Story.append(Indenter(right=.6*inch))

    # add zscore/pvalue plots
    Story.extend([Image('value_plots'+str(i)+'.png') for i in range(0,len(data_plots))])

    # add colorbar
    Story.append(Image('colorbar_h.png'))

    # add ld plot
    for i in range(0,len(annotation_plot)):
        Story.append(Indenter(left=6.9*inch))
        Story.append(RotatedImage('heatmap'+str(i)+'.png'))

    Story.append(Indenter(right=6.9*inch))

    # add other colorbar
    Story.append(Image('colorbar.png'))

    # build image and save
    doc.build(Story)
class ReportAdHoc(object):
    def __init__(self, title, sub_title, detail, **kwargs):
        self.name = kwargs.get('name')
        self.receiver = kwargs.get('receiver')
        self.sender = kwargs.get('sender')
        self.equipment = kwargs.get('equipment')
        self.add_equipment = kwargs.get('add_equipment')

        self.title = title
        self.sub_title = sub_title
        self.detail = detail
        self.buffer = BytesIO()
        self.doc = SimpleDocTemplate(self.buffer, pagesize=A4, title='Report')
        self.layout = [Spacer(1, 0.5 * inch)]
        self.style = getSampleStyleSheet()
        self.image_path = path.join(settings.STATIC_ROOT, 'app', 'images', '')

        self.style.add(
            ParagraphStyle(name='sub_title',
                           parent=self.style['Normal'],
                           fontSize=12,
                           leading=16))

        self.style.add(
            ParagraphStyle(name='detail',
                           parent=self.style['Normal'],
                           leading=24))

        self.style.add(
            ParagraphStyle(name='equipment',
                           parent=self.style['Normal'],
                           fontSize=11,
                           leading=14))

        self.style.add(
            ParagraphStyle(name='signature_left',
                           parent=self.style['Normal'],
                           alignment=TA_LEFT,
                           fontSize=12))

        self.style.add(
            ParagraphStyle(name='signature_right',
                           parent=self.style['Normal'],
                           alignment=TA_RIGHT,
                           fontSize=12))

        self.style.add(
            ParagraphStyle(name='grow',
                           parent=self.style['Normal'],
                           alignment=TA_RIGHT,
                           fontSize=15))

    def restore_default_canvas(self, canvas):
        canvas.restoreState()
        canvas.saveState()

    def mix_canvas_paragraph(self, canvas, paragraph, **kwargs):
        doc = kwargs.get('doc', self.doc)
        position = kwargs.get('position')
        horizontal = doc.leftMargin
        paragraph.wrap(doc.width, doc.bottomMargin)
        if isinstance(position, tuple):
            horizontal = position[0]
            position = position[1]
        paragraph.drawOn(canvas, horizontal, position)

    def set_canvas_dynamic(self, top):
        len_detail = len(self.detail)
        if len_detail == 10:
            top = top - (len_detail / 50)
        elif len_detail > 10:
            top = top - (len_detail / 25)
        return top

    def create_header(self, canvas, doc):
        w, h = doc.pagesize
        width = 100
        height = 100
        canvas.saveState()
        canvas.drawImage(path.join('/' + self.image_path, 'NufarmLogo2.jpg'),
                         w - 20 - width,
                         h - 20 - height,
                         width=width,
                         height=height)
        canvas.restoreState()

    def create_title(self):
        self.layout.append(Spacer(0, 15))
        self.layout.append(Paragraph(self.title, self.style['Title']))

    def create_sub_title(self):
        self.layout.append(Paragraph(self.sub_title, self.style['sub_title']))

    def create_detail(self):
        self.layout.append(Spacer(0, 20))
        detail = Table([(key, ': {value}'.format(value=value))
                        for key, value in self.detail.items()],
                       hAlign='LEFT')
        print(detail.wrap(0, 0))
        self.layout.append(detail)

    def create_equipment(self):
        self.layout.append(Spacer(0, 20))
        self.layout.append(
            Paragraph('<b>Perlengkapan standar :</b>',
                      self.style['equipment']))
        equipment_list = self.equipment
        for equipment in equipment_list:
            self.layout.append(
                Paragraph(equipment,
                          self.style['equipment'],
                          bulletText=u'\u27a4'))

    def create_add_equipment(self):
        self.layout.append(Spacer(0, 20))
        self.layout.append(
            Paragraph('<b>Perlengkapan tambahan :</b>',
                      self.style['equipment']))
        add_equipment_list = self.add_equipment
        for add_equipment in add_equipment_list:
            self.layout.append(
                Paragraph(add_equipment,
                          self.style['equipment'],
                          bulletText=u'\u27a4'))

    def create_signature(self, canvas, doc, **kwargs):
        receiver = "Yang Menerima,"
        receiver = Paragraph(receiver, self.style['signature_left'])
        self.mix_canvas_paragraph(canvas=canvas,
                                  paragraph=receiver,
                                  position=3 * inch)

        receiver_name = kwargs.get('receiver_name')
        receiver_name = Paragraph(receiver_name, self.style['signature_left'])
        self.mix_canvas_paragraph(canvas=canvas,
                                  paragraph=receiver_name,
                                  position=1.8 * inch)

        sender = "Yang Menyerahkan,"
        sender = Paragraph(sender, self.style['signature_right'])
        self.mix_canvas_paragraph(canvas=canvas,
                                  paragraph=sender,
                                  position=3 * inch)

        sender_name = kwargs.get('sender_name')
        sender_name = Paragraph(sender_name, self.style['signature_right'])
        self.mix_canvas_paragraph(canvas=canvas,
                                  paragraph=sender_name,
                                  position=1.8 * inch)

    def create_footer(self, canvas, doc):
        canvas.saveState()
        text = "Demikian Berita Acara ini dibuat dengan sebenarnya"
        top = self.set_canvas_dynamic(4.1)
        canvas.drawString(inch, top * inch, text)
        tgl = "Jakarta, 14 Desember 2016"
        canvas.setFont('Helvetica-Bold', 13)
        top = self.set_canvas_dynamic(3.8)
        canvas.drawString(inch, top * inch, tgl)
        self.create_signature(
            canvas=canvas,
            doc=doc,
            receiver_name='<b>{receiver}</b>'.format(receiver=self.receiver),
            sender_name='<b>{sender}</b>'.format(sender=self.sender))
        grow = "<b><font color='green'>Grow a better tomorrow.</font></b>"
        grow = Paragraph(grow, self.style['grow'])
        self.mix_canvas_paragraph(canvas=canvas,
                                  paragraph=grow,
                                  position=((1.5 * inch), (0.5 * inch)))
        canvas.restoreState()

    def first_page(self, canvas, doc):
        self.create_header(canvas, doc)
        if doc.page > 1:
            return
        return self.create_footer(canvas, doc)

    def last_page(self, canvas, doc):
        if doc.page > 1:
            return self.create_footer(canvas, doc)
        return self.create_header(canvas, doc)

    def write_pdf_view(self):
        self.create_title()
        self.create_sub_title()
        self.create_detail()

        if self.equipment:
            self.create_equipment()

        if self.add_equipment:
            self.create_add_equipment()

        self.doc.build(self.layout,
                       onFirstPage=self.first_page,
                       onLaterPages=self.last_page)

        response = HttpResponse(content_type='application/pdf')
        response[
            'Content-Disposition'] = 'inline; filename="{file_name}.pdf"'.format(
                file_name=self.name)
        response.write(self.buffer.getvalue())
        self.buffer.close()
        return response
Beispiel #58
0
def incidencia_justificar_estudiante_fecha(request, id_estudiante):
    # incidencia = get_object_or_404(Incidencia, fecha__range=(now-dias, now), id=id_incidencia, estado=False)
    estudiante = get_object_or_404(Estudiante, id=id_estudiante)
    inspector = Inspector.objects.get(user=request.user)
    # asignatura = incidencia.asignaturaestudiante.asignatura.asignatura
    # horario = Horario.objects.get(cursoasignatura=incidencia.asignaturaestudiante.asignatura, dia=incidencia.fecha.weekday())
    if request.method == 'POST':
        form = JustificarFechaForm(request.POST)
        if form.is_valid():
            inicioString = request.POST.get('fecha_inicio')
            finString = request.POST.get('fecha_fin')
            justificacion = request.POST.get('justificacion')

            fechaInicio = datetime.datetime.strptime(inicioString,
                                                     '%Y-%m-%d').date()

            fechaFin = datetime.datetime.strptime(finString, '%Y-%m-%d').date()

            incidencias = Incidencia.objects.filter(fecha__in=(fechaInicio,
                                                               fechaFin),
                                                    estado=False)

            if not incidencias.exists():
                return render(request,
                              'incidencia/justificar/justificar_fecha.html', {
                                  'form': form,
                                  'estudiante': estudiante,
                                  'estado': False
                              },
                              context_instance=RequestContext(request))

            for incidencia in incidencias:
                incidencia.justificacion = justificacion
                incidencia.estado = True
                incidencia.revisado_por = inspector
                incidencia.save()

            estiloHoja = getSampleStyleSheet()
            cabecera = estiloHoja['Title']
            cabecera.pageBreakBefore = 0
            cabecera.keepWithNext = 0
            cabecera.textColor = colors.red
            estilo = estiloHoja['BodyText']

            salto = Spacer(0, 10)

            pagina = []

            pagina.append(salto)
            pagina.append(
                Paragraph("Unidad Educativa Particular Emanuel", cabecera))

            cabecera.textColor = colors.black
            pagina.append(Paragraph("" + "Justificación", cabecera))
            pagina.append(salto)
            pagina.append(salto)

            pagina.append(
                Paragraph(
                    "Estudiante: " + estudiante.nombre + " " +
                    estudiante.apellido, estilo))

            fecha1 = fechaInicio.strftime("%A %d de %B del %Y %Z")
            fecha2 = fechaFin.strftime("%A %d de %B del %Y %Z")

            pagina.append(Paragraph("Fecha de Inicio: " + fecha1, estilo))
            pagina.append(Paragraph("Fecha de Final: " + fecha2, estilo))

            estilo.fontName = tt2ps('Times-Roman', 1, 0)

            pagina.append(Paragraph("" + "Justificación: ", estilo))
            estilo.fontName = tt2ps('Times-Roman', 0, 0)
            pagina.append(Paragraph("" + justificacion, estilo))
            pagina.append(salto)
            pagina.append(salto)
            pagina.append(salto)
            pagina.append(salto)

            pagina.append(
                Paragraph("" + estudiante.representante.nombres_completos(),
                          estilo))
            estilo.fontName = tt2ps('Times-Roman', 1, 0)
            pagina.append(Paragraph("REPRESENTANTE", estilo))
            pagina.append(salto)
            pagina.append(salto)
            pagina.append(salto)
            estilo.fontName = tt2ps('Times-Roman', 0, 0)
            pagina.append(Paragraph(request.user.get_full_name(), estilo))
            estilo.fontName = tt2ps('Times-Roman', 1, 0)
            pagina.append(Paragraph("INSPECTOR", estilo))
            nombreArchivo = "justificante.pdf"
            documento = SimpleDocTemplate(nombreArchivo,
                                          pagesize=A6,
                                          showBoundary=1,
                                          displayDocTitle=1,
                                          leftMargin=2,
                                          rightMargin=2,
                                          topMargin=2,
                                          bottomMargin=2,
                                          title="Justificante")

            documento.build(pagina)

            salida = open(nombreArchivo)
            response = HttpResponse(salida, content_type='application/pdf')
            response[
                'Content-Disposition'] = 'inline; filename=' + nombreArchivo
            return response

        # return HttpResponseRedirect(reverse('incidencia_justificar_estudiante', args=(estudiante.id,))+"?mensaje=correcto")
    else:
        form = JustificarFechaForm()

    return render(request,
                  'incidencia/justificar/justificar_fecha.html', {
                      'form': form,
                      'estudiante': estudiante,
                  },
                  context_instance=RequestContext(request))
Beispiel #59
0
from reportlab.platypus import (Paragraph, SimpleDocTemplate, Spacer)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter

from custom_graph.CanvasFigure import CanvasFigure
from custom_graph import graph_wrappers as graphP
from data import generator
from datetime import datetime

doc = SimpleDocTemplate("ignore/custom_graph.pdf", pagesize=letter)
style = getSampleStyleSheet()
story = []
p = Paragraph("This is a table. " * 10, style['Normal'])
story.append(p)

start = datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0).timestamp()
end = datetime(year=2000, month=1, day=1, hour=23, minute=59, second=59, microsecond=999999).timestamp()
data = generator.GenerateData(start, end)

refGraph = CanvasFigure(data, width=500, height=250)
graph = graphP.GetBloodGlucoseGraph(data, (500, 250), boundary=True)

# graph = graphP.GetRangeBarGraph(data, (500, 250), boundary=True)

story.append(refGraph)
story.append(graph)
story.append(p)
s = Spacer(width=0, height=60)
doc.build(story)
Beispiel #60
0
def createProgressReport(contracts,user):
    """ Basic Setup for Report Lab   """
    pdf_buffer = BytesIO()
    doc = SimpleDocTemplate(pdf_buffer)
    doc.pagesize =landscape(A4)
    flowables = []#overall flowables
    structural_summary=[]#for structural summary
    contract_summary=[]
    sample_style_sheet = getSampleStyleSheet()
    #sample_style_sheet.list()
    """Creating Style for Paragraph  """
    custom_body_style = sample_style_sheet['Heading5']
    #custom_body_style.listAttrs()
    custom_body_style.spaceAfter=0
    custom_body_style.spaceBefore=0

    for contract in contracts:
        structures=Contract_Intervention.objects.filter(contract_id=contract)
        """Variable for Holding Total progress in  structure  """
        #mylist = ['', '', '', '', "Overall Progress",'','', '', '', '', '', '']
        contract_data=[]
        item_progress="itemized"+chr(10)+"progress"
        contract_heading=['sl','name','weight','progress',item_progress]
        contract_data.append(contract_heading)
        contract_sl=1
        contract_sum=0

        myheading2 = "Contract Name : " + contract.package_short_name
        myparagraph2 = Paragraph(myheading2, custom_body_style)
        myparagraph2.hAlign = 'LEFT'
        contract_summary.append(myparagraph2)
        for structure in structures:
            """ Structurl Progress Rreport      """
            contractName=""
            contract_row=[contract_sl,prepareMultiline(structure.dpp_intervention_id.name,25),structure.physical_weight,0,0]
            contract_sl +=1
            """ Adding Header Section For Report """
            myheading1 = "Haor Name : " + structure.dpp_intervention_id.haor_id.name
            myparagraph1 = Paragraph(myheading1, custom_body_style)
            myparagraph1.hAlign = 'LEFT'

            myheading3="Structure Name : "+structure.dpp_intervention_id.name
            myheading4="Reproting Date : "+"24/3/2019" # Latter A Proper Date Will be Created
            #mystr=contract.package_short_name+"/"+structure.dpp_intervention_id.name

            flowables.append(myparagraph1)

            flowables.append(myparagraph2)
            myparagraph3 = Paragraph(myheading3, custom_body_style)
            myparagraph1.hAlign = 'LEFT'
            flowables.append(myparagraph3)
            myparagraph4 = Paragraph(myheading4,  custom_body_style)
            myparagraph1.hAlign = 'LEFT'
            flowables.append(myparagraph4)
            flowables.append(Spacer(1, 0.25 * cm))
            """ Table Section of the report  """
            pitems=ProgressItem.objects.filter(intervention_id=structure)
            mydata=[]
            iprog="item"+chr(10)+ "progress"
            qua_exe="Quan"+chr(10)+"Executed"+chr(10)+"RPeriod"
            tableHeading=['Sl','Pre_date','curr_date','duration','Item Name','Unit','Est_Qua','weight','Prev_Qua','Qua_Curr', qua_exe,iprog]
            mydata.append(tableHeading)
            sl=1
            sum=0.0
            total_structural = ['', '', '', '', "Overall Progress", '', '', '', '', '', '', '']
            for pitem in pitems:
                iname=prepareMultiline(pitem.item_name,25)
                mylist=[sl,'','','',iname, pitem.unit,pitem.quantity,pitem.weight,'','','',0]
                mylist=calculateProgressQuantity(pitem,user,mylist)
                mydata.append(mylist)
                sl+=1
                sum+=float(mylist[11])
                print("total for={}".format(mylist[11]))
            total_structural[11]=sum
            mydata.append(total_structural)
            colwidth=[1.0*cm,1.8*cm,1.8*cm,1.8*cm,4.9*cm,2.0*cm,2.2*cm,2.2*cm,2.2*cm,2.0*cm,2.0*cm,2.0*cm]
            t = Table(mydata,repeatRows=1,colWidths=colwidth)
            t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),('BOX', (0,0), (-1,-1), 0.25, colors.black),]))
            t.hAlign = 'LEFT'
            #t.wrapOn()
            flowables.append(t)
            flowables.append(Spacer(1, 0.5* cm))
            contract_row[3]= total_structural[11]
            contract_row[4]=float(contract_row[3])*float(contract_row[2])
            contract_sum +=contract_row[4]
            contract_data.append(contract_row)
        total_contract=['',prepareMultiline('Overall physical Progress',60),'','',contract_sum ]
        contract_data.append(total_contract)
        contract_colwidth=[1.0*cm,12*cm,3*cm,3*cm,4*cm]
        t_contract=Table(contract_data,repeatRows=1,colWidths=contract_colwidth)
        t_contract.setStyle(TableStyle(
            [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ]))
        t_contract.hAlign='LEFT'
        contract_summary.append(t_contract)



    signature_table_data=[]
    #myheading1 = "This is a test paragraph"
    #myparagraph1 = Paragraph(myheading1, custom_body_style)
    for item in reversed(contract_summary):
        flowables.insert(0,item)
    #custom_body_style.listAttrs()
    #sample_style_sheet.list()



    """
    item_name = models.CharField(max_length=200, default="EW")
    unit = models.CharField(max_length=10)
    quantity = models.DecimalField(null=True, blank=True, decimal_places=3, max_digits=13)
    weight = models.DecimalField(null=True, blank=True, decimal_places=3, max_digits=13)
    startdate = models.DateField(default=timezone.now)
    finishdate = models.DateField(default=timezone.now)



    
    styles = getSampleStyleSheet()
    Story = [Spacer(1, 2 * inch)]
    style = styles["Normal"]
    for i in range(100):
        bogustext = ("This is Paragraph number %s.  " % i) * 20
        p = Paragraph(bogustext, style)
        Story.append(p)
        Story.append(Spacer(1, 0.2 * inch))
    """
    doc.build(flowables)

    pdf_value = pdf_buffer.getvalue()
    pdf_buffer.close()
    return pdf_value