Esempio n. 1
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()
Esempio n. 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
Esempio n. 3
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)
Esempio n. 4
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
Esempio n. 5
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)
Esempio n. 6
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
Esempio n. 7
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
Esempio n. 10
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
Esempio n. 11
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)
Esempio n. 12
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)
Esempio n. 13
0
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
Esempio n. 14
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)
Esempio n. 15
0
def main():
    '''
    run as a standalone, tablegen produces a fixed mockup named  
    operating_table_mockup.pdf        
    
    this mockup illustrates all the corner cases that events can fall into:
    events that start on the hour, multiple events within the same hour, 
    multiple events occuring at the same time, and events at the first and 
    last minute of the day. 
    '''
    
    doc = SimpleDocTemplate("operating_table_mockup.pdf")     
    story = [] 
    story.extend(make_day_tables([
        (datetime(2009, 10, 28, 0, 0),   'DROP THE JAZZ, GRATEFUL DEAD'),        
        (datetime(2009, 10, 28, 3, 5),   'TURN OFF TRANSMITTER'),
        (datetime(2009, 10, 28, 5, 45),  
            'TEST EAS LIGHTS AND TURN ON TRANSMITTER'),
        (datetime(2009, 10, 28, 11, 45), 'MY ASS IS ON FIRE'),
        (datetime(2009, 10, 28, 12, 00), 'TEST YOUR MOM'),
        (datetime(2009, 10, 28, 12, 59), 
            'WINNERS ARE LOSERS WITH A NEW ATTITUDE'),
        (datetime(2009, 10, 28, 12, 59), 'ROCK WITH IT'),                 
        (datetime(2009, 10, 28, 13, 00), 'STOP PLAYING METALLICA, FOOL'),
        (datetime(2009, 10, 28, 18,17),  'CHECK TOWER LIGHTS: READING ='),
        (datetime(2009, 10, 28, 23, 01), 'ENABLE HUMPBACK WHALES II'),
    ]))
    story.insert(1, PageBreak())
    
    doc.build(story)
Esempio n. 16
0
    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
Esempio n. 17
0
def make_pdf(data, title):
    tid = str(time()).replace('.', '')
    pdf_file = "reports/" + tid + ".pdf"

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

    doc = SimpleDocTemplate(pdf_file, pagesize=letter)

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

    parts = []
    table_with_style = Table(data)

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

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

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

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

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

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

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

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

		f.close()
Esempio n. 19
0
def make_pdf(bulk_order, outfile):
    """
    Generates a PDF and writes it to file-like object `outfile`.
    """
    logger.info('Starting make_pdf')
    cb = bulk_order.communityboard
    doc = SimpleDocTemplate(outfile, pagesize=letter,
                            leftMargin=0.5 * inch,
                            rightMargin=0.75 * inch,
                            )

    # XXX Sorting by street would be nice, but we don't have
    # addresses split into components, so we can't.
    racks = sorted(bulk_order.racks, key=lambda x: x.date)

    body = []

    body.append(Paragraph('Bike Rack Bulk Order:\n%s' % str(cb),
                          stylesheet['h1']))
    body.append(make_rack_table(racks))

    for rack in racks:
        body.append(PageBreak())
        body.extend(make_rack_page(rack))

    doc.build(body)
    logger.info('Finished make_pdf')
Esempio n. 20
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
Esempio n. 21
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)
Esempio n. 22
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
Esempio n. 23
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
Esempio n. 24
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
Esempio n. 25
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
Esempio n. 26
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
Esempio n. 27
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
Esempio n. 28
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
Esempio n. 29
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
Esempio n. 30
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
#TODO: Get this line right instead of just copying it from the docs
style = TableStyle([
    ('ALIGN', (1, 1), (-2, -2), 'RIGHT'),
    ('TEXTCOLOR', (1, 1), (-2, -2), colors.red),
    ('VALIGN', (0, 0), (0, -1), 'TOP'),
    ('TEXTCOLOR', (0, 0), (0, -1), colors.blue),
    ('ALIGN', (0, -1), (-1, -1), 'CENTER'),
    ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'),
    ('TEXTCOLOR', (0, -1), (-1, -1), colors.green),
    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
])

for links in urls:
    response = requests.get(links)
    rc = response.headers
    data.append([str(links), str(response.status_code), str(rc)])

#Configure style and word wrap
s = getSampleStyleSheet()
s = s["BodyText"]
s.wordWrap = 'CJK'
data2 = [[Paragraph(cell, s) for cell in row] for row in data]
t = Table(data2)
t.setStyle(style)

#Send the data and build the file
elements.append(t)
archivo_pdf.build(elements)
Esempio n. 32
0
class PDF():
    class PdfImage(Flowable):
        def __init__(self, img_data, width=200, height=200):
            self.img_width = width
            self.img_height = height
            self.img_data = img_data

        def wrap(self, width, height):
            return self.img_width, self.img_height

        def drawOn(self, canv, x, y, _sW=0):
            if _sW > 0 and hasattr(self, 'hAlign'):
                a = self.hAlign
                if a in ('CENTER', 'CENTRE', TA_CENTER):
                    x += 0.5 * _sW
                elif a in ('RIGHT', TA_RIGHT):
                    x += _sW
                elif a not in ('LEFT', TA_LEFT):
                    raise ValueError("Bad hAlign value " + str(a))
            canv.saveState()
            canv.drawImage(self.img_data, x, y, self.img_width,
                           self.img_height)
            canv.restoreState()

    def __init__(self, DIR="."):
        """
		Insert Arguments here
		"""
        self.doc = None
        self._title = None
        self.filename = None
        self.styles = getSampleStyleSheet()
        self.story = []
        self.DIR = DIR

    def _newPDF(self, filename, **kwargs):
        """
		Generate a new pdf document.

		Params
		------
		filename: str
			The name of your new pdf to generate
		For full list of arguments, see help(reportlab.platypus.SimpleDocTemplate)
		"""
        # TODO: Insert check for previously existing pdf
        # TODO: Error handle
        # TODO: Add directory to filename
        self.filename = filename
        self.doc = SimpleDocTemplate(filename, **kwargs)

    def addStyle(self, name, **kwargs):
        """
		Add custom styles to pdf.
		"""
        self.styles.add(ParagraphStyle(name=name, **kwargs))

    def addFont(self, font):
        """
		Goal is to add a general way to import fonts regardless of system and download
		"""
        #if font not in self.doc.getAvailableFonts():
        #	raise KeyError("%s not found in available font directory" % font)
        #else:
        #pdfmetrics.registerFont(TTFont('%s' % font, '%s.ttf' % font))
        print("Stub")

    def title(self, title, style=None):
        """
		Insert a title to pdf

		Params
		------
		title: str
			PDF title

		"""
        if style and style in self.styles:
            style = self.styles[style]
        else:
            style = self.styles["title"]
        self._title = Paragraph(title, style)

    def table(self, dataframe, style=None):
        """
		Generates a table with given styling and adds it to the storyboard

		Params
		------
		dataframe: pd.Dataframe
			A dataframe, usually of a collection of results
		"""
        #TODO: Customizable alignment
        if style and style in self.styles:
            style = self.styles[style]
        else:
            style = self.styles["Normal"]
        header = []
        row_list = []
        for heading in dataframe.columns:
            header.append(
                Paragraph("<para align=center>%s</para>" % heading, style))
        row_list.append(header)
        data = dataframe.to_dict("split")["data"]
        for record in data:
            row = [
                Paragraph("<para align=center>%s</para>" % item, style)
                for item in record
            ]
            row_list.append(row)
        t = Table(row_list, hAlign="CENTER")
        t.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))
        self.story.append(t)

    def text(self, text, style=None):
        if style and style in self.styles:
            style = self.styles[style]
        else:
            style = self.styles["Normal"]
        self.story.append(Paragraph(text, style))

    def plot(self, fig, width, height):
        """
		Draws matplotlib figure onto canvas
		"""
        imgdata = BytesIO()
        fig.savefig(imgdata, format="png")
        imgdata.seek(0)  # rewind the data
        im = ImageReader(imgdata)
        image = self.PdfImage(im, width=width, height=height)
        self.story.append(image)

    def newline(self, style=None):
        if style and style in self.styles:
            style = self.styles[style]
        else:
            style = self.styles["Normal"]
        self.story.append(Paragraph("<br /><br />\n", style))

    def build(self):
        if self._title:
            self.story.insert(0, self._title)
        if self.story:
            self.newline()
            #print(self.story)
            self.doc.build(self.story)
            return self.filename
Esempio n. 33
0
def print_app(request, app_id):
    project = Project.objects.get(pk=app_id)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="application.pdf"'
    p = SimpleDocTemplate(response,
                          pagesize=letter,
                          rightMargin=72,
                          leftMargin=72,
                          topMargin=72,
                          bottomMargin=18)
    template = []
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              fontSize=6))
    ptext = "%s Store Application" % (project.concept)
    template.append(Paragraph(ptext, styles["Normal"]))
    template.append(Spacer(1, 12))
    ptext = "%s,%s" % (project.last_name, project.first_name)
    template.append(Paragraph(ptext, styles["Normal"]))
    template.append(Paragraph(project.address, styles["Normal"]))
    ptext = "%s,%s %s" % (project.city, project.state, project.zip_code)
    template.append(Paragraph(ptext, styles["Normal"]))
    template.append(Spacer(1, 24))
    ptext = "Store Details"
    template.append(Paragraph(ptext, styles["Normal"]))
    ptext = "Store Concept: %s" % (project.concept)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Store Square Footage: %s" % (project.store_size)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Development Director: %s" % (project.sales_rep)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Where did you hear about us?: %s" % (project.advertising_source)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Store Location: %s" % (project.opening_location)
    template.append(Paragraph(ptext, styles["Justify"]))
    template.append(Spacer(1, 24))
    ptext = "Contact Information"
    template.append(Paragraph(ptext, styles["Normal"]))
    ptext = "First Name: %s" % (project.first_name)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Last Name: %s" % (project.last_name)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "E-Mail: %s" % (project.email)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Social Security Number: %s" % (project.social_security)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Date of Birth: %s" % (project.date_of_birth)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Primary Phone: %s" % (project.home_phone)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Cell Phone: %s" % (project.cell_phone)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Fax Number: %s" % (project.fax_number)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Best Time to Call: %s" % (project.best_call_time)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Address: %s" % (project.address)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "City: %s" % (project.city)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "State: %s" % (project.state)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Zip Code: %s" % (project.zip_code)
    template.append(Paragraph(ptext, styles["Justify"]))
    template.append(Spacer(1, 24))
    ptext = "Partner Information"
    template.append(Paragraph(ptext, styles["Normal"]))
    ptext = "Partner's Last Name: %s" % (project.last_name_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's First Name: %s" % (project.first_name_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's E-Mail: %s" % (project.email_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's SSN: %s" % (project.social_security_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Date of Birth: %s" % (project.date_of_birth_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Home Phone: %s" % (project.home_phone_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Cell Phone Number: %s" % (project.cell_phone_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Fax Number: %s" % (project.fax_number_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Address: %s" % (project.address_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's City: %s" % (project.city_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's State: %s" % (project.state_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Zip Code: %s" % (project.zip_code_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Credit and Employment"
    template.append(Spacer(1, 24))
    template.append(Paragraph(ptext, styles["Normal"]))
    ptext = "Place of Employment: %s" % (project.place_of_employment)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Place of Employment: %s" % (
        project.place_of_employment_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Years at Job: %s" % (project.years_at_job)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Years at Job: %s" % (project.years_at_job_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Annual Salary: %s" % (project.annual_salary)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Annual Salary: %s" % (project.annual_salary_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Credit Score: %s" % (project.credit_score)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Partner's Credit Score: %s" % (project.credit_score_partner)
    template.append(Paragraph(ptext, styles["Justify"]))
    template.append(Spacer(1, 48))
    ptext = "Funds Available"
    template.append(Paragraph(ptext, styles["Normal"]))
    ptext = "Cash Funds: %s" % (project.financing_cash)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Line of Credit: %s" % (project.financing_loc)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Home Equity LOC: %s" % (project.financing_hloc)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "401K Funds: %s" % (project.financing_401k)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Pension Funds: %s" % (project.financing_pension)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "IRA Funds: %s" % (project.financing_ira)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Stocks and Bonds: %s" % (project.financing_stocksbonds)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "CD Funds: %s" % (project.financing_cd)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Life Insurance: %s" % (project.financing_lifeinsurance)
    template.append(Paragraph(ptext, styles["Justify"]))
    template.append(Spacer(1, 36))
    template.append(Paragraph("Signature", styles["Normal"]))
    ptext = "My signature below authorizes: %s to obtain my consumer credit report and verifies that I am releasing my financial information including ACH Authorization. It is understood and agreed that this deposit is 100 percent refundable if the proper location for a store is not found and / or financing cannot be secured. With your prior approval, we will send a representative to do site location for you in your area. Only in that instance will reasonable travel expenses be deducted from your deposit amount. Once work begins in Real Estate on your project, the Company will be expending considerable resources to identify, evaluate and negotiate the lease terms of locations that you approve. It is imperative that you remain in constant contact with your leasing team, as time is of the essence in securing a location. You may request that your project be put on hold (for example, due to a family vacation or personal emergency) at any time, without penalty. A lapse of more than 7 days in telephone communication will result in the forfeiture of $1,500 of your deposit. More importantly, it may result in the loss of a desired store location. It is important that the net worth be realistic so we research the proper size of store that fits your budget." % (
        project.concept)
    template.append(Paragraph(ptext, styles["Justify"]))
    ptext = "Signature: %s" % (project.signature)
    template.append(Paragraph(ptext, styles["Normal"]))

    p.build(template)
    return response
Esempio n. 34
0
import os, glob, sys, shutil

if len(sys.argv) < 3:
    print "makePDF.py [folder] [image filetype]"

if not os.path.exists("./PDF"):
    os.makedirs("PDF")

path = sys.argv[1]
ext = sys.argv[2]
print "Reading Path : " + path

#PDF Prepare

parts = []

title = os.path.abspath(path)

title = os.path.basename(os.path.dirname(title)) + \
        "-" + os.path.basename(title)

title = title.replace("/", "-")

doc = SimpleDocTemplate("./PDF/" + title + ".pdf", pagesize=A2)

for infile in glob.glob(os.path.join(path, '*.' + ext)):
    parts.append(Image(infile))
print "Start Making PDF ...."
print "..."
doc.build(parts)
print "Outputt File at PDF/" + title + ".pdf"
Esempio n. 35
0
files.write(
    "\nExcept the main folder listed above, all other files will be deleted. \n If there is a specific file who dont want to be deleted,  "
    "kindly let us know the full path of the file. For example \n"
    "/Shared/Documents/E/myfile.pdf\n"
    "/Shared/Documents/E/cats.jpg \n"
    "wont be deleted")

flowables.append(
    Paragraph(
        "Except the main folder listed above, all other files will be deleted. \n If there is a specific file who dont want to be deleted,  "
        "kindly let us know the full path of the file. For example "
        "/Shared/Documents/E/myfile.pdf"
        "/Shared/Documents/E/cats.jpg "
        "wont be deleted", custom_body_style))

my_doc.build(flowables)
while True:
    answer = input(
        "Type D to delete these files. The files will be moved to Trash and can be restored up to 90 days: \n\n"
    )
    if answer.upper() == "D":
        for filename in os.listdir("/Volumes/gudmarketing/Shared/Documents"):
            #os.unlink(filename)
            for f in os.listdir("/Volumes/gudmarketing/Shared/Documents/" +
                                filename):
                try:
                    os.remove("/Volumes/gudmarketing/Shared/Documents/" +
                              filename + '/' + f)
                except PermissionError:
                    os.rmdir("/Volumes/gudmarketing/Shared/Documents/" +
                             filename + '/' + f)
Esempio n. 36
0
    ('FONTSIZE', (0, 0), (-1, 0), 14),
    ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
    ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
])

table.setStyle(style)

runNumb = len(data)
for i in range(1, runNumb):
    if i % 2 == 0:
        bc = colors.burlywood
    else:
        bc = colors.beige

    ts = TableStyle([
        ('BACKGROUND', (0, i), (-1, i), bc),
        ('LINEBEFORE', (2, 1), (2, -1), 2, colors.red),
        ('LINEABOVE', (0, 2), (-1, 2), 2, colors.green),
        ('GRID', (0, 1), (-1, -1), 2, colors.black),
    ])
    table.setStyle(ts)

# 添加边框
ts = TableStyle([('BOX', (0, 0), (-1, -1), 2, colors.black)])
table.setStyle(ts)

elements = []
elements.append(table)

pdf.build(elements)
Routing #: 226071457<br/>
Account #: 603000183<br/>
Northfield Bank<br/>
24 Hillel Pl., Brooklyn, NY 11210"""
para_routing = Paragraph(routing, style=para_style)

table_end_data = [['Please remit payment to', '', 'Wiring Instructions:'],
                  [para_address, '', para_routing],
                  ['Please reference on payment', '', ''],
                  ['Order Number ' + number_invoice, '', '']]

end_table = Table(table_end_data,
                  style=[('BOX', (0, 0), (0, 3), 0.5, colors.black),
                         ('BOX', (2, 0), (2, 3), 0.5, colors.black),
                         ('BOX', (0, 2), (0, 2), 0.5, colors.black),
                         ('LINEABOVE', (0, 1), (0, 1), 0.5, colors.black),
                         ('LINEABOVE', (2, 1), (2, 1), 0.5, colors.black),
                         ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                         ("FONTNAME", (0, 0), (3, 0), "palab"),
                         ("FONTNAME", (0, 1), (-1, -1), "pala"),
                         ("FONTSIZE", (0, 0), (-1, -1), 10),
                         ('VALIGN', (0, 1), (0, 1), 'TOP')])

end_table._argW[0] = 3.9 * inch
end_table._argW[2] = 3.9 * inch

Story.append(Spacer(0, 0.5 * inch))
Story.append(end_table)

doc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
Esempio n. 38
0
def makePdfAndSendToEmail(npm):
    checkDir()
    foldername='suratva'
    doc = SimpleDocTemplate(f'./{foldername}/SURAT-{npm}.pdf', pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18)
    doc.pagesize = portrait(A4)
    elements = []
    for i in range(2):
        namaOrtu=kelas.getParentNamefromStudentID(npm)[i]
        noTelp=kelas.getParentTelpNumberandHandphoneNumber(npm)[0]
        noHandphone=kelas.getParentTelpNumberandHandphoneNumber(npm)[1]
        emailOrtu=kelas.getParentEmailfromStudentID(npm)
        if i == 0:
            pekerjaanOrtu=getPekerjaanOrtuAyah(npm)
        else:
            pekerjaanOrtu=getPekerjaanOrtuIbu(npm)
        alamatLengkapOrtu=getAlamatLengkapOrtu(npm)
        hari=datetime.now().strftime('%d')
        bulan=bkd.bulanSwitcher(datetime.now().strftime('%m'))
        tahun=datetime.now().strftime('%Y')

        logo = Image("logo.png", 7.3 * inch, 1 * inch)
        logo.hAlign = "CENTER"
        elements.append(logo)

        pdfmetrics.registerFont(TTFont('TNR', 'timesdownload.ttf'))
        pdfmetrics.registerFont(TTFont('TNRB', 'timesdownloadbd.ttf'))

        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
        styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
        styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))
        styles.add(ParagraphStyle(name='surat_pernyataan_style', fontName="TNRB", fontSize=16, alignment=TA_CENTER))
        styles.add(ParagraphStyle(name='Times', fontName="TNR"))

        ptext = '<font>SURAT PERNYATAAN</font>'
        elements.append(Paragraph(f'<u>{ptext}</u>', styles["surat_pernyataan_style"]))
        elements.append(Spacer(1, 35))

        ptext = f'<font name="Times" size="10">Yang bertanda tangan di bawah ini :</font>'
        elements.append(Paragraph(ptext, styles["Justify"]))
        elements.append(Spacer(1, 8))

        data= [
            [f'<font name="Times" size="10">Nama</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{namaOrtu}</font>'],
            [f'<font name="Times" size="10">KTP</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10"> </font>'],
            [f'<font name="Times" size="10">No. Telepon</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{noTelp}</font>'],
            [f'<font name="Times" size="10">No. HP/WA</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{noHandphone}</font>'],
            [f'<font name="Times" size="10">Alamat E-mail</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{emailOrtu}</font>'],
            [f'<font name="Times" size="10">Pekerjaan</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{pekerjaanOrtu}</font>'],
            [f'<font name="Times" size="10">Alamat</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{alamatLengkapOrtu}</font>'],
            [f'<font name="Times" size="10">Lampiran</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">FC KTP dan KK orang tua/Wali (Wajib)</font>']
        ]
        style = TableStyle(
            [
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ]
        )
        s = getSampleStyleSheet()
        s = s["BodyText"]
        s.wordWrap = 'CJK'
        data1 = [[Paragraph(cell, s) for cell in row] for row in data]
        tab = Table(data1, hAlign='LEFT', colWidths=[3*cm, .5*cm, 10*cm])
        tab.setStyle(style)

        elements.append(tab)
        elements.append(Spacer(1, 0.35 * inch))

        ptext = f'<font name="Times" size="10">Adalah orang tua/wali dari Mahasiswa Politeknik Pos Indonesia :</font>'
        elements.append(Paragraph(ptext, styles["Justify"]))
        elements.append(Spacer(1, 8))

        data= [
            [f'<font name="Times" size="10">Nama</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{kelas.getStudentNameOnly(npm)}</font>'],
            [f'<font name="Times" size="10">NPM</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{npm}</font>'],
            [f'<font name="Times" size="10">No. HP</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{kelas.getStudentPhoneNumberFromNPM(npm)}</font>'],
            [f'<font name="Times" size="10">Alamat E-mail</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{kelas.getStudentEmail(npm)}</font>'],
            [f'<font name="Times" size="10">Prodi/Kelas</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{kelas.getProdiNameWithStudentID(npm)}/{kelas.getKelasMahasiswabyStudentID(npm)}</font>'],
            [f'<font name="Times" size="10">Angkatan</font>', '<font name="Times" size="10">:</font>', f'<font name="Times" size="10">{kelas.getTahunAngkatanWithStudentID(npm)}</font>'],
        ]
        style = TableStyle(
            [
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ]
        )
        s = getSampleStyleSheet()
        s = s["BodyText"]
        s.wordWrap = 'CJK'
        data1 = [[Paragraph(cell, s) for cell in row] for row in data]
        tab = Table(data1, hAlign='LEFT', colWidths=[3*cm, .5*cm, 10*cm])
        tab.setStyle(style)

        elements.append(tab)
        elements.append(Spacer(1, 0.25 * inch))

        ptext = f'<font name="Times" size="10">Dengan ini telah melakukan pembayaran sebesar Rp. .................................................................... (.............................................................................) serta menyatakan akan melunasi sisa kewajiban pembayaran uang SPP/Variabel/Tugas Akhir/PKL sebesar Rp. (...............................................................................) Paling lambat tanggal ...........................................................................</font>'
        elements.append(Paragraph(ptext, styles["Justify"]))
        elements.append(Spacer(1, 6))

        ptext = f'<font name="Times" size="10">Demikian surat pernyataan ini saya buat dengan sebenarnya untuk dipergunakan sebagaimana mestinya. Apabila saya melalaikan surat pernyataan ini, maka saya bersedia menerima sanksi sesuai dengan ketentuan yang berlaku di Politeknik Pos Indonesia.</font>'
        elements.append(Paragraph(ptext, styles["Justify"]))
        elements.append(Spacer(1, 12.5))

        data = [
            ['', '', Paragraph(f'<font name="Times">Bandung, {hari} {bulan} {tahun}</font>', styles["Center"])],
            [Paragraph(f'<font name="Times">Mengetahui,</font>', styles["Justify"]), '', Paragraph(f'<font name="Times">Yang Membuat Pernyataan,</font>', styles["Center"])],
            [Paragraph('<font name="Times">Dosen Wali</font>', styles["Justify"]), '',Paragraph('<font name="Times">Orang Tua/Wali</font>', styles["Center"])],
            ['', '', ''],
            ['', '', Paragraph('<font name="Times">Materai</font>', styles["Center"])],
            ['', '', ''],
            [Paragraph(f'<font name="Times">{kelas.getNamaDosen(kelas.getPenasehatAkademik(npm))}</font>', styles["Justify"]), '',Paragraph(f'<font name="Times">{namaOrtu}</font>', styles["Center"])],
            ['', Paragraph('<font name="Times">Menyetujui,</font>', styles["Center"]), ''],
            ['', Paragraph('<font name="Times">Wadir 2 / Ka. BAUK</font>', styles["Center"]), ''],
            ['', '', ''],
            ['', Paragraph('<font name="Times">...........................................</font>', styles["Center"]), ''],
        ]
        table = Table(data, [7*cm, 4.3*cm, 7*cm], [1*cm, .5*cm, .5*cm, .65*cm, .4*cm, .65*cm, .5*cm, .5*cm, .5*cm, 1.7*cm, .5*cm])
        table.setStyle(TableStyle([
            ('FONT',(0,0),(-1,-1),'Times-Roman', 12),
            ('ALIGN',(0,0),(-1,-1),'CENTER'),
        ]))
        elements.append(table)
    doc.build(elements)
    bkd.mail(
        kelas.getStudentEmail(npm),
        f'eyyyyooww {config.bot_name} kirim file SURAT PERNYATAAN PENGANGGUHAN SPP/VARIABEL nihhh',
        f'coba dicek dulu ya datanya, jika belum benar, coba cek SIAP-nya ya ubah lagi datanya, terus minta lagi ke {config.bot_name}, untuk surat pernyataannya',
        getFilePath(npm, foldername)
    )
Esempio n. 39
0
def merge_report_peeps(subj_id, report_filepath, graphs_dir):
    ps = ParagraphStyle(
        name='Normal',
        fontName='Helvetica',
        fontSize=10,
        spaceAfter=8,
    )

    doc = SimpleDocTemplate(graphs_dir + "{}_graphs.pdf".format(subj_id),
                            rightMargin=50,
                            leftMargin=50,
                            topMargin=50,
                            bottomMargin=50)
    parts = []

    image = get_image(graphs_dir + "{}_mean_exposure.png".format(subj_id),
                      width=480)
    parts.append(image)

    parts.append(Spacer(width=0, height=35))
    lines = tuple(open(graphs_dir + "{}_stats.txt".format(subj_id), 'r'))
    for line in lines:
        parts.append(Paragraph(line, ps))

    parts.append(PageBreak())

    image = get_image(graphs_dir + "{}_airspeck_map.png".format(subj_id),
                      width=480)
    parts.append(image)

    parts.append(Spacer(width=0, height=20))

    image = get_image(graphs_dir + "viridis_legend.png".format(subj_id),
                      width=300)  #was 220
    parts.append(image)

    parts.append(PageBreak())

    #image = get_image(graphs_dir + "{}_detailed_exposure.png".format(subj_id), rotated=True, width=720)
    image_2 = get_image(graphs_dir +
                        "{}_detailed_exposure.png".format(subj_id),
                        rotated=True,
                        width=720)

    parts.append(image_2)

    doc.build(parts)

    output = PdfFileWriter()

    with open(peeps_reports_dir + "first_page.pdf", "rb") as f:
        cover_pdf = PdfFileReader(f)
        output.addPage(cover_pdf.getPage(0))

        with open(graphs_dir + "{}_graphs.pdf".format(subj_id), "rb") as f:
            rest_pdf = PdfFileReader(f)
            for p_idx in range(rest_pdf.getNumPages()):
                output.addPage(rest_pdf.getPage(p_idx))

            with open(report_filepath, "wb") as f:
                output.write(f)
Esempio n. 40
0
def schedulepdf(request):
    response = {}

    if (request.method == 'POST'):

        token = request.POST.get("token")
        day = request.POST.get("day")

        auth_result = views.verify_token(token)
        if (auth_result != None):
            schedule = []
            if (auth_result["type"] == "FACULTY"):
                # retrieve faculties timetable
                if (day != None and int(day) >= 1 and int(day) <= 7):
                    # courses=models.Course.objects.filter(lecture__lecturer=auth_result["object"],lecture__timetable__day=day)
                    lecs = models.Timetable.objects.filter(lecture__lecturer=auth_result["object"], day=day)
                    for course in lecs:
                        schedule.append(
                            {
                                "coursename": course.lecture.course.name,
                                "starttime": course.start,
                                "duration": course.duration,
                                "semester": course.lecture.course.clas.semester.semester,
                                "division": course.lecture.div.div,
                                "department": course.lecture.course.clas.dept.name
                            }
                        )
                    response['timetable'] = schedule
                else:
                    lecs = models.Timetable.objects.filter(lecture__lecturer=auth_result["object"])
                    for course in lecs:
                        schedule.append(
                            {
                                "coursename": course.lecture.course.name,
                                "starttime": course.start,
                                "duration": course.duration,
                                "semester": course.lecture.course.clas.semester.semester,
                                "division": course.lecture.div.div,
                                "department": course.lecture.course.clas.dept.name,
                                "day": course.day,
                            }
                        )
                    response['timetable'] = schedule
            elif (auth_result["type"] == "STUDENT"):
                # retrieve student timetable
                student = auth_result["object"]
                if (day != None and int(day) >= 1 and int(day) <= 7):
                    lecs = models.Timetable.objects.filter(lecture__div=student.div, day=day)
                    for course in lecs:
                        schedule.append(
                            {
                                "coursename": course.lecture.course.name,
                                "starttime": course.start,
                                "duration": course.duration,
                                "semester": course.lecture.course.clas.semester.semester,
                                "division": course.lecture.div.div,
                                "department": course.lecture.course.clas.dept.name,
                                "faculty": course.lecture.lecturer.user.first_name + " " + course.lecture.lecturer.user.last_name
                            }
                        )
                    response['timetable'] = schedule
                else:
                    lecs = models.Timetable.objects.filter(lecture__div=student.div)
                    for course in lecs:
                        schedule.append(
                            {
                                "coursename": course.lecture.course.name,
                                "starttime": course.start,
                                "duration": course.duration,
                                "semester": course.lecture.course.clas.semester.semester,
                                "division": course.lecture.div.div,
                                "department": course.lecture.course.clas.dept.name,
                                "day": course.day,
                                "faculty": course.lecture.lecturer.user.first_name + " " + course.lecture.lecturer.user.last_name
                            }
                        )
                        # Create the HttpResponse object with the appropriate PDF headers.
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename="schedule.pdf"'

            elements = []
            table_data=[]
            doc = SimpleDocTemplate(response, rightMargin=2, leftMargin=3, topMargin=10, bottomMargin=0)
            headers=[]
            for header in schedule[0]:
                headers.append(header)

            table_data.append(headers)

            for lec in schedule:
                data = []
                for key in lec:
                    data.append(lec[key])
                table_data.append(data)

            table = Table(table_data)

            table.setStyle(TableStyle([
                                   ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                                   ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                   ]))
            elements.append(table)
            doc.build(elements)

            return response
        else:
            return HttpResponse("Invalid")

    else:
        return HttpResponse("Invalid")
Esempio n. 41
0
class Report:
    def __init__(self, fileName):
        self.doc = SimpleDocTemplate(fileName,
                                     pagesize=A4,
                                     rightMargin=52,
                                     leftMargin=52,
                                     topMargin=52,
                                     bottomMargin=18)
        self.styles = getSampleStyleSheet()
        self.numberColumns = 0
        self.numberRows = 0
        self.numberRowsTrain = 0
        self.numberRowsTest = 0
        self.nNeighbors = []

    '''
    Método adiciona novos estilos de parágrafo
    '''

    def defineStyles(self):
        self.styles.add(
            ParagraphStyle(name='Justify',
                           alignment=TA_JUSTIFY,
                           fontName='Times-Roman',
                           fontSize=12))

    def setNumberColumnsAndRows(self, nColTotal, nRowTotal, nRowTrain,
                                nRowTest):
        self.numberColumns = nColTotal
        self.numberRows = nRowTotal
        self.numberRowsTrain = nRowTrain
        self.numberRowsTest = nRowTest

    '''
    Método gera relatório no formato pdf
    '''

    def generateReport(self, graphics, neighbors):
        self.defineStyles()
        head = self.head()
        self.nNeighbors = neighbors
        graphics = self.graphics(graphics)

        story = head + graphics

        self.doc.build(story)

    '''
    Método adiciona informações básicas ao relatório
    '''

    def head(self):
        story = []
        texto = '<font name=Times-Roman>Sistemas de Apoio a Decisão</font>'
        story.append(Paragraph(texto, self.styles['Title']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Roman>CLASSIFICAÇÃO</font>'
        story.append(Paragraph(texto, self.styles['Title']))
        story.append(Spacer(1, 12))
        texto = '<font size=16 name=Times-Roman>BASE DE DADOS: SRAG - 2020</font>'
        story.append(Paragraph(texto, self.styles['Title']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Bold>Descrição da base de dados: </font>\
        <font>Ficha individual de casos de síndrome respiratória aguda grave hospitalizados</font>'

        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        texto = '<font size=12 name=Times-Bold>Tipo de classificação: </font>\
        <font>Diagnóstico de SRAG (1 - SRAG por influenza, 2 - SRAG por outro vírus respiratório, 3 - SRAG por outro agente etiológico,\
         4 - SRAG não especificado, 5 - SRAG por COVID-19)</font>'

        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Bold>Equipe: </font><font>Fabiana Barreto Pereira, Guilherme Ferreira Faioli Lima,\
         Junior Reis dos Santos, Rafaela Silva Miranda e Yasmine de Melo Leite</font>'

        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Bold>Discente: </font><font>Janniele Aparecida Soares Araujo</font>'
        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        data = datetime.now().strftime('%d/%m/%Y - %H:%M')
        texto = '<font name=Times-Bold>Data da análise: </font><font>' + data + '</font>'
        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Bold>Total de linhas da base de dados: </font><font>725615</font>'
        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Bold>Total de colunas da base de dados: </font><font>154</font>'
        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Bold>Total de linhas consideradas: </font><font>' + str(
            self.numberRows) + ' (' + str(
                self.numberRowsTrain) + ' para treinamento e ' + str(
                    self.numberRowsTest) + ' para teste)</font>'
        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Bold>Total de colunas consideradas: </font><font>' + str(
            self.numberColumns) + '</font>'
        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))
        texto = '<font name=Times-Bold>Algoritmo: </font><font>K-NN (KNeighborsClassifier da biblioteca Scikit-learn)</font>'
        story.append(Paragraph(texto, self.styles['Justify']))
        story.append(Spacer(1, 12))

        return story

    def graphics(self, graphics):
        story = []
        story.append(Spacer(1, 20))
        # Balanceamento do banco
        texto = '<font fontSize=12>Verificando balanceamento do conjunto de dados</font>'
        story.append(Paragraph(texto, self.styles['Title']))
        story.append(Spacer(1, 12))

        image = graphics[0]
        im = Image(image, self.in2p(4), self.in2p(3))
        story.append(im)
        story.append(Spacer(1, 12))
        # precisão
        texto = '<font fontSize=12>Precisão dos dados de teste</font>'
        story.append(Paragraph(texto, self.styles['Title']))
        story.append(Spacer(1, 12))

        image = graphics[len(graphics) - 1]
        im = Image(image, self.in2p(5), self.in2p(2))
        story.append(im)
        story.append(Spacer(1, 12))
        #análise para cada k

        texto = '<font fontSize=12>Avaliação por número de vizinhos (k)</font>'
        story.append(Paragraph(texto, self.styles['Title']))
        story.append(Spacer(1, 12))

        for k in self.nNeighbors:
            texto = '<font fontSize=12>Avaliação para k = ' + str(
                k) + '</font>'
            story.append(Paragraph(texto, self.styles['Title']))
            story.append(Spacer(1, 12))

            for i in range(1, len(graphics) - 1):
                test = "_" + str(k)
                if test in graphics[i]:
                    image = graphics[i]
                    if 'Erro' in graphics[i]:
                        im = Image(image, self.in2p(5), self.in2p(2))
                    else:
                        im = Image(image, self.in2p(4), self.in2p(3))
                    story.append(im)

            story.append(Spacer(1, 20))

        return story

    '''
    Método transforma Inch em pt
    '''

    def in2p(self, Inch):
        return Inch * 72
Esempio n. 42
0
def download(request):
    #form = ReportForm()
    #context = {'form': form}
    if request.method == 'GET':
        urls = request.GET.getlist("article_url")
        #form = ReportForm(request.GET.getlist("article_url[]"))
        time = strftime("%Y-%m-%d-%H_%M_%S", gmtime())
        doc = SimpleDocTemplate("/tmp/relatorioNOTICIAS%s.pdf" % time)
        styles = getSampleStyleSheet()
        Story = [Spacer(1, 0 * inch)]
        style = styles["Normal"]
        bogustext = ("Relatório de notícias:")
        p = Paragraph(bogustext, style)
        Story.append(p)
        Story.append(Spacer(1, 0.2 * inch))
        for i, url in enumerate(urls):
            article_in_db = Article.objects.filter(url=str(url)).first()
            if article_in_db is not None:
                bogustext = ("%d. Título da notícia: %s." %
                             (i + 1, article_in_db.title))
                p = Paragraph(bogustext, style)
                Story.append(p)
                bogustext = ("Resumo da notícia: %s." %
                             article_in_db.long_summary)
                p = Paragraph(bogustext, style)
                Story.append(p)
                if article_in_db.publish_date != None:
                    bogustext = ("Data de publicação: %s." %
                                 article_in_db.publish_date)
                    p = Paragraph(bogustext, style)
                    Story.append(p)
                if article_in_db.risk == 1:
                    bogustext = "Risco dessa notícia: Baixo."
                    p = Paragraph(bogustext, style)
                    Story.append(p)
                elif article_in_db.risk == 2:
                    bogustext = "Risco dessa notícia: Médio."
                    p = Paragraph(bogustext, style)
                    Story.append(p)
                elif article_in_db.risk == 3:
                    bogustext = "Risco dessa notícia: Alto."
                    p = Paragraph(bogustext, style)
                    Story.append(p)
                bogustext = "Entidades envolvidas na notícia: "
                for entity in article_in_db.entities:
                    bogustext += ("%s " % entity)
                p = Paragraph(bogustext, style)
                Story.append(p)
                bogustext = ("Categoria da notícia: %s." %
                             article_in_db.category)
                p = Paragraph(bogustext, style)
                Story.append(p)
                bogustext = ("Fonte da notícia: %s" % get_domain(url))
                p = Paragraph(bogustext, style)
                Story.append(p)
                bogustext = ("Url da notícia: %s" % url)
                p = Paragraph(bogustext, style)
                Story.append(p)
                Story.append(Spacer(1, 0.2 * inch))

        doc.build(Story)
        fs = FileSystemStorage("/tmp")
        with fs.open("relatorioNOTICIAS%s.pdf" % time) as pdf:
            response = HttpResponse(pdf, content_type='application/pdf')
            response['Content-Disposition'] = (
                'attachment; filename="relatorioNOTICIAS%s.pdf"' % time)
            return response

    return response