Example #1
0
def hourpdf(request): # use to see working of temporary employee.
    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page()
    ganY = [46, 54]  # line bettwen collumn.
    
    pdf.add_font('Kinnari', '', 'Kinnari.ttf', uni=True)
    pdf.set_font('Kinnari', '', 12)
    
    gen_single_text(pdf, 60, u'ใบลงเวลาทำงานลูกจ้างชั่วคราวรายชั่วโมง')
    gen_single_text(pdf, 45, u'มหาวิทยาลัยเทคโนโลยีพระจอมเกล้าพระนครเหนือ')
    gen_single_text(pdf, 70, u'ชื่อ')
    
    pdf.ln(8)
    pdf.cell(0, 18, u'    วัน           วันที่ เดือน ปี          เวลาทำงาน      รวมชั่วโมง       ลายมือชื่อ          หมายเหตุ')
    drawAttr2(pdf, ganY[0], ganY[1], True)
    
    gen_single_text(pdf, 90, u'รวมจำนวนชั่วโมง ' + u'ชั่วโมง') # call spacial funtion to write a text per line.
    gen_single_text(pdf, 90, u'อัตรา 45.45 บาท ชั่วโมง')
    gen_single_text(pdf, 90, u'รวมเป็นเงินทั้งสิ้น' + u'บาท')
    gen_single_text(pdf, 90, u'(                   )')
    gen_single_text(pdf, 90, u'ได้ตรวจสอบถูกต้องแล้ว')
    gen_single_text(pdf, 75, u'ลงชื่อ.......................................................')
    gen_single_text(pdf, 80, u'(...................................................)')
    
    pdf.output("group3/hour.pdf", 'F')
    
    with open('group3/hour.pdf', 'rb') as pdf: # path to pdf in directory views.
        response = HttpResponse(pdf.read(),content_type='application/pdf')
        response['Content-Disposition'] = 'filename=hour.pdf'
        return response
    pdf.closed
Example #2
0
class Document(object):

    def __init__(self, **kwargs):
        self.pdf = FPDF(**kwargs)
        self.pdf.add_page()
        self.pdf.set_margins(20, 20, 0)
        self.pdf.ln()
        self._add_font('DejaVu', 'DejaVuSansCondensed.ttf')
        self._add_font('DejaVu-Bold', 'DejaVuSansCondensed-Bold.ttf')

    def _add_font(self, font_name, file_name):
        self.pdf.add_font(font_name, '', asset_path(file_name), uni=True)

    def _font(self, size, bold=False):
        font_name = 'DejaVu' if not bold else 'DejaVu-Bold'
        self.pdf.set_font(font_name, '', size)

    def _text_cell(self, w, h, text, size=10, bold=False, align='L', border=BORDER_DEBUG):
        self._font(size, bold=bold)
        self.pdf.cell(w, h, text, align=align, border=border)

    def _multi_cell(self, w, h, text, size=10, bold=False, align='L', border=BORDER_DEBUG):
        self._font(size, bold=bold)
        self.pdf.multi_cell(w, h, text, align=align, border=border)

    def output(self):
        return self.pdf.output(dest='S')
Example #3
0
def randompdf (path) :

	numpdf = (randint(1500,2000))

	for i in range(10):
	
		name = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"
	
		numwords = (randint(200,1000))
	
		pdf = FPDF()
		pdf.add_page()
		pdf.set_font("Arial", size=12)
	
		words =[]
	
		for i in range(numwords):
		
			randomword  = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))])
			words.append(randomword)
	
		wordsinstring = ''.join(words)
	
		pdf.cell(200, 10, txt=wordsinstring, align="C")
		
		pdf.output(name)
		
		for i in range(numpdf):
			
			dupli = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"
			
			copyfile(name, dupli)
Example #4
0
 def test_hello_world(self):
     pdf=FPDF()
     pdf.add_page()
     pdf.set_font('Arial','B',16)
     pdf.cell(40,10,hello_world)
     pdf.output(hello_world_file,'F')
     self.assertTrue(os.path.exists(hello_world_file))
Example #5
0
    def createPDF(self, name=None, size='10kb'):
        from PyPDF2 import PdfFileReader, PdfFileWriter
        from fpdf import FPDF
        import os
        import random
        name = os.path.basename(name)
        tmp_name = '/tmp/' + name
        output_name = self.sharepath + '/' + name

        if size == '10kb':
            randlength = random.randint(10000,90000)
        elif size == '100kb':
            randlength = random.randint(100000,900000)
        elif size == '1mb':
            randlength = random.randint(1000000,9000000)

        #create file
        pdf=FPDF()
        pdf.add_page()
        pdf.set_font('Arial','B',8)
        pdf.cell(0,0,os.urandom(randlength))
        pdf.output(tmp_name, "F")

        #encrypt it
        output = PdfFileWriter()
        input1 = PdfFileReader(open(tmp_name, "rb"))
        output.encrypt(user_pwd="ihasapass")
        output.addPage(input1.getPage(0))

        outputStream = file(output_name, "wb")
        output.write(outputStream)
        outputStream.close()
def createPDF(tFile):
    # Create PDF output dir if not exist
    if args.op.split("/")[0] not in listdir(curdir):
        mkdir(args.op)

    # Set fuzzed pdf name
    sPfile = tFile.split(".ttf")[0]
    tempPDF = FPDF()
    # Add our fuzzed ttf into PDF
    try:
        tempPDF.add_font(sPfile, "", args.o + "/" + tFile, uni=True)
    except:
        return
    tempPDF.set_font(sPfile, "", 16)

    # Create blank page and fill it with data
    tempPDF.add_page()
    tempPDF.cell(40, 10, "PDF TEST FILE")

    # Create fuzzed PDF
    try:
        tempPDF.output(args.op + sPfile + ".pdf", "F")
    except:
        return

    tempPDF.close()
Example #7
0
 def get(self):
     pdf=FPDF()
     pdf.add_page()
     pdf.add_font('DejaVu','','font/DejaVuSansCondensed.ttf',uni=True)
     pdf.set_font('DejaVu','',16)
     #pdf.set_font('Arial','B',16)
     pdf.cell(40,10,u'Hello World! Здравствуй мир')
     pdf.image('images/LoadFile.png', 0, 50)
     self.response.headers['Content-Type'] = 'application/pdf'
     self.response.write(pdf.output('', 'S'))
Example #8
0
def fpdf():
	pdf = FPDF()
	pdf.add_page()
	pdf.set_font('Arial', 'B', 16)
	pdf.cell(40, 10, 'Reporte')
	pdf.output('reporte.pdf', 'F')
	import os
    	try:
        	os.startfile('reporte.pdf')
    	except Exception:
        	os.system("xdg-open \"%s\"" % 'reporte.pdf')
Example #9
0
def create_pdf(traceback):
	traceback = traceback.split("\n")
	pdf = FPDF()
	pdf.add_page()
	pdf.set_font('Arial', 'B', 12)
	pdf.cell(40, 10, "Send this error report to the administrator if the problem occurs again: \n", 0, 1)
	
	for x in xrange(0, len(traceback)):
		pdf.cell(40, 10, traceback[x], 0, 1)
		print traceback[x]
	pdf.output('pdf/stack.pdf', 'F')
Example #10
0
 def test_unicode_font(self):
     pdf=FPDF()
     pdf.add_page()
     #pdf.add_font('DejaVu','','font/DejaVuSansCondensed.ttf',uni=True)
     pdf.add_font('DejaVu','I','font/DejaVuSerif-Italic.ttf',uni=True)
     pdf.set_font('DejaVu','I',16)
     #pdf.set_font('Arial','B',16)
     pdf.cell(40,10,u'Здравствуй мир  \u2200 x \u2203 y \u223c \u221e')
     pdf.output('HelloWorld.pdf', 'F')
     
     
Example #11
0
def createPDF(values):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", "B", 24)
    pdf.cell(0, 20, TITLE_PDF, border=0,align="C", ln=1)
    #pdf.image(LETTERHEAD_PNG,5, 5, 0, 0)     #### COMENTED OUT TO DUE NO IMAGE
    pdf.set_font("Courier", "", 10)
    i = 0
    for i in range(len(values)):
        pdf.multi_cell(0, 6, values["res"+str(i)], border=1)  ## Must be dynamic
        i += 1

    curUTC = strftime("%Y-%m-%dT%H-%M-%SZ", gmtime(time()))
    pdf.output(PDF_SAVE_TEMPLATE + "-" + curUTC + ".pdf", "F")
 def createReportForProjectPDF(self, pid):
     data = self.createReportForProject(pid)
     pdf = FPDF()
     pdf.add_page()
     pdf.set_font('Arial', 'B', 16)
     pdf.cell(40, 10, data['title'])
     pdf.set_font('Arial', size=12)
     pdf.multi_cell(w=0, h=10, txt='')
     pdf.multi_cell(0, 5, 'Users involved in project: ')
     for user in data['users']:
         pdf.multi_cell(0, 5, txt=" - " + user)
     pdf.multi_cell(0, 5, 'Tasks closed: ' + str(data['nrTasksClosed']))
     pdf.multi_cell(0, 5, 'Tasks in progress: ' + str(data['nrTasksInProgress']))
     pdf.multi_cell(0, 5, 'Tasks to do: ' + str(data['nrTasksToDO']))
     pdf.multi_cell(0, 5, 'Most active user is: ' + str(data['mostActive']))
     pdf.multi_cell(0, 5, 'Total time logged: ' + str(data['timeLogged']))
     pdf.multi_cell(0, 5, 'Time remaining for tasks: ' + str(data['timeRemaining']))
     pdf.output('generated_reports/project_' + str(pid) + '_report.pdf', 'F')
Example #13
0
def save_file():
	filename = request.values['filename']
	contents = request.values['contents']
	fname = os.path.join(app.config['UPLOAD_FOLDER'], filename)
	backup_path = os.path.join(app.config['BACKUP_FOLDER'], filename)
	shutil.copy2(fname, backup_path)
	exten = fname.split('.')[1]
	if exten != 'pdf' :
		f = open(fname, 'w')
		f.write(contents)
		f.close()
	else:
		pdf=FPDF('P', 'mm',(500,400))
		pdf.add_page()
		pdf.set_font('Courier','B',16)
		for line in contents.split("\n"):
			pdf.cell(40,10,line)
			pdf.ln(h='')
		pdf.output(fname,'F')
	return redirect(url_for('list'))
Example #14
0
	def pdf(query, title):
		pdf=FPDF(format='letter', unit='in')
		pdf.add_page()
		pdf.set_font('Times','',7.0)
		epw = pdf.w - 2*pdf.l_margin
		col_width = epw/4

		pdf.set_font('Times','B',14.0)
		pdf.cell(epw, 0.0, title, align='C')
		pdf.set_font('Times','',10.0)
		pdf.ln(0.5)
		th = pdf.font_size

		for row in query:
			for datum in row:
				pdf.cell(col_width, th, str(datum), border=1)
			pdf.ln(th)

		pdf.ln(4*th)

		return pdf.output('reporte.pdf','F')
Example #15
0
def dotest(outputname, nostamp=True):
    pdf = FPDF(unit="pt")
    pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font("Times", size=12)
    pdf.cell(0, 12, "Dummy content")
    
    # Get the PDF data the usual way via a real file
    pdf.output(outputname)
    with open(outputname, "rb") as file:
        data = file.read(1000)
        assert len(data) == 966, "Unexpected PDF file size"
    
    try:  # Python < 3 (Python 2.5 does not have the "io" module)
        from cStringIO import StringIO
        capture = StringIO()
        detach = lambda: capture
    except ImportError:  # Python >= 3.1
        from io import TextIOWrapper, BytesIO
        # Ensure that no text encoding is actually done
        capture = TextIOWrapper(BytesIO(), "undefined")
        detach = lambda: capture.detach()
    
    # Compare data when output() writes to stdout
    original_stdout = sys.stdout
    try:
        sys.stdout = capture
        pdf.output()
        capture = detach()
    finally:
        sys.stdout = original_stdout
    assert capture.getvalue() == data, "Unexpected stdout data"
    
    # Compare data when output() returns a byte string
    returned = pdf.output(dest="S")
    assert isinstance(returned, bytes), "output() should return bytes"
    assert returned == data, "Unexpected PDF data returned"
Example #16
0
 def group_label(self, group_id, name, location, notes):
     pdf = FPDF(format=(80,65), unit='mm')
     pdf.set_margins(5, 5)
     pdf.add_page()
     self.create_barcode(group_id)
     pdf.image('barcode.png', x=0, y=0, h=30)
     pdf.set_font('Arial', '', 14)
     pdf.cell(30)
     pdf.cell(40,0, location, 0, 2)
     pdf.ln(10)
     pdf.cell(30)
     pdf.cell(21, 4, str(group_id) + ": " + name, 0, 1)
     pdf.ln(10)
     pdf.set_font('Arial', '', 8)
     pdf.multi_cell(0, 5, notes, 0, 2)
     pdf.output('barcodes/group_label.pdf')
     self.print_barcode('barcodes/group_label.pdf')
Example #17
0
def dotest(outputname, nostamp):
    try:
        # Portrait, millimeter units, A4 page size     
        pdf = FPDF("P", "mm", "A4")
        # Set font: Times, normal, size 10
        pdf.set_font('Times','', 12)
        ##pdf.add_page()
        # Layout cell: 0 x 5 mm, text, no border, Left
        pdf.cell(0,5,'Input 1 : ',border=0,align="L")
        pdf.cell(0,5,'Input 2 : ', border=0,align="L")
        pdf.cell(0,5,'Recomendation : ', border=0, align="L")
        pdf.cell(0,5,'Data 1 :', border=0, align="L" )
        pdf.cell(0,5,'Data 2 :', border=0, align="L" )
        pdf.output(outputname,'F')
    except RuntimeError as e:
        assert e.args[0] == "FPDF error: No page open, you need to call add_page() first"
    else:
        raise RuntimeError("Exception not raised!")
Example #18
0
    def label_with_info(self, serial, f_list, username, old, new):
        pdf = FPDF(format=(80,65), unit='mm')
        pdf.add_page()
    # put barcode here
        self.create_barcode(serial)

        pdf.image('barcode.png', x=0, y=0,  h=30) # barcodes print out with height of 280px.
        pdf.set_font('Arial', '', 12) 
        pdf.ln(21)
        pdf.cell(21, 4, "Added " + time.strftime("%c"),0,2)
        pdf.cell(80, 4, "Created: " + old,0,2)
        pdf.cell(80, 4, "Modified: " + new,0,2)
        #pdf.set_font('Arial', '', 12)
        #pdf.cell(30, 10, "created: " + old + ", modified: " + new, ln=1)        
        pdf.output('barcodes/label.pdf')
        self.print_barcode('barcodes/label.pdf')
Example #19
0
def print_file(title, data):
  (f, fname) = tempfile.mkstemp(text=True)
  pdf = FPDF('L', unit='mm', format=(112, 100))
  pdf.add_page()

  pdf.set_font('Arial', '', 8)
  pdf.cell(0, 10, data['newTicketTime'], 0, 1)
  pdf.ln()
  pdf.ln()

  pdf.set_font('Arial', 'B', 128)
  pdf.cell(0, 10, data['newTicketValue'], 0, 1, 'C')

  pdf.set_font('Arial', '', 18)
  pdf.ln()
  pdf.cell(0, 10, data['description'].encode('cp1252', 'ignore'), 0, 1, 'C')

  qr = qrcode.QRCode(box_size=3)
  link = 'http://q.foi.hr/view?id=' + str(data['id'])
  qr.add_data(link)
  qr.make(fit=True)
  img = qr.make_image()
  (qf, qfname) = tempfile.mkstemp(suffix='.png')
  img.save(qfname, 'PNG')
  pdf.image(qfname)

  pdf.set_font('Arial', '', 10)
  pdf.text(47, 87, link)

  pdf.output(fname)

  job = CUPS.printFile(PRINTER_NAME, fname, title, {})
  while job in CUPS.getJobs(which_jobs='not-completed').keys():
    time.sleep(2)

  os.unlink(fname)
  os.unlink(qfname)
Example #20
0
 def test_pdf_cell(self):
     pdf=FPDF()
     pdf.c_margin = 0.0
     pdf.add_font('symbol','','font/DejaVuSans.ttf',uni=True)
     pdf.add_page()
     f = 0.81
     font_name = 'times'
     
     text = 'small text'
     pdf.set_font(font_name,'',12)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w, h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     text = 'Large text'
     pdf.set_font(font_name,'',24)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w,h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     text = 'Larger text'
     pdf.set_font(font_name,'',48)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w,h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     pdf.output('out/fpdf/test_pdf_cell.pdf', 'F')
def query_matching(q):
    global output
    q_vector = vectorizer.transform([q])
    q_transformed = svd_model.transform(q_vector)

    coses = []
    for j in range(len(X_transformed)):
        ap = np.dot(q_transformed, X_transformed[j]) / (
            np.linalg.norm(q_transformed) * np.linalg.norm(X_transformed[j]))
        if str(ap[0]) == 'nan':
            coses.append(-1)
        else:
            coses.append(ap[0])
        #print("cos(q,doc["+str(j)+"] = "+str(coses[-1]))

    coses = np.asarray(coses)
    p = coses.argsort()
    largest = p[::-1][:20]

    max_num_docs = 8
    print("Top " + str(max_num_docs) + " similar documents are: ")

    output = []
    #os.mkdir('./output')
    os.chdir('./static/output')
    output.append("<html><body>")
    for i in range(max_num_docs):
        output.append(' <p class="w3-wide">DOCUMENT ' + str(i) +
                      " with similarity " + str(coses[largest[i]]) + " </p> ")
        #output.append(' <pre> '+documents[largest[i]]+" </pre> <hr>")
        output.append('<embed src="' +
                      url_for('static',
                              filename='output/doc ' + str(i) + "[" +
                              str(coses[largest[i]]) + '].pdf') +
                      '" type="application/pdf" width="50%" height="80%">')
        output.append("</body></html>")
        name = "doc " + str(i) + "[" + str(coses[largest[i]]) + "]"

        with open(name, 'w') as f:
            f.write("%s\n" % documents[largest[i]])

        pdf = FPDF()

        # Add a page
        pdf.add_page()

        # set style and size of font
        # that you want in the pdf
        pdf.set_font("Arial", size=15)

        # open the text file in read mode
        f = open(name, "r")

        # insert the texts in pdf
        for x in f:
            pdf.cell(200, 10, txt=x, ln=1, align='C')

        # save the pdf with name .pdf
        name += ".pdf"
        pdf.output(name)
    os.chdir('../../')
Example #22
0
# -*- coding: utf-8 -*-

from fpdf import FPDF

pdf=FPDF()
#Adicionando página
pdf.add_page()
#Adicionando configurações de Fonte
pdf.set_font('Arial','B',11)
#Inserindo linhas cell by cell.
pdf.cell(0,10,'CONTRATO DE LOCAÇÃO RESIDENCIAL', 0,1 , 'C')
pdf.set_font('Arial','',8)
pdf.cell(0,10,'(SUGESTÃO DE MINUTA BÁSICA)', 0,1 ,'C')
pdf.ln(10)
#Locador
pdf.set_font('Arial','I',9)
pdf.cell(0,5,'LOCADOR(A):	..................................., brasileiro, solteiro, comerciante,', 0,1 , 'J')
pdf.cell(0,5,'portador da cédula de identidade RG ....................../SSP.SP e inscrito no CPFMF sob nº ...................', 0,1 , 'J')
#Locatario
pdf.cell(0,5,'LOCATÁRIO(A): ................................................, brasileiro, casado, autônomo,', 0,1 , 'J')
pdf.cell(0,5,', portador da cédula de identidade RG .................SSP/SP e inscrito no CPFMF sob nº ................... ', 0,1 , 'J')
pdf.ln(5)
#Objeto
pdf.set_font('Arial','B',9)
pdf.cell(0,5,'OBJETO:', 0,1 , 'C')
pdf.set_font('Arial','',9)
pdf.cell(0,5,'A CASA SOB Nº ....., DA RUA ................................, ou A UNIDADE RESIDENCIAL SOB N ....., ', 0,1 ,'')
pdf.cell(0,5,'SITO NA RUA ............. N ..., na cidade de ..................., SP, com suas benfeitorias e instalações',0,1,'')
pdf.ln(5)
#--
pdf.set_font('Arial','I',8)
Example #23
0
def novoVenda(
    nomeVend,
    naturalidadeVend,
    estadoCivilVend,
    profissaoVend,
    rgVend,
    cpfVend,
    ruaVend,
    numVend,
    bairroVend,
    cepVend,
    cidadeVend,
    estadoVend,
    nomeComp,
    naturalidadeComp,
    estadoCivilComp,
    profissaoComp,
    rgComp,
    cpfComp,
    ruaComp,
    numComp,
    bairroComp,
    cepComp,
    cidadeComp,
    estado,
    area,
    registro,
    valor,
):
    # Definindo o formato do PDF
    pdf = FPDF("P", "mm", "A4")
    # Definindo as margens
    pdf.set_margins(10, 10, 10)
    # Adicionando página
    pdf.add_page()
    # Adicionando configurações de Fonte

    pdf.set_font("Arial", "B", 16)
    # Inserindo linhas cell by cell.
    contrato = "CONTRATO E COMPROMISSO DE COMPRA E VENDA DE IMÓVEL"
    utxt1 = unicode(contrato, "UTF-8")
    stxt1 = utxt1.encode("iso-8859-1")
    pdf.cell(0, 10, stxt1, 1, 1, "C")
    pdf.ln(10)
    # Dados pessoais das partes interessadas

    pdf.set_font("Arial", "", 8)
    vendedor = (
        "PROMITENTE VENDEDOR: "
        + nomeVend
        + ", nascido em "
        + naturalidadeVend
        + ", "
        + estadoCivilVend
        + ","
        + profissaoVend
        + ",portador do R.G. nº "
        + rgVend
        + " ,"
    )
    vendedor += (
        "  e CPF/MF nº "
        + cpfVend
        + " residente e domiciliado à "
        + ruaVend
        + ", "
        + numVend
        + ", "
        + bairroVend
        + ", "
        + cepVend
        + ", "
        + cidadeVend
        + ", "
        + estadoVend
        + "."
    )
    utxt2 = unicode(vendedor, "UTF-8")
    stxt2 = utxt2.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt2, 0, "J")
    pdf.ln(1)

    comprador = (
        "PROMITENTE COMPRADOR: "
        + nomeComp
        + ", "
        + naturalidadeComp
        + ", "
        + estadoCivilComp
        + ", "
        + profissaoComp
        + ", portador do R.G. nº "
        + rgComp
        + ","
    )
    comprador += (
        " e CPF/MF nº "
        + cpfComp
        + " residente e domiciliado à "
        + ruaComp
        + ", "
        + numComp
        + ", "
        + bairroComp
        + ", "
        + cepComp
        + ", "
        + cidadeComp
        + ", "
        + estado
        + "."
    )
    utxt3 = unicode(comprador, "UTF-8")
    stxt3 = utxt3.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt3, 0, "J")
    pdf.ln(5)

    pdf.set_font("Arial", "B", 10)
    clausulas = "Têm entre os mesmos, de maneira justa e acordada, o presente contrato particular de compromisso de compra e venda de bem imóvel, ficando desde já aceito, pelas cláusulas abaixo descritas:"
    utxt4 = unicode(clausulas, "UTF-8")
    stxt4 = utxt4.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt4, 0, "J")
    pdf.ln(3)

    pdf.set_font("Arial", "", 8)
    pdf.ln(1)
    primeira = "CLÁUSULA PRIMEIRA:"
    utxt5 = unicode(primeira, "UTF-8")
    stxt5 = utxt5.encode("iso-8859-1")
    pdf.cell(33, 5, stxt5, 1, 1, "L")
    pdf.ln(1)

    clausulaPrimeira = (
        "Que a PROMITENTE VENDEDORA é legítima possuidora do imóvel composto por área privativa de "
        + area
        + " metros quadrados, "
    )
    clausulaPrimeira += (
        "inscrito no livro de registro de imóveis sob nº " + registro + ", com as seguintes confrontações:"
    )
    utxt6 = unicode(clausulaPrimeira, "UTF-8")
    stxt6 = utxt6.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt6, 0, "J")
    pdf.ln(2)

    segunta = "CLÁUSULA SEGUNDA:"
    utxt7 = unicode(segunta, "UTF-8")
    stxt7 = utxt7.encode("iso-8859-1")
    pdf.cell(33, 5, stxt7, 1, 1, "L")
    pdf.ln(1)

    clausulaSegunda = (
        "O valor da presente transação é feita pelo preço de R$ "
        + valor
        + ", que serão pagos de acordo com o que as partes acharem cabíveis."
    )
    utxt8 = unicode(clausulaSegunda, "UTF-8")
    stxt8 = utxt8.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt8, 0, "J")
    pdf.ln(2)

    terceira = "CLÁUSULA TERCEIRA:"
    utxt9 = unicode(terceira, "UTF-8")
    stxt9 = utxt9.encode("iso-8859-1")
    pdf.cell(33, 5, stxt9, 1, 1, "L")
    pdf.ln(1)

    clausulaTerceira = "Que o PROMITENTE VENDEDOR se compromete a entregar o imóvel livre e desembaraçado de todos os débitos até esta data, junto ao Agente Financeiro"
    clausulaTerceira += ", ficando daí a responsabilidade do PROMITENTE COMPRADORE o pagamento mensal da prestação."
    utxt10 = unicode(clausulaTerceira, "UTF-8")
    stxt10 = utxt10.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt10, 0, "J")
    pdf.ln(2)

    quarta = "CLÁUSULA QUARTA:"
    utxt11 = unicode(quarta, "UTF-8")
    stxt11 = utxt11.encode("iso-8859-1")
    pdf.cell(33, 5, stxt11, 1, 1, "L")
    pdf.ln(1)

    clausulaQuarta = "Fica acordado entre o PROMITENTE VENDEDOR e PROMITENTE COMPRADOR que o imóvel transacionado permanecerá em nome do PROMITENTE VENDEDOR por "
    clausulaQuarta += "prazo indeterminado, ficando o PROMITENTE VENDEDOR obrigado a apresentar os documentos necessários para transrência a partir do momento em que "
    clausulaQuarta += "o mesmo for notificado pelo PROMITENTE COMPRADOR a qualquer época. "
    utxt12 = unicode(clausulaQuarta, "UTF-8")
    stxt12 = utxt12.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt12, 0, "J")
    pdf.ln(2)

    quinta = "CLÁUSULA QUINTA:"
    utxt13 = unicode(quinta, "UTF-8")
    stxt13 = utxt13.encode("iso-8859-1")
    pdf.cell(33, 5, stxt13, 1, 1, "L")
    pdf.ln(1)

    clausulaQuinta = "Todos os compromissos assumidos neste contrato são de caráter irrevogável e irrefratével, obrigado as partes, seus herdeiros e sucessores a qualquer"
    clausulaQuinta += "título fazer sempre boa e valiosa a presente cessão, ficando sujeito às penalidades da lei."
    utxt14 = unicode(clausulaQuinta, "UTF-8")
    stxt14 = utxt14.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt14, 0, "J")
    pdf.ln(2)

    sexta = "CLÁUSULA SEXTA:"
    utxt15 = unicode(sexta, "UTF-8")
    stxt15 = utxt15.encode("iso-8859-1")
    pdf.cell(33, 5, stxt15, 1, 1, "L")
    pdf.ln(1)

    clausulaSexta = "Fica ainda acordando, que caso haja necessidade de se beneficiar do seguro referente ao imóvel,os beneficiados será o PROMITENTE COMPRADOR,ou filhos."
    utxt16 = unicode(clausulaSexta, "UTF-8")
    stxt16 = utxt16.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt16, 0, "J")
    pdf.ln(2)

    setima = "CLÁUSULA SÉTIMA:"
    utxt17 = unicode(setima, "UTF-8")
    stxt17 = utxt17.encode("iso-8859-1")
    pdf.cell(33, 5, stxt17, 1, 1, "L")
    pdf.ln(1)

    clausulaSetima = "Em caso de falecimento do PROMITENTE VENDEDOR ,fica acordando entre as partes que todo e qualquer benefício oriundo deste fato,transfere-se"
    clausulaSetima += "para o PROMITENTE COMPRADOR."
    utxt18 = unicode(clausulaSetima, "UTF-8")
    stxt18 = utxt18.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt18, 0, "J")
    pdf.ln(2)

    oitava = "CLÁUSULA OITAVA:"
    utxt19 = unicode(oitava, "UTF-8")
    stxt19 = utxt19.encode("iso-8859-1")
    pdf.cell(33, 5, stxt19, 1, 1, "L")
    pdf.ln(1)

    clausulaOitava = "Caso haja manifestação pública por parte do Agente Financeiro, quando à transferência do imóvel citado neste instrumento particular de compra"
    clausulaOitava += "venda, sem que haja o aumento das prestações fica acordo entre as partes a sua transferência."
    utxt20 = unicode(clausulaOitava, "UTF-8")
    stxt20 = utxt20.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt20, 0, "J")
    pdf.ln(2)

    nona = "CLÁUSULA NONA:"
    utxt21 = unicode(nona, "UTF-8")
    stxt21 = utxt21.encode("iso-8859-1")
    pdf.cell(33, 5, stxt21, 1, 1, "L")
    pdf.ln(1)

    clausulaNona = "O foro deste contrato é da Comarca de, renunciando as partes quaisquer outro por mais privilegiado que seja.E por estarem assim  juntos e"
    clausulaNona += (
        "contra  assinam o presente em 03 (Três) vias de igual teor e forma, na presença das testemunhas abaixo."
    )
    utxt22 = unicode(clausulaNona, "UTF-8")
    stxt22 = utxt22.encode("iso-8859-1")
    pdf.multi_cell(0, 5, stxt22, 0, "J")
    pdf.ln(3)

    pdf.cell(0, 10, "____________________________________________   _____ , _____ , _________", 0, 1, "C")
    pdf.ln(10)

    pdf.cell(0, 5, "PROMITENTE COMPRADOR:", 0, 1, "C")
    pdf.cell(0, 5, "__________________________________________________", 0, 1, "C")
    pdf.cell(0, 5, "PROMITENTE VENDEDOR:", 0, 1, "C")
    pdf.cell(0, 5, "__________________________________________________", 0, 1, "C")
    pdf.cell(0, 5, "TESTEMUNHA:", 0, 1, "C")
    pdf.cell(0, 5, "__________________________________________________", 0, 1, "C")
    pdf.cell(0, 5, "R.G.:", 0, 1, "C")
    pdf.cell(0, 5, "__________________________________________________", 0, 1, "C")
    pdf.cell(0, 5, "TESTEMUNHA:", 0, 1, "C")
    pdf.cell(0, 5, "__________________________________________________", 0, 1, "C")
    pdf.cell(0, 5, "R.G.:", 0, 1, "C")
    pdf.cell(0, 5, "__________________________________________________", 0, 1, "C")

    pdf.output("numero%s.pdf" % (registro), "F")
Example #24
0
def createPDF(hospital_name, doctor_name, doctor_address, patient_name,
              patient_age, patient_gender, symptoms, diseases, prescriptions,
              advice):
    pdf = FPDF()
    pdf.add_page()
    #pdf.set_draw_color(70,225,250)
    pdf.set_line_width(2)
    pdf.rect(10, 10, 190, 275)
    #pdf.set_text_color(70,225,250)
    pdf.set_font("Helvetica", style="I", size=40)
    pdf.cell(200, 20, txt=hospital_name, ln=1, align="C")
    pdf.set_font("Arial", size=20)
    pdf.cell(200, 10, txt=doctor_name, ln=1, align="C")
    pdf.set_font("Arial", size=12)
    pdf.multi_cell(200, 5, txt=doctor_address, align="C")
    pdf.set_line_width(0.5)
    pdf.line(60, 60, 160, 60)
    pdf.ln(10)
    pdf.set_left_margin(20)
    pdf.set_font("Arial", size=15)
    pdf.cell(300, 5.5, txt="Patient's Name:  " + patient_name, ln=1)
    pdf.cell(300, 5.5, txt="Age:  " + patient_age, ln=1)
    pdf.cell(300, 5.5, txt="Sex:  " + patient_gender, ln=1)
    pdf.cell(300, 5.5, txt="Date: " + date, ln=1)
    pdf.ln(7)
    pdf.set_font("Arial", size=20)
    pdf.cell(300, 7, txt="Symptoms", ln=1)
    pdf.ln(3)
    pdf.set_left_margin(40)
    pdf.set_font("Arial", size=15)
    pdf.multi_cell(200, 6, txt=symptoms)

    pdf.ln(3)
    pdf.set_left_margin(20)
    pdf.cell(300, 1, txt="", ln=1)
    pdf.ln(3)
    pdf.set_left_margin(20)
    pdf.set_font("Arial", size=20)
    pdf.cell(300, 1, txt="Diagnosis", ln=1)
    pdf.ln(5)
    pdf.set_left_margin(40)
    pdf.set_font("Arial", size=15)
    pdf.multi_cell(200, 6, txt=diseases)

    pdf.ln(3)
    pdf.set_left_margin(20)
    pdf.cell(300, 1, txt="", ln=1)
    pdf.ln(3)
    pdf.set_left_margin(20)
    pdf.set_font("Arial", size=20)
    pdf.cell(300, 1, txt="Prescription", ln=1)
    pdf.ln(5)
    pdf.set_left_margin(40)
    pdf.set_font("Arial", size=15)
    pdf.multi_cell(200, 6, txt=prescriptions)

    pdf.ln(3)
    pdf.set_left_margin(20)
    pdf.cell(300, 1, txt="", ln=1)
    pdf.ln(3)
    pdf.set_left_margin(20)
    pdf.set_font("Arial", size=20)
    pdf.cell(300, 1, txt="Advice", ln=1)
    pdf.ln(5)
    pdf.set_left_margin(40)
    pdf.set_font("Arial", size=15)
    pdf.multi_cell(200, 6, txt=advice)
    temp_list = doctor_name.split()
    folder_name = "".join(temp_list)

    if not os.path.exists("static/" + folder_name):
        os.makedirs("static/" + folder_name)

    temp_list = patient_name.split()
    file_name = "".join(temp_list)
    month = datetime.now().month
    month = str(month)
    year = datetime.now().year
    year = str(year)
    day = datetime.now().day
    day = str(day)
    hour = datetime.now().hour
    hour = str(hour)
    minutes = datetime.now().minute
    minutes = str(minutes)
    seconds = datetime.now().second
    seconds = str(seconds)

    time_stamp = year + "_" + month + "_" + day + "_" + hour + "_" + minutes + "_" + seconds + "_file"
    file_name += time_stamp

    path = "static/" + folder_name + "/" + file_name + ".pdf"
    pdf.output(path)
    return path
Example #25
0
    pdf.set_fill_color(0, 0, 0)
    pdf.ellipse(x - 15, y - 15, 30, 30)
    pdf.ellipse(x - 5, y - 5, 10, 10, 'F')
    pdf.set_fill_color(255, 255, 255)
    pdf.ellipse(x - 1.5, y - 1.5, 3, 3, 'F')


# Begin a pdf in landscape orientation, units of mm, and letter size paper
pdf = FPDF(orientation="L", unit="mm", format="letter")

# Create a new page a print a title
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200,
         10,
         txt="Standard Japanese Arcade Layout, Letter Size",
         ln=1,
         align="C")

# draw joystick hole
drawButtonHole(pdf, joystick_pos_x, joystick_pos_y)

# bottom row, leftmost button
draw_b1_x = joystick_pos_x + 59
draw_b1_y = joystick_pos_y + 14
drawButtonHole(pdf, draw_b1_x, draw_b1_y)

# top row, leftmost button
draw_t1_x = draw_b1_x + 7
draw_t1_y = draw_b1_y - 38.5
drawButtonHole(pdf, draw_t1_x, draw_t1_y)
Example #26
0
            continue
        if len(mail) > 0 and '@' not in mail:
            print('Discarding [' + (';'.join(row)) + ']: incorrect e-mail',
                  file=sys.stderr)
            continue
        if len(mail) > 0:
            emails.append(mail)
            continue
        if not repc.search(addr):
            print('Discarding [' + (';'.join(row)) +
                  ']: incorrect postal code',
                  file=sys.stderr)
            continue
        pdf.add_page()
        pdf.set_font('Arial', 'B', 16)
        pdf.cell(190, 5, 'Association France Parkinson', b, 1)
        pdf.set_font('Arial', '', 12)
        pdf.cell(190, 5, 'Comité de Haute-Garonne', b, 1)
        pdf.set_font('Times', '', 11)

        pdf.cell(190, 25, '', b, 1)

        pdf.cell(90, 5, '', b, 0)
        pdf.cell(100, 5, name, b, 1)
        third = 45
        if len(moar) > 0:
            pdf.cell(90, 5, '', b, 0)
            pdf.cell(100, 5, moar, b, 1)
            third -= 5
        lines = addr.split('#')
        for ln in lines:
Example #27
0
import pygame
import pygame.camera

pygame.camera.init()

cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")

from fpdf import FPDF

pdf = FPDF('P', 'mm', (100, 150))
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
pdf.cell(40, 5, 'MATTHIAS & CELINE')
pdf.image(name="filename.jpg", x =5, y = 20, w = 90, h = 70, link = 'filename.jpg')

pdf.output('tuto1.pdf', 'F')


import subprocess
print (subprocess.check_output(['lp','tuto1.pdf']))
Example #28
0
            def create_pdf2(self):
                # Set up a logo
                conn = sqlite3.connect("db_member.db")
                conn.row_factory = sqlite3.Row
                cur = conn.cursor()
                cur.execute("SELECT max(id) FROM member")
                rows = cur.fetchall()
                for row in rows:
                    print("%s" % (row["max(id)"]))

                cur2 = conn.cursor()
                cur2.execute("SELECT name_pk FROM print_dt")
                cur3 = conn.cursor()
                cur3.execute("SELECT address FROM print_dt")
                cur4 = conn.cursor()
                cur4.execute("SELECT dt_name FROM print_dt")
                cur5 = conn.cursor()
                cur5.execute("SELECT * FROM `member`")

                rows5 = cur5.fetchall()
                rows4 = cur4.fetchall()
                rows3 = cur3.fetchall()
                rows2 = cur2.fetchall()

                for row5 in rows5:
                    row5[6]
                for row2 in rows2:
                    row2["name_pk"]

                for row3 in rows3:
                    row3["address"]

                for row4 in rows4:
                    row4["dt_name"]



                t = row2["name_pk"]
                t1 = row3["address"]
                t2 = "BS: " + row4["dt_name"]

                pdf = FPDF()
                pdf.set_font("Arial", size=12)
                pdf.add_page()

                pdf.image('demo.png', 8, 10, 25)
                pdf.add_font('DejaVu', '', 'DejaVuSerif-Italic.ttf', uni=True)
                pdf.set_font('DejaVu', '', 16)
                pdf.set_text_color(0, 70, 255)
                pdf.cell(35)
                pdf.cell(0, 5, t, ln=1)
                pdf.set_font('DejaVu', '', 14)

                pdf.cell(70)
                pdf.cell(0, 10, t2, ln=1)
                pdf.set_font('DejaVu', '', 14)
                pdf.set_text_color(0, 70, 255)
                pdf.cell(30)

                pdf.cell(0, 0, "ĐC:", ln=1)
                pdf.set_font('DejaVu', '', 12)
                pdf.set_text_color(0, 0, 0)
                pdf.cell(40)
                pdf.cell(0, 0, t1, ln=1)
                pdf.set_draw_color(0, 0, 0)
                pdf.set_line_width(1)
                pdf.line(30, 30, 180, 30)

                pdf.set_font('DejaVu', '', 16)
                pdf.set_text_color(255, 0, 40)
                pdf.cell(35)
                pdf.cell(0, 5, ' ', ln=1)

                pdf.set_font('DejaVu', '', 16)
                pdf.set_text_color(255, 0, 40)
                pdf.cell(35)
                pdf.cell(0, 15, 'PHIẾU KHÁM NỘI SOI TAI-MŨI-HỌNG', ln=1)

                pdf.set_font('DejaVu', '', 12)
                pdf.set_text_color(0, 70, 255)
                pdf.cell(75)
                pdf.cell(0, 0, 'Số Phiếu : ' + str(row5[0]), ln=1)

                pdf.set_font('DejaVu', '', 16)
                pdf.set_text_color(0, 70, 255)
                pdf.cell(0, 8, ' ', ln=1)

                pdf.set_font('DejaVu', '', 10)
                pdf.cell(5)
                pdf.cell(0, 0, 'Tên bệnh nhân : ' + str(row5[1]), ln=1)
                pdf.cell(85)
                pdf.cell(0, 0, 'Tuổi : ' + str(row5[4]), ln=1)
                pdf.cell(135)
                pdf.cell(0, 0, 'Giới tính : ' + str(row5[6]), ln=1)

                pdf.set_font('DejaVu', '', 10)
                pdf.set_text_color(0, 70, 255)
                pdf.cell(0, 8, ' ', ln=1)
                pdf.cell(5)
                pdf.cell(0, 0, 'Địa chỉ : ' + str(row5[3]), ln=1)
                pdf.cell(85)
                pdf.cell(0, 0, 'Số bảo hiểm : ' + str(row5[7]), ln=1)
                pdf.cell(135)
                pdf.cell(0, 0, 'Nghề nghiệp : ' + str(row5[2]), ln=1)

                pdf.set_font('DejaVu', '', 10)
                pdf.set_text_color(0, 70, 255)
                pdf.cell(0, 8, ' ', ln=1)
                pdf.cell(5)
                pdf.cell(0, 0, 'Triệu chứng : ' + str(row5[5]), ln=1)
                pdf.cell(85)
                pdf.cell(0, 0, 'Điện thoại: ' + str(row5[8]), ln=1)

                pdf.set_font('DejaVu', '', 14)
                pdf.cell(0, 15, ' ', ln=1)
                pdf.cell(70)
                pdf.cell(0, 0, 'HÌNH ẢNH NỘI SOI ', ln=1)
                #
                file_name =  ('anh\%s.png' % ("a" + str(row["max(id)"]) + "a" + str(2)))
                file_name1 = ('anh\%s.png' % ("a" + str(row["max(id)"]) + "a" + str(3)))
                file_name2 = ('anh\%s.png' % ("a" + str(row["max(id)"]) + "a" + str(4)))
                file_name3 = ('anh\%s.png' % ("a" + str(row["max(id)"]) + "a" + str(5)))
                file_name4 = ('anh\%s.png' % ("a" + str(row["max(id)"]) + "a" + str(6)))
                file_name5 = ('anh\%s.png' % ("a" + str(row["max(id)"]) + "a" + str(7)))
                #
                pdf.image(file_name, 12, 90, 60)
                pdf.image(file_name1, 12, 150, 60)
                pdf.image(file_name2, 74, 90, 60)
                pdf.image(file_name3, 74, 150, 60)
                pdf.image(file_name4, 136, 90, 60)
                pdf.image(file_name5, 136, 150, 60)

                pdf.set_font('DejaVu', '', 16)
                pdf.cell(0, 132, ' ', ln=1)
                pdf.cell(60)
                pdf.cell(0, 0, 'MÔ TẢ KẾT QUẢ NỘI SOI ', ln=1)
                pdf.set_font('DejaVu', '', 12)
                pdf.cell(0, 8, ' ', ln=1)
                pdf.cell(12)
                pdf.cell(0, 7, 'Chẩn đoán : ', ln=1)
                pdf.cell(12)
                pdf.cell(0, 7, 'Điều trị : ', ln=1)
                pdf.cell(12)
                pdf.cell(0, 7, 'Chỉ định bác sĩ : ', ln=1)

                pdf.set_x(120)
                pdf.cell(0, 10, " Ngày " + str(today.day) + " Tháng " + str(today.month) + " Năm " + str(today.year),
                         ln=1)
                pdf.set_x(145)
                pdf.cell(0, 6, 'Bác sĩ : ', ln=1)
                pdf.cell(0, 15, ' ', ln=1)
                pdf.set_x(126)
                pdf.cell(0, 0, t2, ln=1)
                directory1 = "doccument/"
                if not os.path.exists(directory1):
                    os.makedirs(directory1)
                pdf.output('doccument\%s.pdf' %("a" + str(row["max(id)"])))
                webbrowser.open_new(r'doccument\%s.pdf' %("a" + str(row["max(id)"])))
                conn.commit()
                cur.close()
Example #29
0
def genallpdf(request):  # grnerate pdf for show all section data.
    allTeach = Teach.objects.all()
    allsection = Section.objects.all()

    ListSec = [
    ]  # collect teacher each sectoin because a section has more than a teacher.
    for sec in allsection:  # collecting teacher to each section.
        eachSec = []
        for teach in allTeach:
            if teach.section == sec:
                eachSec.append(teach)
        ListSec.append(eachSec)

    pdf = FPDF('L', 'mm', 'A4')  # start pdf 'L' is landscape.
    pdf.add_page()

    pdf.add_font('Kinnari', '', 'Kinnari.ttf', uni=True)
    pdf.set_font('Kinnari', '', 8)

    ganY = [10, 18]
    drawAttr(pdf, ganY[0], ganY[1], True)  # call to draw table
    pdf.cell(
        0, ganY[0],
        u'ลำดับ              ชื่อ-สกุล                    ตัวย่อ    รหัสวิชา                ชื่อวิชา                      ตอนเรียน  วัน       เวลา       ห้องเรียน  เบอร์โทรศัพท์                   Email                  บ-ช สหกรณ์      หมายเหตุ    '
    )
    pdf.ln(4)  # width:298 height:210

    cnt_no = 0  # use to fill in number column.
    cnt_line = 0  # use to calculate next line to draw row of table.
    for sec in ListSec:  # drawing table
        cnt_no += 1
        no = str(cnt_no)
        # write no.
        for Prof in sec:  # access all teacher in each section
            cnt_line += 1
            try:
                first_name = Prof.prof.firstName
                last_name = Prof.prof.lastName
                full_name = first_name + '  ' + last_name
            except:
                full_name = 'None'

            try:
                shortname = Prof.prof.shortName
            except:
                shortname = 'None'

            try:
                subjectID = Prof.subject.subjectID
            except:
                subjectID = 'None'

            try:
                subject = Prof.subject.subjectName
            except:
                subject = 'None'

            try:
                section = Prof.section.section
            except:
                section = " "

            try:
                day = Prof.section.date
            except:
                day = ' '

            try:
                starttime = Prof.section.startTime
            except:
                starttime = 'None'

            try:
                room = Prof.section.classroom
            except:
                room = 'None'

            try:
                phone_num = Prof.prof.tell
            except:
                phone_num = 'None'

            try:
                email = Prof.prof.email
            except:
                email = 'None'

            try:
                sahakorn = Prof.prof.sahakornAccount
            except:
                sahakorn = 'None'

            pdf.cell(8, 18, no)
            pdf.cell(45, 18, full_name)
            pdf.cell(8, 18, shortname)
            pdf.cell(17, 18, subjectID)
            pdf.cell(45, 18, subject)
            pdf.cell(12, 18, section)
            pdf.cell(7, 18, day)
            pdf.cell(17, 18, str(starttime))
            pdf.cell(12, 18, room)
            pdf.cell(19, 18, phone_num)
            pdf.cell(43, 18, email)
            pdf.cell(29, 18, sahakorn)

            pdf.ln(8)
            if cnt_line % 16 == 0:  # check for new pae. I set maximun 16 teachers per a page.
                drawAttr(pdf, ganY[0] + (cnt_line * 8),
                         ganY[1] + (cnt_line * 8), True)
            else:
                drawAttr(pdf, ganY[0] + (cnt_line * 8),
                         ganY[1] + (cnt_line * 8))
            no = ''

    pdf.ln(8)
    pdf.cell(230, 18, '')
    pdf.cell(230, 18, u'ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์ ')
    pdf.ln(8)
    pdf.cell(240, 18, '')
    pdf.cell(240, 18, u'คณะวิศวกรรมศาสตร์ ')
    pdf.ln(8)
    pdf.output("group3/allTeach.pdf", 'F')

    with open('group3/allTeach.pdf',
              'rb') as pdf:  # use to call pdf page in browser.
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'filename=allTeach.pdf'
        return response
    pdf.closed
Example #30
0
]

total_price = 0

# IMPORT PDF EDITOR
from fpdf import FPDF

# CREATE NEW PDF AND ADD A PAGE
pdf = FPDF()
pdf.add_page()

# SET FONT TO HEADER SIZE
pdf.set_font('Arial', 'B', 16)

# PRINT A HEADER
pdf.cell(40, 10, 'Sannas kvitto', 0, 1)

# SET FONT TO NORMAL SIZE
pdf.set_font('Arial', '', 12)

for product in products:
    print("Produkt: {:10} Antal: {:<10} Pris: {:>7} kr".format(
        product.name, product.count, product.price_with_tax()))
    # ADD THE SAME LINE TO THE PDF FILE
    pdf.cell(
        40, 10, "Produkt: {:10} Antal: {:<10} Pris: {:>7} kr".format(
            product.name, product.count, product.price_with_tax()), 0, 1)

print("-" * 80)  # streckad linje

# ADD THE STRECKAD LINJE TO THE PDF AS WELL
Example #31
0
def draw_daily_table(*, date: datetime.date, foods_list: list,
                     pdf_object: FPDF, current_timezone: str) -> dict:
    if len(foods_list) == 0:
        return {}
    week_days = [
        'понедельник',
        'вторник',
        'среда',
        'четверг',
        'пятница',
        'суббота',
        'воскресенье',
    ]
    pdf_object.set_font('FreeSans', size=14)
    pdf_object.set_text_color(255, 255, 255)
    pdf_object.set_fill_color(12, 82, 130)
    pdf_object.cell(190,
                    12,
                    txt=f'{date} ({week_days[date.isoweekday() - 1]})',
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.ln(12)
    pdf_object.set_font('FreeSans', size=7)
    pdf_object.cell(15, 6, txt=f'Время', border=1, align='C', fill=1)
    pdf_object.cell(82, 6, txt=f"Наименование", border=1, align='C', fill=1)
    pdf_object.cell(11, 6, txt=f"Белки", border=1, align='C', fill=1)
    pdf_object.cell(11, 6, txt=f"% белков", border=1, align='C', fill=1)
    pdf_object.cell(11, 6, txt=f"Жиры", border=1, align='C', fill=1)
    pdf_object.cell(11, 6, txt=f"% жиров", border=1, align='C', fill=1)
    pdf_object.cell(11, 6, txt=f"Углев", border=1, align='C', fill=1)
    pdf_object.cell(11, 6, txt=f"% углев", border=1, align='C', fill=1)
    pdf_object.cell(11, 6, txt=f"Сахар", border=1, align='C', fill=1)
    pdf_object.cell(16, 6, txt=f"Калории", border=1, align='C', fill=1)
    pdf_object.ln(6)
    pdf_object.set_text_color(0, 0, 0)
    pdf_object.set_fill_color(246, 246, 246)
    pdf_object.set_font('FreeSans', size=10)
    row_height = 10
    day_calories = 0
    day_protein = 0
    day_fat = 0
    day_sugar = 0
    day_carbohydrates = 0

    for food in foods_list:
        nutrition_dict = food['foods']
        food_calories = 0
        food_protein = 0
        food_fat = 0
        food_carbohydrates = 0
        food_sugar = 0
        food_time = dateutil.parser.parse(food['time'])
        food_time = food_time.replace(tzinfo=dateutil.tz.gettz('UTC')). \
            astimezone(dateutil.tz.gettz(current_timezone))
        for f in nutrition_dict['foods']:
            calories = f.get("nf_calories", 0) or 0
            food_calories += calories
            day_calories += calories
            protein = f.get("nf_protein", 0) or 0
            food_protein += protein
            day_protein += protein
            fat = f.get("nf_total_fat", 0) or 0
            food_fat += fat
            day_fat += fat
            carbohydrates = f.get("nf_total_carbohydrate", 0) or 0
            food_carbohydrates += carbohydrates
            day_carbohydrates += carbohydrates
            sugar = f.get("nf_sugars", 0) or 0
            food_sugar += sugar
            day_sugar += sugar
        food_total_nutritions = food_protein + food_fat + food_carbohydrates
        food_protein_percent = int((food_protein / food_total_nutritions) *
                                   100) if food_total_nutritions > 0 else 0
        food_fat_percent = int((food_fat / food_total_nutritions) *
                               100) if food_total_nutritions > 0 else 0
        food_carbohydrates_percent = int((food_carbohydrates / food_total_nutritions) * 100) if \
            food_total_nutritions > 0 else 0
        pdf_object.set_fill_color(246, 246, 246)
        pdf_object.cell(15,
                        row_height,
                        txt=f'{food_time.strftime("%H:%M")}',
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.set_fill_color(255, 255, 255)
        if len(food['utterance']) > 44:
            pdf_object.set_font('FreeSans', size=8)
        pdf_object.cell(82,
                        row_height,
                        txt=f" {food['utterance']}",
                        border=1,
                        align='L',
                        fill=1)
        pdf_object.set_font('FreeSans', size=10)
        pdf_object.set_fill_color(246, 246, 246)
        pdf_object.cell(11,
                        row_height,
                        txt=f"{int(food_protein)}",
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.set_fill_color(255, 255, 255)
        pdf_object.cell(11,
                        row_height,
                        txt=f"{food_protein_percent}%",
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.set_fill_color(246, 246, 246)
        pdf_object.cell(11,
                        row_height,
                        txt=f"{int(food_fat)}",
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.set_fill_color(255, 255, 255)
        pdf_object.cell(11,
                        row_height,
                        txt=f"{food_fat_percent}%",
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.set_fill_color(246, 246, 246)
        pdf_object.cell(11,
                        row_height,
                        txt=f"{int(food_carbohydrates)}",
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.set_fill_color(255, 255, 255)
        pdf_object.cell(11,
                        row_height,
                        txt=f"{food_carbohydrates_percent}%",
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.set_fill_color(246, 246, 246)
        pdf_object.cell(11,
                        row_height,
                        txt=f"{int(food_sugar)}",
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.set_fill_color(255, 255, 255)
        pdf_object.cell(16,
                        row_height,
                        txt=f"{int(food_calories)}",
                        border=1,
                        align='C',
                        fill=1)
        pdf_object.ln(row_height)
        print(food_time.strftime('%H:%M'), food['utterance'],
              int(food_protein),
              str(food_protein_percent) + '%', int(food_fat),
              str(food_fat_percent) + '%', int(food_carbohydrates),
              str(food_carbohydrates_percent) + '%', food_calories)
    day_total_nutritions = day_protein + day_fat + day_carbohydrates
    day_protein_percent = int((day_protein / day_total_nutritions) *
                              100) if day_total_nutritions > 0 else 0
    day_fat_percent = int((day_fat / day_total_nutritions) *
                          100) if day_total_nutritions > 0 else 0
    day_carbohydrates_percent = int((day_carbohydrates / day_total_nutritions) * 100) if \
        day_total_nutritions > 0 else 0
    pdf_object.set_fill_color(99, 210, 255)
    # pdf_object.set_fill_color(255, 255, 255)

    pdf_object.cell(97,
                    row_height,
                    txt=f'Итого: {round(day_calories, 2)} калорий',
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.set_fill_color(89, 200, 245)
    pdf_object.cell(11,
                    row_height,
                    txt=f"{int(day_protein)}",
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.set_fill_color(99, 210, 255)
    pdf_object.cell(11,
                    row_height,
                    txt=f"{day_protein_percent}%",
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.set_fill_color(89, 200, 245)
    pdf_object.cell(11,
                    row_height,
                    txt=f"{int(day_fat)}",
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.set_fill_color(99, 210, 255)
    pdf_object.cell(11,
                    row_height,
                    txt=f"{day_fat_percent}%",
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.set_fill_color(89, 200, 245)
    pdf_object.cell(11,
                    row_height,
                    txt=f"{int(day_carbohydrates)}",
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.set_fill_color(99, 210, 255)
    pdf_object.cell(11,
                    row_height,
                    txt=f"{day_carbohydrates_percent}%",
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.set_fill_color(89, 200, 245)
    pdf_object.cell(11,
                    row_height,
                    txt=f"{int(day_sugar)}",
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.set_fill_color(99, 210, 255)
    pdf_object.set_font('FreeSans', size=14)
    pdf_object.cell(16,
                    row_height,
                    txt=f"{int(day_calories)}",
                    border=1,
                    align='C',
                    fill=1)
    pdf_object.ln(25)
    print(
        f'Итого за день: \t{int(day_protein)}({day_protein_percent}%)\t{int(day_fat)}({day_fat_percent}%)'
        f'\t{int(day_carbohydrates)}({day_carbohydrates_percent}%)\t{int(day_sugar)}\t{int(day_calories)}'
    )
Example #32
0
        def Add():
            mon = entry_1.get()
            monint = int(mon)
            yr = entry_2.get()
            yrint = int(yr)
            name = entry_3.get()
            conn = sqlite3.connect("myspendmate.db")
            df = pd.read_sql_query(
                "select * from income where month='%s' AND year='%s';" %
                (mon, yr),
                conn,
            )
            print(df)
            df1 = pd.read_sql_query(
                "select * from expense where month='%s' AND year='%s';" %
                (mon, yr),
                conn,
            )
            print(df1)

            np.random.seed(19680801)

            plt.rcdefaults()
            fig, ax = plt.subplots()

            dates = []
            income_cost = []
            print('monint')
            print(monint)
            if monint == 2:
                if (yrint % 4) == 0 and (yrint % 100) == 0 and (yrint %
                                                                400) == 0:
                    days_num = 28
                else:
                    days_num = 29
            elif monint == 1 or monint == 3 or monint == 5 or monint == 7 or monint == 8 or monint == 10 or monint == 12:
                days_num = 31
            elif monint == 4 or monint == 6 or monint == 9 or monint == 11:
                days_num = 30
                print('days are 30')
            print(days_num)
            for i in range(days_num):
                dates.append(i + 1)
            dates = tuple(dates)

            db = sqlite3.connect('myspendmate.db')
            cursor = db.cursor()
            for i in range(days_num):
                val = i + 1
                cursor.execute(
                    "select sum(amount) from income where day=? AND month=? AND year=?",
                    (val, mon, yr))
                total_income = cursor.fetchone()[0]
                if total_income == None:
                    total_income = 0
                income_cost.append(total_income)

            y_pos = np.arange(days_num)
            ax.barh(y_pos, income_cost, align='center', alpha=0.5)
            ax.set_yticks(y_pos)
            ax.set_yticklabels(dates)
            ax.invert_yaxis()
            ax.set_ylabel('Date')
            print(income_cost)
            ax.set_xlabel('Income')
            ax.set_title('Day Wise Income')
            plt.savefig('barincome.png', dpi=100)
            # plt.show()

            # ======================================================================================
            db = sqlite3.connect('myspendmate.db')
            cursor = db.cursor()
            cursor.execute(
                " select sum(amount) from income where month='%s' AND year='%s';"
                % (mon, yr))
            total_expense = cursor.fetchone()[0]
            if total_expense == None:
                total_expense = 0
            cursor.execute(
                "select * from income where month='%s' AND year='%s';" %
                (mon, yr))
            expense_list = cursor.fetchall()

            labels = []
            amt_expe = []
            sizes = []
            count = -1

            for i in expense_list:
                category = str(i[3])
                print("category " + str(category))
                amt_category = i[0]
                print("amt of category " + str(amt_category))
                if labels.count(category) == 0:
                    count += 1
                    labels.append(category)
                    amt_expe.append(amt_category)
                    sizes.append(float((amt_category * 100) / total_expense))
                else:
                    ppcount = labels.index(category)
                    amt_expe[ppcount] = amt_expe[ppcount] + amt_category
                    sizes[ppcount] = float(
                        (amt_expe[ppcount] * 100) / total_expense)

            tobe = sizes.index(max(sizes))
            print('tobe is : ' + str(tobe))
            explode = []
            for i in range(count + 1):
                if i == tobe:
                    explode.append(0.1)
                else:
                    explode.append(0)
            explode = tuple(explode)
            print('label ' + str(labels))
            print('amt ' + str(amt_expe))
            print('sizes ' + str(sizes))
            print('explode ' + str(explode))

            # Plot
            fig1, ax1 = plt.subplots()
            ax1.pie(sizes,
                    explode=explode,
                    labels=labels,
                    autopct='%1.1f%%',
                    shadow=True,
                    startangle=90)
            ax1.axis(
                'equal'
            )  # Equal aspect ratio ensures that pie is drawn as a circle.
            ax1.set_title('Category Wise Analysis of Income')
            plt.savefig('pieincome.png', dpi=100)
            # plt.show()
            # ==========================================================================================

            db = sqlite3.connect('myspendmate.db')
            cursor = db.cursor()
            cursor.execute(
                " select sum(amount) from expense where month='%s' AND year='%s';"
                % (mon, yr))
            total_expense = cursor.fetchone()[0]
            if total_expense == None:
                total_expense = 0
            cursor.execute(
                "select * from expense where month='%s' AND year='%s';" %
                (mon, yr))
            expense_list = cursor.fetchall()

            labels = []
            amt_expe = []
            sizes = []
            count = -1

            for i in expense_list:
                category = str(i[3])
                print("category " + str(category))
                amt_category = i[0]
                print("amt of category " + str(amt_category))
                if labels.count(category) == 0:
                    count += 1
                    labels.append(category)
                    amt_expe.append(amt_category)
                    sizes.append(float((amt_category * 100) / total_expense))
                else:
                    ppcount = labels.index(category)
                    amt_expe[ppcount] = amt_expe[ppcount] + amt_category
                    sizes[ppcount] = float(
                        (amt_expe[ppcount] * 100) / total_expense)

            tobe = sizes.index(max(sizes))
            print('tobe is : ' + str(tobe))
            explode = []
            for i in range(count + 1):
                if i == tobe:
                    explode.append(0.1)
                else:
                    explode.append(0)
            explode = tuple(explode)
            print('label ' + str(labels))
            print('amt ' + str(amt_expe))
            print('sizes ' + str(sizes))
            print('explode ' + str(explode))

            # Plot
            fig1, ax1 = plt.subplots()
            ax1.pie(sizes,
                    explode=explode,
                    labels=labels,
                    autopct='%1.1f%%',
                    shadow=True,
                    startangle=90)
            ax1.axis(
                'equal'
            )  # Equal aspect ratio ensures that pie is drawn as a circle.
            ax1.set_title('Category Wise Analysis of Expense')
            plt.savefig('pieexpense.png', dpi=100)
            # plt.show()

            # ==================================================================================

            plt.rcdefaults()
            fig, ax = plt.subplots()

            dates = []
            expense_cost = []
            print('days')
            print(days_num)
            for i in range(days_num):
                dates.append(i + 1)
            dates = tuple(dates)

            db = sqlite3.connect('myspendmate.db')
            cursor = db.cursor()
            for i in range(days_num):
                val = i + 1
                cursor.execute(
                    "select sum(amount) from expense where day=? AND month=? AND year=?",
                    (val, mon, yr))
                total_income = cursor.fetchone()[0]
                if total_income == None:
                    total_income = 0
                expense_cost.append(total_income)

            y_pos = np.arange(days_num)
            ax.barh(y_pos, expense_cost, align='center', alpha=0.5)
            ax.set_yticks(y_pos)
            ax.set_yticklabels(dates)
            ax.invert_yaxis()
            ax.set_ylabel('Date')
            ax.set_xlabel('Expense')
            ax.set_title('Day Wise Expense')
            plt.savefig('barexpense.png', dpi=100)
            # plt.show()
            # =========================================================================================

            mon_name = [
                'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
                'Oct', 'Nov', 'Dec'
            ]

            # ==========================================================================================
            pdf = FPDF()
            pdf.add_page()
            pdf.set_xy(0, 0)
            pdf.set_font('arial', 'B', 12)
            pdf.cell(60)
            pdf.cell(75, 10, " ", 0, 2, 'C')
            pdf.cell(90, 3, " ", 0, 2, 'C')
            pdf.cell(75, 10, "SpendMate - Your Money Manager", 0, 2, 'C')
            pdf.cell(90, 3, " ", 0, 2, 'C')
            pdf.cell(
                75, 10, "A Tabular and Graphical Report of Income for " +
                str(mon_name[int(mon) - 1]) + " " + str(yr), 0, 2, 'C')
            pdf.cell(90, 5, " ", 0, 2, 'C')
            pdf.cell(-40)
            pdf.cell(20, 10, 'amount', 1, 0, 'C')
            pdf.cell(30, 10, 'date', 1, 0, 'C')
            pdf.cell(75, 10, 'description', 1, 0, 'C')
            pdf.cell(30, 10, 'category', 1, 0, 'C')
            pdf.cell(30, 10, 'account_type', 1, 2, 'C')
            pdf.cell(-155)
            pdf.set_font('arial', '', 12)
            for i in range(0, len(df)):
                pdf.cell(20, 10, '%s' % (df['amount'].iloc[i]), 1, 0, 'C')
                pdf.cell(30, 10, '%s' % (str(df.date.iloc[i])), 1, 0, 'C')
                pdf.cell(75, 10, '%s' % (str(df.description.iloc[i])), 1, 0,
                         'C')
                pdf.cell(30, 10, '%s' % (str(df.category.iloc[i])), 1, 0, 'C')
                pdf.cell(30, 10, '%s' % (str(df.account_type.iloc[i])), 1, 2,
                         'C')
                pdf.cell(-155)
            pdf.cell(90, 10, " ", 0, 2, 'C')
            pdf.cell(-20)
            pdf.image('pieincome.png',
                      x=None,
                      y=None,
                      w=0,
                      h=0,
                      type='',
                      link='')
            pdf.cell(90, 10, " ", 0, 2, 'C')
            pdf.cell(-5)
            pdf.image('barincome.png',
                      x=None,
                      y=None,
                      w=0,
                      h=0,
                      type='',
                      link='')
            # ======================================================================================

            pdf.add_page()
            pdf.set_font('arial', 'B', 12)
            pdf.cell(45)
            pdf.cell(90, 3, " ", 0, 2, 'C')
            pdf.cell(
                75, 10, "A Tabular and Graphical Report of Expense for " +
                str(mon_name[int(mon) - 1]) + " " + str(yr), 0, 2, 'C')
            pdf.cell(90, 5, " ", 0, 2, 'C')
            pdf.cell(-40)
            pdf.cell(20, 10, 'amount', 1, 0, 'C')
            pdf.cell(30, 10, 'date', 1, 0, 'C')
            pdf.cell(75, 10, 'description', 1, 0, 'C')
            pdf.cell(30, 10, 'category', 1, 0, 'C')
            pdf.cell(30, 10, 'account_type', 1, 2, 'C')
            pdf.cell(-155)
            pdf.set_font('arial', '', 12)
            for i in range(0, len(df1)):
                pdf.cell(20, 10, '%s' % (df1['amount'].iloc[i]), 1, 0, 'C')
                pdf.cell(30, 10, '%s' % (str(df1.date.iloc[i])), 1, 0, 'C')
                pdf.cell(75, 10, '%s' % (str(df1.description.iloc[i])), 1, 0,
                         'C')
                pdf.cell(30, 10, '%s' % (str(df1.category.iloc[i])), 1, 0, 'C')
                pdf.cell(30, 10, '%s' % (str(df1.account_type.iloc[i])), 1, 2,
                         'C')
                pdf.cell(-155)
            pdf.cell(90, 10, " ", 0, 2, 'C')
            pdf.cell(-20)
            pdf.image('pieexpense.png',
                      x=None,
                      y=None,
                      w=0,
                      h=0,
                      type='',
                      link='')
            pdf.cell(90, 10, " ", 0, 2, 'C')
            pdf.cell(-5)
            pdf.image('barexpense.png',
                      x=None,
                      y=None,
                      w=0,
                      h=0,
                      type='',
                      link='')
            print('name---------------------------' + str(name))
            pdf.output('{}.pdf'.format(name), 'F')
            messagebox.showinfo(
                "Success!!",
                "Your Report have been saved in Root Directory.\nCheck it out!!"
            )
            Acexit()
Example #33
0
    def pdfgenerator(self, df):
        # Todays date
        today = datetime.now(timezone.utc)
        now = datetime.now(timezone.utc)
        strtoday = today.strftime("%d.%m.%Y")
        df['real_datetime'] = pd.to_datetime(df['real_datetime'], utc=True)

        # variables
        minus1 = datetime.now(timezone.utc) - timedelta(days=1)
        minus7 = datetime.now(timezone.utc) - timedelta(days=7)
        minus31 = datetime.now(timezone.utc) - timedelta(days=31)
        minus365 = datetime.now(timezone.utc) - timedelta(days=365)

        # Counting different timeframes for the reporting tiles
        array_minus1_neg = df[(df.real_datetime > minus1)
                              & (df.real_datetime < now) &
                              (df.sentiment == 2)].count()
        array_minus7_neg = df[(df.real_datetime > minus7)
                              & (df.real_datetime < now) &
                              (df.sentiment == 2)].count()
        array_minus31_neg = df[(df.real_datetime > minus31)
                               & (df.real_datetime < now) &
                               (df.sentiment == 2)].count()
        array_minus365_neg = df[(df.real_datetime > minus365)
                                & (df.real_datetime < now) &
                                (df.sentiment == 2)].count()

        count_minus1_neg = array_minus1_neg[0]
        count_minus7_neg = array_minus7_neg[0]
        count_minus31_neg = array_minus31_neg[0]
        count_minus365_neg = array_minus365_neg[0]

        array_minus1_ges = df[(df.real_datetime > minus1)
                              & (df.real_datetime < now)].count()
        array_minus7_ges = df[(df.real_datetime > minus7)
                              & (df.real_datetime < now)].count()
        array_minus31_ges = df[(df.real_datetime > minus31)
                               & (df.real_datetime < now)].count()
        array_minus365_ges = df[(df.real_datetime > minus365)
                                & (df.real_datetime < now)].count()

        count_minus1_ges = array_minus1_ges[0]
        count_minus7_ges = array_minus7_ges[0]
        count_minus31_ges = array_minus31_ges[0]
        count_minus365_ges = array_minus365_ges[0]

        percent1 = round((count_minus1_neg / count_minus1_ges) * 100, 2)
        percent7 = round((count_minus7_neg / count_minus7_ges) * 100, 2)
        percent31 = round((count_minus31_neg / count_minus31_ges) * 100, 2)
        percent365 = round((count_minus365_neg / count_minus365_ges) * 100, 2)

        # Create strings for reporting tiles
        slash = '/'
        percent = '%'
        string_neg1 = str(count_minus1_neg)
        string_ges1 = str(count_minus1_ges)
        string1 = string_neg1 + slash + string_ges1
        string_neg7 = str(count_minus7_neg)
        string_ges7 = str(count_minus7_ges)
        string7 = string_neg7 + slash + string_ges7
        string_neg31 = str(count_minus31_neg)
        string_ges31 = str(count_minus31_ges)
        string31 = string_neg31 + slash + string_ges31
        string_neg365 = str(count_minus365_neg)
        string_ges365 = str(count_minus365_ges)
        string365 = string_neg365 + slash + string_ges365
        string_percent1 = str(percent1) + percent
        string_percent7 = str(percent7) + percent
        string_percent31 = str(percent31) + percent
        string_percent365 = str(percent365) + percent

        # Create PDF
        pdf = FPDF()
        pdf.add_page()
        pdf.set_xy(0, 0)

        # Adding Layout
        pdf.image(self.static_folder + '/Report_Template.png',
                  x=0,
                  y=0,
                  w=210,
                  h=0,
                  type='',
                  link='')
        pdf.set_font('arial', '', 14)

        # Adding Plots
        pdf.set_xy(108, 113)
        pdf.image(self.static_folder + '/DayPlot.png',
                  x=None,
                  y=None,
                  w=92,
                  h=0,
                  type='',
                  link='')
        pdf.set_xy(15, 196)
        pdf.image(self.static_folder + '/WeekPlot1.png',
                  x=None,
                  y=None,
                  w=85,
                  h=0,
                  type='',
                  link='')
        pdf.set_xy(110, 196)
        pdf.image(self.static_folder + '/WeekPlot2.png',
                  x=None,
                  y=None,
                  w=85,
                  h=0,
                  type='',
                  link='')

        # Adding tile kpis
        pdf.set_xy(21, 132)
        pdf.cell(40, 10, str(string1))
        pdf.set_xy(67, 132)
        pdf.cell(40, 10, str(string7))
        pdf.set_xy(21, 167)
        pdf.cell(40, 10, str(string31))
        pdf.set_xy(67, 167)
        pdf.cell(40, 10, str(string365))
        pdf.set_xy(177, 75)
        pdf.cell(40, 10, strtoday)

        pdf.set_font('arial', '', 20)
        pdf.set_xy(21, 124)
        pdf.cell(40, 10, str(string_percent1))
        pdf.set_xy(67, 124)
        pdf.cell(40, 10, str(string_percent7))
        pdf.set_xy(21, 159)
        pdf.cell(40, 10, str(string_percent31))
        pdf.set_xy(67, 159)
        pdf.cell(40, 10, str(string_percent365))
        pdf.set_xy(177, 75)

        # Save PDF
        strtoday2 = today.strftime("%Y%m%d")
        filename = self.static_folder + '/Facebook_Report_' + str(
            strtoday2) + '.pdf'
        pdffile = pdf.output(filename, 'F')

        print('##### ', filename)
        return filename
Example #34
0
def sendmail(travelbooking, company, mode, receiver):
    #generatetravel(travelbooking,company)
    pdf = FPDF()
    pdf.add_page()
    pdf.set_xy(10, 10)

    pdf.set_font('arial', 'B', 18.0)
    content = "Your Ticket to Destination"
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    pdf.set_font('arial', 'B', 16.0)
    content = "Travel Company: " + company.travel_name
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Mode: " + mode.mode_of_transport
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Location: " + travelbooking.from_dest
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Destination: " + travelbooking.to_dest
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Date of Departure: " + str(travelbooking.depart_date)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Date of Arrival: " + str(travelbooking.arrival_date)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Number of tickets: " + str(travelbooking.num_tickets)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Total price: " + str(travelbooking.totprice)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    filename = str(travelbooking.booking_id) + ".pdf"
    pdf.output(filename, 'F')
    body = "Please find attached your tickets. Bon Voyage!"
    yag = yagmail.SMTP("emailid")
    yag.send(
        to=receiver,
        subject="Your reservation has been confirmed",
        contents=body,
        attachments=filename,
    )
Example #35
0
def hotelreservation(hoteldetails, hotelbooking, roomtype, receiver):
    #generatetravel(travelbooking,company)
    pdf = FPDF()
    pdf.add_page()
    pdf.set_xy(10, 10)

    pdf.set_font('arial', 'B', 18.0)
    content = "Your Hotel Reservation"
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    pdf.set_font('arial', 'B', 16.0)
    content = "Hotel Name: " + hoteldetails.hotel_name
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "City: " + hoteldetails.hotel_city
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Address: " + hoteldetails.hotel_addr
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Contact number: " + hoteldetails.hotel_contact
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Date of check-in " + str(hotelbooking.check_in)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Date of check-out: " + str(hotelbooking.check_out)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Room type: " + roomtype.room_type
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Number of rooms: " + str(hotelbooking.num_rooms)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    content = "Total price: " + str(hotelbooking.totprice)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt=content, border=0)
    pdf.cell(ln=1, h=5.0, align='L', w=0, txt="\n", border=0)

    filename = str(hotelbooking.booking_id) + ".pdf"
    pdf.output(filename, 'F')
    body = "Please find attached your hotel reservation details. Enjoy your stay!"
    yag = yagmail.SMTP("emailid")
    yag.send(
        to=receiver,
        subject="Your reservation has been confirmed",
        contents=body,
        attachments=filename,
    )
Example #36
0
    def format_pdf(data):
        date_time = 1
        issue = 2
        discipline = 3
        document = 4
        uid = 5
        project = 6
        sentiment = 7
        status = 8

        pdf = FPDF(format='A4', unit='in')
        pdf.add_page()

        effective_page_width = pdf.w - 2 * pdf.l_margin

        for item in data:
            pdf.set_font('Times', 'B', 15.0)
            pdf.cell(effective_page_width,
                     0.0,
                     'Project: {}'.format(item[project]),
                     align='C')
            pdf.ln(0.6)
            break

        for item in data:
            pdf.set_font('Times', 'B', 10.0)
            pdf.cell(
                1.0, 0.0,
                'ID: {} - Logged in: {}'.format(item[uid], item[date_time]))
            pdf.ln(0.15)
            pdf.cell(1.0, 0.0, 'Document: {}'.format(item[document]))
            pdf.ln(0.15)
            pdf.cell(1.0, 0.0, 'Discipline: {}'.format(item[discipline]))
            pdf.ln(0.15)
            pdf.cell(1.0, 0.0, 'Status: {}'.format(item[status]))
            pdf.ln(0.15)
            pdf.cell(1.0, 0.0, 'Sentiment: {}'.format(item[sentiment]))
            pdf.ln(0.25)

            pdf.set_font('Times', '', 10.0)
            pdf.multi_cell(effective_page_width, 0.15, item[issue])
            pdf.ln(0.5)

        return pdf
Example #37
0
def genpdf(request,
           profID):  # use to generate pdf file for lend another teacher.
    teachObj = Teach.objects.get(pk=int(profID))  # get all objects teacher.
    pdf = FPDF('P', 'mm', 'A4')  # start pdf file
    pdf.add_page()  # begin first page.

    pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)  # add font
    pdf.set_font('DejaVu', '', 14)  # set font and font size

    pdf.image('group3/trarachakarn.png', 20, 20, 20)  # insert image
    pdf.ln(25)  # new line

    proID = ''
    firstname = ''
    lastname = ''
    shortname = ''
    department = ''
    faculty = ''
    sahakornAccount = ''
    tell = ''
    email = ''

    try:  # check all data for beware blank data.
        proID = teachObj.prof.profID
    except:
        proID = 'None'

    try:
        firstname = teachObj.prof.firstName
    except:
        firstname = 'None'

    try:
        lastname = teachObj.prof.lastName
    except:
        lastname = 'None'

    try:
        shortname = teachObj.prof.shortName
    except:
        shortname = 'None'

    try:
        department = teachObj.prof.department
    except:
        department = 'None'

    try:
        faculty = teachObj.prof.faculty
    except:
        faculty = 'None'

    try:
        sahakornAccount = teachObj.prof.sahakornAccount
    except:
        sahakornAccount = 'None'

    try:
        tell = teachObj.prof.tell
    except:
        tell = 'None'

    try:
        email = teachObj.prof.email
    except:
        email = 'None'

    pdf.add_font('Kinnari-Bold', '', 'Kinnari-Bold.ttf',
                 uni=True)  # thai font bold
    pdf.set_font('Kinnari-Bold', '', 18)
    pdf.cell(0, 10, u'                         บันทึกข้อความ')
    pdf.ln(10)
    pdf.add_font('Kinnari', '', 'Kinnari.ttf', uni=True)  # thai font
    pdf.set_font('Kinnari', '', 12)
    pdf.cell(
        0, 10,
        u'         ส่วนราชการ ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์ คณะวิศวกรรมศาสตร์  โทร. ๘๕๑๘'
    )
    pdf.line(46, 52, 180, 52)
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'         ที่  วฟ     /๒๕๕๘                                        วันที่  '
    )
    pdf.line(30, 60, 180, 60)
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'         เรื่อง การจัดการเรียนการสอนสำหรับนักศึกษาโครงการพิเศษ(สองภาษา) '
    )
    pdf.line(30, 68, 180, 68)
    pdf.ln(8)
    pdf.cell(0, 10, u'         เรียน หัวหน้าภาควิชา ')
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                     ตามที่ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  ได้ขอรับบริการจัดการเรียนการ'
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'         สอนจากท่านในรายวิชา                                                      สำหรับนักศึกษา'
    )
    pdf.ln(8)
    pdf.cell(0, 10,
             u'         โครงการพิเศษ (สองภาษา)  ภาคเรียนที่            นั้น')
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                    ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  ขอให้ท่านยืนยันการจัดการเรียนการสอนใน'
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'         รายวิชาดังกล่าว ตามแบบฟอร์มด้านล่าง พร้อมตารางสอนและใบเบิกค่าสอนของอาจารย์ผู้สอนและ'
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'         ส่งคืนกลับภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  เพื่อจะได้ดำเนินการในส่วนที่เกี่ยวข้องต่อไป'
    )
    pdf.ln(8)
    pdf.cell(0, 10, u'                        จึงเรียนมาเพื่อโปรดทราบ')
    pdf.ln(20)
    pdf.cell(
        0, 10,
        u'                                                  (ดร.นภดล   วิวัชรโกเศศ)'
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                                              หัวหน้าภาควิศวกรรมไฟฟ้าและคอมพิวเตอร์'
    )
    pdf.ln(14)
    pdf.cell(
        0, 10,
        u'            ..................................................................................................................................................'
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'         ชื่อผู้สอน.................................................................... รหัสผู้สอน.................................ภาควิชา '
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'         คณะ.......................................................................รหัสวิชา...........................................ชื่อวิชา '
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                        ตอนเรียน           วัน              เวลา  ')
    pdf.ln(8)
    pdf.cell(0, 10, u'         ได้จัดการเรียนการสอนเป็น ')
    pdf.ln(8)
    pdf.cell(0, 10, u'                    ภาษาอังกฤษ  ')
    pdf.rect(37, 210, 3, 3)
    pdf.ln(8)
    pdf.cell(0, 10, u'                    ภาษาไทย')
    pdf.rect(37, 218, 3, 3)
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                                            ลงชื่อ......................................อาจารย์ผู้สอน '
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                                            (..............................................) '
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                                            ลงชื่อ......................................'
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                                            (..............................................) '
    )
    pdf.ln(8)
    pdf.cell(
        0, 10,
        u'                                            หัวหน้าภาควิชา............................................'
    )
    pdf.ln(8)

    pdf.cell(0, 10, u'' + proID)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + firstname + '   ' + lastname)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + shortname)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + department)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + faculty)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + sahakornAccount)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + tell)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + email)
    pdf.ln(20)
    pdf.cell(0, 10, u'' + teachObj.subject.subjectID)
    pdf.ln(20)
    pdf.cell(0, 10, u'' + teachObj.subject.subjectName)
    pdf.ln(20)
    pdf.cell(0, 10, u'' + teachObj.section.section)
    pdf.ln(20)
    pdf.cell(0, 10, u'' + str(teachObj.section.startTime))
    pdf.ln(20)
    pdf.cell(0, 10, u'' + teachObj.section.date)
    pdf.ln(20)
    pdf.output("group3/uni.pdf", 'F')

    # next path will open pdf file in new tab on browser.
    with open('group3/uni.pdf',
              'rb') as pdf:  # path to pdf in directory views.
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        response['Content-Disposition'] = 'filename=uni.pdf'
        return response
    pdf.closed
Example #38
0
    def ImrimirPDF(self, saleId):
	# Obtener los datos de la base de datos (datos de la venta y los elementos)
	datos = db.Salerecord(saleId)
	# guardar los datos de la venta en datos_sale
	datos_sale  = datos[0]
	#Guardar los datos de los elementos de la venta en datos_items 
	datos_items = datos[1]
	# Formatear el numero de la venta (ej: 0000000023)
	facturaNumero = str(("0"*(10-len(str(saleId))))+str(saleId))
	# Obtener los datos de la tienda/empresa desde la base de datos
	Datos = db.SelectConfigNS()
	
	logo = self.ResourcePath('logo.png')
	pdf = FPDF()
	pdf.add_page()
#	pdf.add_font('courier', '', 'cour.ttf', uni=True)
#	pdf.add_font('courier', '', 'cour.ttf', uni=True)
	pdf.set_font('courier', '', 13.0)
	pdf.set_xy(105.0, 16.0)
	pdf.cell(ln=0, h=22.0, align='L', w=75.0, txt='', border=0)
	pdf.set_line_width(0.0)
	pdf.rect(15.0, 45.0, 180.0, 90.0) # Marco Principal
	pdf.set_line_width(0.0)
	#pdf.rect(95.0, 15.0, 10.0, 10.0) # cuadrito 
    # LOGOTIPO
	pdf.image(logo, 27.0, 10.0, link='', type='', w=0, h=20)
	pdf.set_font('courier', 'B', 16.0)
	pdf.set_xy(95.0, 18.0)
	#pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt='Hola 1', border=0)
    # DATOS DE LA EMPRESA
	pdf.set_font('courier', '', 8.0)
	pdf.set_xy(115.0, 25.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Tel:              "+str(Datos[3]), border=0)
	pdf.set_xy(115.0, 28.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Web:              "+str(Datos[4]), border=0)
	pdf.set_xy(115.0, 31.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="E-mail:           "+Datos[7], border=0)
	pdf.set_xy(115.0, 34.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="NIT:              "+str(Datos[8]), border=0)
	pdf.set_font('courier', '', 7.0)

	pdf.set_xy(115.0, 35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=60.0, txt='Fecha:', border=0)
	pdf.set_xy(145.0, 35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=40.0, txt=datos_sale[1], border=0)

	pdf.rect(15.0, 9.0, 180.0, 35.8) # header datos principales

	pdf.set_xy(95.0, 21.5)
	pdf.set_line_width(0.0)
	pdf.set_font('arial', 'B', 13.0)
	pdf.set_xy(15.0, 10.5)
	pdf.cell(ln=0, h=5.5, align='C', w=180.0, txt='Comprobante de venta', border=0)
#	pdf.line(100.0, 25.0, 100.0, 57.0) #linea vertical header
	pdf.set_font('arial', 'B', 14.0)
	pdf.set_xy(143.0, 15.5)
	pdf.cell(ln=0, h=9.5, align='L', w=60.0, txt=facturaNumero, border=0)
	pdf.set_xy(115.0, 17.5)
	pdf.cell(ln=0, h=5.5, align='L', w=10.0, txt='N\xba: ', border=0)
	pdf.set_font('courier', 'B', 12.0)
	pdf.set_xy(17.0, 30.5)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt=Datos[1], border=0)#Datos[1] nombre
	pdf.set_font('courier', '', 12.0)
	pdf.set_xy(17.0, 26.5)
	pdf.set_font('courier', '', 8.0)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt="", border=0) #Datos[2] slogan
	pdf.set_xy(17.0, 34.5)
	pdf.set_font('courier', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=Datos[5], border=0, )
	pdf.set_xy(115.0, 39.5)
	pdf.set_font('courier', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt="Atendido por: ", border=0, )
	pdf.set_xy(145.0, 39.5)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=db.SelectUser(datos_items[0][7])[0][1], border=0, )
	
    #Datos del cliente
	nombre = ""
	for i in datos_sale[3].split(" "): nombre = nombre+i.capitalize()+" "

	
	if(str(datos[0][4])=="1"):
		pdf.set_fill_color(244, 244,244 )
	else:
		pdf.set_fill_color(255, 255,204 )

	pdf.set_xy(15.0, 45.0)
	pdf.cell(ln=0, h=5.0, align='L', w=180.0, txt='', fill=1)

	pdf.set_line_width(0.0)
	pdf.line(15.0, 50.0, 185.0, 50.0) #Linea de cabecera
	pdf.set_font('courier', '', 10.0)

	pdf.set_xy(17.0, 44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=13.0, txt='Cliente: '+nombre, border=0)

	pdf.set_xy(110.0, 44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Nit: '+datos_sale[5].upper(), border=0)

	pdf.set_xy(163.0, 44.3)
	if(str(datos[0][4])=="1"):
		est = "CREDITO"
	else:
		est = "PAGADO"
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt=est, border=0)


	pdf.set_xy(133.0, 69.0)
	#pdf.cell(ln=0, h=6.0, align='L', w=42.0, txt='Springfield', border=0)
	pdf.set_line_width(0.0)
	pdf.line(15.0, 50.0, 195.0, 50.0) #linea header de productos
	pdf.set_line_width(0.0)
	pdf.line(35.0, 50.0, 35.0, 130.0) #Separador 3
	pdf.line(50.0, 50.0, 50.0,   130.0) #Separador 2
	pdf.line(150.0, 50.0, 150.0, 130.0) #Separador 4
	pdf.line(172.0, 50.0, 172.0, 135.0) #Separador 5
	pdf.set_font('courier', '', 8.0)
	pdf.set_xy(14.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt='Codigo', border=0)
	pdf.set_xy(35.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Cantidad', border=0)
	pdf.set_xy(50.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Producto', border=0)
	pdf.set_xy(150.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Precio', border=0)
	pdf.set_xy(173.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt='Total', border=0)

	pdf.set_line_width(0.0)
	pdf.line(15.0, 55.0, 195.0, 55.0)

	lineaN = 55.0
	contador = 0
	for elemento in datos_items:
		contador = contador+1
		pdf.set_xy(15.0, lineaN)
		pdf.set_font('courier', '', 8.0)
		if len(elemento[6]) > 10:
			elemento[6] = elemento[6][:10]
		pdf.cell(ln=0, h=5.0, align='L', w=15.0, txt=elemento[6].upper(), border=0) # CODIGO

		pdf.set_xy(35.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt=str(elemento[4]), border=0)  # CANTIDAD


		pdf.set_xy(35.0+15, lineaN)
		if len(elemento[5]) > 57:
			pdf.cell( h=5.0, align='L', w=100.0, txt=elemento[5][:57], border=0) # NOMBRE
		else:
			pdf.cell(ln=0, h=5.0, align='L', w=100.0, txt=elemento[5], border=0) # NOMBRE

		pdf.set_xy(150.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.TSep(self.formatCant(elemento[3])), border=0) # PRECIO

		pdf.set_xy(173.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=self.TSep(self.formatCant(elemento[3]*elemento[4])), border=0) # TOTAL
		lineaN = lineaN+4

	pdf.set_line_width(0.0)
	pdf.line(15.0, 130.0, 195.0, 130.0)

	pdf.set_xy(70.0, 130.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Total', border=0)

	pdf.set_xy(173.0, 130.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.TSep(self.formatCant(datos_sale[2])), border=0)


	
#------------ SEGUNDA PARTE ---------------#

	ln2 = 141
	pdf.set_line_width(0.0)
	pdf.rect(15.0, ln2+45.0, 180.0, 90.0) # Marco Principal

	pdf.rect(15.0, ln2+9.0, 180.0, 35.8) # header datos principales
	pdf.set_font('arial', 'B', 13.0)
	pdf.set_xy(15.0, ln2+10.5)
	pdf.cell(ln=0, h=5.5, align='C', w=180.0, txt='Comprobante de venta', border=0)
 # LOGOTIPO
	pdf.image(logo, 27.0, ln2+10.0, link='', type='', w=0, h=20)
	pdf.set_font('courier', 'B', 16.0)
	pdf.set_xy(ln2+95.0, 18.0)
	#pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt='Hola 1', border=0)
    # DATOS DE LA EMPRESA
	pdf.set_font('courier', '', 8.0)
	pdf.set_xy(115.0, ln2+25.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Tel:              "+str(Datos[3]), border=0)
	pdf.set_xy(115.0, ln2+28.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Web:              "+str(Datos[4]), border=0)
	pdf.set_xy(115.0, ln2+31.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="E-mail:           "+Datos[7], border=0)
	pdf.set_xy(115.0, ln2+34.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="NIT:              "+str(Datos[8]), border=0)

	pdf.set_font('courier', '', 7.0)
	pdf.set_xy(115.0, ln2+35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=60.0, txt='Fecha:', border=0)
	pdf.set_xy(145.0, ln2+35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=40.0, txt=datos_sale[1], border=0)

	pdf.set_xy(95.0, ln2+21.5)
	pdf.set_line_width(0.0)
#	pdf.line(100.0, 25.0, 100.0, 57.0) #linea vertical header
	pdf.set_font('arial', 'B', 14.0)
	pdf.set_xy(143.0, ln2+15.5)
	pdf.cell(ln=0, h=9.5, align='L', w=60.0, txt=facturaNumero, border=0)
	pdf.set_xy(115.0, ln2+17.5)
	pdf.cell(ln=0, h=5.5, align='L', w=10.0, txt='N\xba: ', border=0)
	pdf.set_font('courier', 'B', 12.0)
	pdf.set_xy(17.0, ln2+30.5)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt=Datos[1], border=0)#Datos[1] nombre
	pdf.set_font('courier', '', 12.0)
	pdf.set_xy(17.0, ln2+26.5)
	pdf.set_font('courier', '', 8.0)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt="", border=0) #Datos[2] slogan
	pdf.set_xy(17.0, ln2+34.5)
	pdf.set_font('courier', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=Datos[5], border=0, )

	pdf.set_xy(115.0, ln2+39.5)
	pdf.set_font('courier', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt="Atendido por: ", border=0, )
	pdf.set_xy(145.0, ln2+39.5)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=db.SelectUser(datos_items[0][7])[0][1], border=0, )



    #Datos del cliente
	nombre = ""
	for i in datos_sale[3].split(" "): nombre = nombre+i.capitalize()+" "

	if(str(datos[0][4])=="1"):
		pdf.set_fill_color(244, 244,244 )
	else:
		pdf.set_fill_color(255, 255,204 )


	pdf.set_xy(15.0, ln2+45.0)
	pdf.cell(ln=0, h=5.0, align='L', w=180.0, txt='', fill=1)

	pdf.set_line_width(0.0)
	pdf.line(15.0, ln2+50.0, 195.0, ln2+50.0) #Linea de cabecera
	pdf.set_font('courier', '', 10.0)

	pdf.set_xy(17.0, ln2+44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=13.0, txt='Cliente: '+nombre, border=0)

	pdf.set_xy(110.0, ln2+44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Nit: '+datos_sale[5].upper(), border=0)

	pdf.set_xy(163.0, ln2+44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt=est, border=0)


	pdf.set_xy(133.0, ln2+69.0)
	#pdf.cell(ln=0, h=6.0, align='L', w=42.0, txt='Springfield', border=0)
	pdf.set_line_width(0.0)
	pdf.line(15.0, ln2+50.0, 195.0, ln2+50.0) #linea header de productos
	pdf.set_line_width(0.0)
	pdf.line(35.0, ln2+50.0, 35.0, ln2+130.0) #Separador 3
	pdf.line(50.0, ln2+50.0, 50.0,   ln2+130.0) #Separador 2
	pdf.line(150.0, ln2+50.0, 150.0, ln2+130.0) #Separador 4
	pdf.line(172.0, ln2+50.0, 172.0, ln2+135.0) #Separador 5
	pdf.set_font('courier', '', 8.0)

	pdf.set_xy(14.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt='Codigo', border=0)

	pdf.set_xy(35.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Cantidad', border=0)

	pdf.set_xy(50.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Producto', border=0)

	pdf.set_xy(150.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Precio', border=0)

	pdf.set_xy(173.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt='Total', border=0)

	pdf.set_line_width(0.0)
	pdf.line(15.0, ln2+55.0, 195.0, ln2+55.0)

	lineaN = ln2+55.0
	contador = 0
	for elemento in datos_items:
		contador = contador+1
		pdf.set_xy(15.0, lineaN)
		pdf.set_font('courier', '', 8.0)
		if len(elemento[6]) > 10:
			elemento[6] = elemento[6][:10]
		pdf.cell(ln=0, h=5.0, align='L', w=15.0, txt=elemento[6].upper(), border=0) # CODIGO

		pdf.set_xy(35.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt=str(elemento[4]), border=0)  # CANTIDAD


		pdf.set_xy(35.0+15, lineaN)
		if len(elemento[5]) > 57:
			pdf.cell( h=5.0, align='L', w=100.0, txt=elemento[5][:57], border=0) # NOMBRE
		else:
			pdf.cell(ln=0, h=5.0, align='L', w=100.0, txt=elemento[5], border=0) # NOMBRE

		pdf.set_xy(150.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.TSep(self.formatCant(elemento[3])), border=0) # PRECIO

		pdf.set_xy(173.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=self.TSep(self.formatCant(elemento[3]*elemento[4])), border=0) # TOTAL
		lineaN = lineaN+4

	pdf.set_line_width(0.0)
	pdf.line(15.0, ln2+130.0, 195.0, ln2+130.0)

	pdf.set_xy(70.0, ln2+130.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Total', border=0)

	pdf.set_xy(173.0, ln2+130.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.TSep(self.formatCant(datos_sale[2])), border=0)




	pdf.output('invoice.pdf', 'F')
	if sys.platform.startswith("linux"):
		os.system("evince ./invoice.pdf")
	else:
		#os.system("invoice.pdf")
		import subprocess
		subprocess.Popen("invoice.pdf", shell=True, bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Example #39
0
def bill():
    try:
        if 'username' in session and session['username'] != manager_name:
            if request.method == 'POST':
                a = datetime.datetime.now(pytz.timezone('Asia/Calcutta'))
                end_time = a.strftime("%c")
                db.details.update({"name": session['username']}, {
                    "$set": {
                        "destination": request.form['destination'],
                        "end_time": end_time
                    }
                })
                db.scooter.update({"rider_name": session['username']}, {
                    "$set": {
                        "docking_station": request.form['destination'],
                        "ignition_status": "off",
                        "rider_name": "-"
                    }
                })
                details = db.docking_station.find(
                    {"station_name": request.form['destination']})
                num = details[0]["no_of_scooters"]
                num = num + 1
                db.docking_station.update(
                    {"station_name": request.form['destination']},
                    {"$set": {
                        "no_of_scooters": num
                    }})
                data = db.details.find({"name": session['username']})
                start_time = data[0]["start_time"]
                a = start_time.split(" ")
                x = db.fare.find({})
                base_price = int(x[0]["base_price"])
                per_min = int(x[0]["per_min"])
                min_price = int(x[0]["min_price"])
                global time
                global before_hour
                global before_min
                try:
                    time = a[3].split(":")
                    before_hour = int(time[0])
                    before_min = int(time[1])
                except:
                    time = a[4].split(":")
                    before_hour = int(time[0])
                    before_min = int(time[1])
                a = end_time.split(" ")
                global after_hour
                global after_min
                try:
                    time = a[3].split(":")
                    after_hour = int(time[0])
                    after_min = int(time[1])
                except:
                    time = a[4].split(":")
                    after_hour = int(time[0])
                    after_min = int(time[1])

                #calculaitng ride timming
                hour = after_hour - before_hour - 1
                minutes = after_min + (60 - before_min) + (hour * 60)
                #caluclation fare on half an hour basis
                # quo = int(minutes/30)
                # rem = minutes%30
                # if rem == 0:
                #     amount = quo*50
                # else:
                #     amount = (quo + 1 )*50
                amount = base_price + (minutes * per_min)
                balance = data[0]["balance"]
                balance = balance - amount
                db.details.update({"name": session['username']},
                                  {"$set": {
                                      "balance": balance
                                  }})
                details = {
                    "name": session['username'],
                    "registration_number": data[0]["registration_number"],
                    "from": data[0]["from"],
                    "start_time": data[0]["start_time"],
                    "destination": data[0]["destination"],
                    "end_time": data[0]["end_time"],
                    "amount": amount,
                    "duration": minutes
                }
                db.logs.insert(details)

                #writing into pdf file
                pdf = FPDF()
                pdf.add_page()
                pdf.set_font("times", 'I', size=32)
                pdf.cell(200, 10, txt="Ride-a-Bike", ln=1, align="C")
                pdf.set_font("Arial", size=20)
                pdf.set_line_width(1)
                pdf.set_draw_color(255, 0, 0)
                pdf.line(10, 25, 200, 25)
                pdf.image('static/images/logo.png', x=85, y=30, w=50)
                pdf.set_font("Arial", 'B', size=20)
                pdf.cell(200, 120, txt=session['username'], ln=1, align="L")
                pdf.set_font("Arial", size=18)
                pdf.set_line_width(1)
                pdf.set_draw_color(0, 0, 0)
                pdf.line(15, 90, 195, 90)
                start_station = data[0]["from"]
                pdf.cell(200,
                         -75,
                         txt="From :  " + start_station + "    " + start_time,
                         ln=1,
                         align="L")
                pdf.cell(200,
                         100,
                         txt="To :   " + request.form['destination'] + "    " +
                         end_time,
                         ln=1,
                         align="L")
                pdf.cell(200,
                         -75,
                         txt="Minimum Fare : " + str(base_price),
                         ln=1,
                         align="L")
                pdf.cell(200,
                         100,
                         txt="Time Fare (" + str(minutes) + " mins) : " + str(
                             (minutes * per_min)),
                         ln=1,
                         align="L")
                pdf.set_font("Arial", 'B', size=20)
                pdf.cell(200,
                         -75,
                         txt="Total : " + str(amount),
                         ln=1,
                         align="L")
                pdf.set_line_width(1)
                pdf.set_draw_color(0, 0, 0)
                pdf.line(15, 165, 195, 165)
                pdf.output("ride-a-bike_bill.pdf")

                db.details.update({"name": session['username']},
                                  {"$set": {
                                      "status": "-"
                                  }})
                return render_template("bill.html",
                                       time=end_time,
                                       data=data,
                                       minutes=minutes,
                                       amount=amount,
                                       username=session['username'],
                                       balance=balance,
                                       base_price=x[0]["base_price"],
                                       per_min=x[0]["per_min"],
                                       min_price=x[0]["min_price"])
            else:
                return render_template("bill.html")
        else:
            return render_template("login_error.html")
    except:
        return redirect('/end_ride')
Example #40
0
from fpdf import FPDF

#font_file_name = 'font/mathjax_amsregular.ttf'
font_file_name = 'font/MathJax/ttf/mathjax_size4regular.ttf'

size = 10
pdf = FPDF()
pdf.add_page()
pdf.add_font('jax','',font_file_name,uni=True)

lb = 0
for n in range(0xeffc):
    c = unichr(n)
    pdf.set_font('jax','',size)
    w = pdf.get_string_width(c)
    if w > 0:
        pdf.set_font('times','',size)
        pdf.cell(13, 10, hex(n) + ': ' )
        pdf.set_font('jax','',size)
        pdf.cell(10, 10, c)
        if lb == 6: 
            pdf.ln(10)
            lb = 0
        else:
            lb += 1
    #print unichr(i)
pdf.output('out/latex/font_view.pdf', 'F')
print 'done'
Example #41
0
def create_form():
    """Generates report and saves to a locaiton.

    """
    rp_save = gui.rpnum_text.get('1.0', 'end').split('\n')[0].strip()
    pdf = FPDF()
    pdf.add_page()
    sum_out = ''
    count = 0
    cliping = ''

    if gui.rpnum_text.get('1.0', 'end').split('\n')[0] == '' or gui.pic_text.get('1.0', 'end').split('\n')[0] == '' or \
            gui.rp.get() == False and gui.nrp.get() == False and gui.rt.get() == False and gui.kj.get() == False or \
            gui.bhotswap.get() == False and gui.bvibration.get() == False and \
            gui.bnoise.get() == False and gui.bheat.get() == False and gui.bnff.get() == False and gui.bcable.get() == False and \
            gui.bsurge.get() == False and gui.bimpact.get() == False or gui.bapp_nff.get() == False and gui.bapp_oil.get() == False and \
            gui.bapp_impact.get() == False and gui.bapp_cable.get() == False and gui.bapp_filterglass.get() == False or \
            gui.bsym_cable.get() == False and \
            gui.bsym_inout.get() == False and gui.bsym_nocom.get() == False and gui.bsym_noint.get() == False and \
            gui.bsym_nolaser.get() == False and gui.bsym_nopower.get() == False and gui.bsym_symnff.get() == False and \
            gui.bsym_nffstruct.get() == False:
        checkerror()
        return None
    else:
        pass
    pdf.image('report_img/logo.jpg', w=190, h=55, type='jpg')
    # pdf.set_font('Arial', 'IB', 22)
    # pdf.cell(190, 15, 'Failure Analysis Report', ln=1, align='C')
    pdf.ln(10)
    pdf.set_font('Arial', 'B', 14)
    if gui.rpnum_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'RP#: ' + 'None          ')
    else:
        pdf.cell(40, 10, 'RP#: ' + gui.rpnum_text.get('1.0', 'end') + '          ')

    if gui.item_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'Item: ' + 'None          ')
    else:
        pdf.cell(40, 10, 'Item: ' + gui.item_text.get('1.0', 'end') + '          ')

    # if serial_text.get('1.0', 'end').strip() == '':
    #     pdf.cell(40, 10, 'Serial: ' + 'None          ')
    # else:
    pdf.cell(40, 10, 'Serial: ' + gui.entries())

    pdf.ln(h=15)

    if gui.key_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'Keyword: ' + 'None          ')
    else:
        pdf.cell(40, 10, 'Keyword: ' + gui.key_text.get('1.0', 'end'))

    if gui.pic_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'PIC: ' + 'None          ')
    else:
        pdf.cell(40, 10, 'PIC: ' + gui.pic_text.get('1.0', 'end'))

    if gui.bench_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'Time: ' + 'None          ')
    else:
        pdf.cell(40, 10, 'Time: ' + gui.bench_text.get('1.0', 'end'))

    if gui.pic_text.get('1.0', 'end').strip() == 'Angel' or gui.pic_text.get('1.0', 'end').strip() == 'angel':
        pdf.image('report_img/angel.jpg', y=85, x=125, w=20, h=20, type='jpg')
    elif gui.pic_text.get('1.0', 'end').strip() == 'Grant' or gui.pic_text.get('1.0', 'end').strip() == 'grant':
        pdf.image('report_img/grant.jpg', y=85, x=125, w=20, h=20, type='jpg')
    elif gui.pic_text.get('1.0', 'end').strip() == 'Adolfo' or gui.pic_text.get('1.0', 'end').strip() == 'adolfo':
        pdf.image('report_img/adolfo.jpg', y=85, x=125, w=20, h=20, type='jpg')

    pdf.ln(h=15)
    pdf.image('report_img/rp-history.jpg', w=190, h=12, type='jpg')
    pdf.set_font('Arial', 'B', 12)

    if gui.his_rp_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'RP#: ' + 'None', ln=1)
    else:
        pdf.cell(40, 10, 'RP#: ' + gui.his_rp_text.get('1.0', 'end'))

    if gui.his_comp_date_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'Date: ' + 'None', ln=1)
    else:
        pdf.cell(40, 10, 'Date:' + gui.his_comp_date_text.get('1.0', 'end'))

    if gui.his_symptom_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'Symptom: ' + 'None', ln=1)
    else:
        pdf.cell(40, 10, 'Symptom: ' + gui.his_symptom_text.get('1.0', 'end'), ln=1)

    if gui.his_result_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'Result: ' + 'None', ln=1)
    else:
        pdf.cell(40, 10, 'Result: ' + gui.his_result_text.get('1.0', 'end'), ln=1)

    pdf.ln(h=15)
    pdf.image('report_img/appearance.jpg', w=190, h=12, type='jpg')
    pdf.set_font('Arial', 'B', 12)
    pdf.cell(40, 10, gui.appearance_text.get('1.0', 'end'), ln=1)
    pdf.ln(h=15)
    pdf.image('report_img/symptom.jpg', w=190, h=12, type='jpg')
    pdf.set_font('Arial', 'B', 12)
    pdf.cell(40, 10, gui.symptom_text.get('1.0', 'end'), ln=1)
    pdf.ln(h=15)
    pdf.image('report_img/tests.jpg', w=190, h=12, type='jpg')
    pdf.set_font('Arial', 'B', 12)
    pdf.cell(40, 10, gui.tests_text.get('1.0', 'end'), ln=1)
    pdf.ln(h=15)
    pdf.image('report_img/failure.jpg', w=190, h=12, type='jpg')
    pdf.set_font('Arial', 'B', 12)
    pdf.ln(h=15)

    if gui.fb_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'Failed Board: ' + ' None', ln=1)
    else:
        pdf.cell(40, 10, 'Failed Board: ' + gui.fb_text.get('1.0', 'end'), ln=1)

    if gui.comp_text.get('1.0', 'end').strip() == '':
        pdf.cell(40, 10, 'Location of Component: ' + 'None', ln=1)
    else:
        pdf.cell(40, 10, 'Location of Component: ' + gui.comp_text.get('1.0', 'end'), ln=1)
    pdf.cell(40, 10, 'Failed Structure Part: ' + gui.structure_text.get('1.0', 'end'), ln=1)

    if gui.parts_text.get('1.0', 'end').split('\n')[0] == '':
        pdf.cell(40, 10, 'Were parts replaced? No')
    else:
        pdf.cell(40, 10, 'Were parts replaced? Yes. ' + gui.parts_text.get('1.0', 'end') + '.')

    pdf.ln(h=15)
    pdf.image('report_img/analysis.jpg', w=190, h=12, type='jpg')
    pdf.set_font('Arial', 'B', 12)

    for a in range(len(gui.analysis_text.get('1.0', 'end').split('\n'))):
        pdf.cell(40, 10, gui.analysis_text.get('1.0', 'end').split('\n')[count], ln=1)
        count += 1

    pdf.ln(h=15)
    pdf.image('report_img/causeof.jpg', w=190, h=12, type='jpg')
    pdf.set_font('Arial', 'B', 12)
    pdf.cell(40, 10, gui.failure_text.get('1.0', 'end'), ln=1)
    pdf.ln(h=15)
    pdf.image('report_img/summary.jpg', w=190, h=12, type='jpg')
    pdf.set_font('Arial', 'B', 12)

    if gui.rp.get():
        sum_out = 'This unit was repaired and sent back to the customer'
    elif gui.nrp.get():
        sum_out = 'This unit was not repaired and sent back to the customer in the condition it was received'
    elif gui.rt.get():
        sum_out = 'This unit was sent back to the customer in the condition it was received'
    elif gui.kj.get():
        sum_out = 'This unit was sent to KJ'

    pdf.cell(40, 10, sum_out, ln=1)
    pdf.ln(h=15)
    pdf.add_page()
    pdf.cell(175, 15, 'Customer Inspection Report', ln=1, align='C')
    pdf.ln(h=15)

    pdf.set_font('Arial', '', 14)
    pdf.cell(40, 10, '< Appearance Check > ', ln=1)
    pdf.set_font('Arial', '', 12)
    pdf.multi_cell(175, 10, rep.apperance_check())

    if gui.c_appearance_text.get('1.0', 'end').strip() == '':
        cliping += '< Appearance Check >\n' + rep.apperance_check() + '\n'
    else:
        pdf.multi_cell(175, 10, 'Additional information:\n' + gui.c_appearance_text.get('1.0', 'end') + '\n')
        cliping += '< Appearance Check >\n' + rep.apperance_check() + '\nAdditional information:\n' + \
                   gui.c_appearance_text.get('1.0', 'end') + '\n'

    pdf.set_font('Arial', '', 14)
    pdf.cell(40, 10, '< Operation Check > ', ln=1)
    pdf.set_font('Arial', '', 12)
    pdf.multi_cell(175, 10, rep.operation_check())

    if gui.c_operation_text.get('1.0', 'end').strip() == '':
        cliping += '< Operation Check >\n' + rep.operation_check() + '\n'
    else:
        pdf.multi_cell(175, 10, 'Additional information:\n' + gui.c_operation_text.get('1.0', 'end') + '\n')
        cliping += '< Operation Check >\n' + rep.operation_check() + '\nAdditional information:\n' + \
                   gui.c_operation_text.get('1.0', 'end') + '\n'

    pdf.set_font('Arial', '', 14)
    pdf.cell(40, 10, '< Internal Check > ', ln=1)
    pdf.set_font('Arial', '', 12)
    pdf.multi_cell(175, 10, rep.internal_check())

    if gui.c_internal_text.get('1.0', 'end').strip() == '':
        cliping += '< Internal Check >\n' + rep.internal_check() + '\n'
    else:
        pdf.multi_cell(175, 10, 'Additional information:\n' + gui.c_internal_text.get('1.0', 'end') + '\n')
        cliping += '< Internal Check >\n' + rep.internal_check() + '\nAdditional information:\n' + \
                   gui.c_internal_text.get('1.0', 'end') + '\n'

    pdf.set_font('Arial', '', 14)
    pdf.cell(40, 10, '< Suspected Cause > ', ln=1)
    pdf.set_font('Arial', '', 12)
    pdf.multi_cell(175, 10, rep.suspected_cause())

    if gui.c_suspected_text.get('1.0', 'end').strip() == '':
        cliping += '< Suspected Cause >\n' + rep.suspected_cause() + '\n'
    else:
        pdf.multi_cell(175, 10, 'Additional information:\n' + gui.c_suspected_text.get('1.0', 'end') + '\n')
        cliping += '< Suspected Cause >\n' + rep.suspected_cause() + '\nAdditional information:\n' + \
                   gui.c_suspected_text.get('1.0', 'end') + '\n'

    pdf.set_font('Arial', '', 14)
    pdf.cell(40, 10, '< Conclusion > ', ln=1)
    pdf.set_font('Arial', '', 12)
    pdf.multi_cell(175, 10, rep.conclusion())

    if gui.c_conclusion_text.get('1.0', 'end').strip() == '':
        cliping += '< Conclusion >\n' + rep.conclusion() + '\n'
    else:
        pdf.multi_cell(175, 10, 'Additional information:\n' + gui.c_conclusion_text.get('1.0', 'end') + '\n')
        cliping += '< Conclusion >\n' + rep.conclusion() + '\nAdditional information:\n' + \
                   gui.c_conclusion_text.get('1.0', 'end') + '\n'

    pdf.set_font('Arial', '', 14)
    pdf.cell(40, 10, '< Preventative Measure > ', ln=1)
    pdf.set_font('Arial', '', 12)
    pdf.multi_cell(175, 10, rep.preventative_measure())
    cliping += '< Preventative Measure >\n' + rep.preventative_measure()

    try:
        pdf.output('I:/PRD/Check Sheets/RSS/' + rp_save + ' - ' + gui.serial_list[0].get('1.0', 'end').strip() + '.pdf',
                   'F')
        # pdf.output(rp_save + ' - ' + gui.serial_list[0].get('1.0', 'end').strip() + '.pdf', 'F')
    except OSError:
        gui.fileopen()
        return None

    pyperclip.copy(cliping)
    gui.copy_message()
    gui.rpnum_text.delete('1.0', 'end')
    # serial_text.delete('1.0', 'end')
    gui.key_text.delete('1.0', 'end')
    gui.comp_text.delete('1.0', 'end')
    gui.structure_text.delete('1.0', 'end')
    gui.fb_text.delete('1.0', 'end')
Example #42
0
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import random
from fpdf import FPDF

vowels = ["a","o","i","u","e"]
consonants = raw_input("Enter the range of consonants (np.> d s r t) >").split()

pages=int(raw_input("Enter the number of pages >"))

pdf = FPDF()
pdf.add_page()
pdf.set_font('Arial', 'B', 16)

for quantity in xrange(pages*80):
    pdf.cell(20, 30, random.choice(consonants)+random.choice(vowels))
    if (quantity+1)%10==0: pdf.ln()

pdf.output('Hiragana exercises.pdf')
Example #43
0
    def generate_report(self):
        """ Generate a report as PDF file
        """
        # Option
        pdf = FPDF()
        pdf.add_page()
        pdf.set_xy(20, 5)
        pdf.set_title("KNN")
        pdf.accept_page_break()

        # Title
        pdf.set_font('arial', 'B', 25)
        pdf.cell(0, 30, 'KNN', border=0, ln=2, align='C')

        # Info
        pdf.cell(15)
        pdf.set_font('arial', 'I', 14)
        pdf.cell(30, 2, 'Accuracy : ', border=0, ln=0, align='L')
        pdf.set_font('arial', '', 14)
        pdf.cell(50, 2, f'{self.acc}', border=0, ln=2, align='L')

        # Plot Report
        pdf.cell(10)
        pdf.image(self.cfg['plot_path'] + "knn-report.png",
                  x=30,
                  y=40,
                  w=150,
                  h=100,
                  type='',
                  link='')

        # Chapter
        pdf.set_y(140)
        pdf.cell(10)
        pdf.set_font('arial', 'B', 18)
        pdf.cell(0, 20, 'Confusion Matrix', border=0, ln=2, align='L')

        # Plot Confusion Matrix
        pdf.cell(0)
        pdf.image(self.cfg['plot_path'] + "knn-confusion-matrix.png",
                  x=20,
                  y=160,
                  w=100,
                  h=75,
                  type='',
                  link='')
        pdf.cell(10)
        pdf.image(self.cfg['plot_path'] + "knn-confusion-matrix-normalize.png",
                  x=100,
                  y=160,
                  w=100,
                  h=75,
                  type='',
                  link='')

        # Info -> Precision/Recall/F1
        pdf.set_y(235)
        pdf.cell(15)
        pdf.set_font('arial', 'B', 12)
        pdf.cell(30, 7, f'{self.classes[0]} : ', border=0, ln=0, align='L')
        pdf.cell(50)
        pdf.cell(30, 7, f'{self.classes[1]} : ', border=0, ln=1, align='L')

        pdf.cell(20)
        pdf.set_font('arial', 'I', 12)
        pdf.cell(22, 7, f'Precision : ', border=0, ln=0, align='L')
        pdf.set_font('arial', '', 12)
        pdf.cell(60, 7, f'{self.lp}', border=0, ln=0, align='L')
        pdf.set_font('arial', 'I', 12)
        pdf.cell(22, 7, f'Precision : ', border=0, ln=0, align='L')
        pdf.set_font('arial', '', 12)
        pdf.cell(60, 7, f'{self.wp}', border=0, ln=1, align='L')

        pdf.cell(20)
        pdf.set_font('arial', 'I', 12)
        pdf.cell(22, 7, f'Recall : ', border=0, ln=0, align='L')
        pdf.set_font('arial', '', 12)
        pdf.cell(60, 7, f'{self.lr}', border=0, ln=0, align='L')
        pdf.set_font('arial', 'I', 12)
        pdf.cell(22, 7, f'Recall : ', border=0, ln=0, align='L')
        pdf.set_font('arial', '', 12)
        pdf.cell(60, 7, f'{self.wr}', border=0, ln=1, align='L')

        pdf.cell(20)
        pdf.set_font('arial', 'I', 12)
        pdf.cell(22, 7, f'F1 : ', border=0, ln=0, align='L')
        pdf.set_font('arial', '', 12)
        pdf.cell(60, 7, f'{self.lf1}', border=0, ln=0, align='L')
        pdf.set_font('arial', 'I', 12)
        pdf.cell(22, 7, f'F1 : ', border=0, ln=0, align='L')
        pdf.set_font('arial', '', 12)
        pdf.cell(60, 7, f'{self.wf1}', border=0, ln=1, align='L')

        pdf.add_page()
        pdf.set_font('arial', 'B', 18)
        pdf.cell(10)
        pdf.cell(0, 20, 'Decision Boundary', border=0, ln=2, align='L')

        try:
            pdf.image(self.cfg['plot_path'] + "knn-decision-boundary-xy.png",
                      x=10,
                      y=30,
                      w=100,
                      h=70,
                      type='',
                      link='')
            pdf.image(self.cfg['plot_path'] + "knn-decision-boundary-xz.png",
                      x=100,
                      y=30,
                      w=100,
                      h=70,
                      type='',
                      link='')
            pdf.image(self.cfg['plot_path'] + "knn-decision-boundary-yz.png",
                      x=10,
                      y=100,
                      w=100,
                      h=70,
                      type='',
                      link='')
        except:
            pass
        try:
            pdf.image(self.cfg['plot_path'] +
                      "knn-decision-boundary-uniform-3D.png",
                      x=10,
                      y=175,
                      w=180,
                      h=120,
                      type='',
                      link='')
        except:
            print("ciao")

        pdf.output(self.cfg['info_path'] + 'knn-report.pdf', 'F')
Example #44
0
def create_qc_pdf(**kwargs):
    try:
        kwargs['company'] = kwargs.get('company', u'台茂化工儀器原料行')
        kwargs['product'] = kwargs.get('product', u'product name?')
        kwargs['ASE_pn'] = kwargs.get('ASE_pn', u'ASE PN?')
        if not kwargs.get('lot_no'):
            kwargs['make_date'] = date.today()
            kwargs['test_date'] = date.today()
            kwargs['lot_no'] = u'lot number?'
        else:
            year = 2000 + int(kwargs['lot_no'][1:3])
            month = int(kwargs['lot_no'][3:5])
            day = int(kwargs['lot_no'][5:7])
            kwargs['make_date'] = date(year, month, day)
            kwargs['test_date'] = date(year, month, day)
        kwargs['exp_period'] = kwargs.get('exp_period', u'一年')
        kwargs['amount'] = kwargs.get('amount', u'amount?')
        kwargs['tester'] = kwargs.get('tester', u'tester?')
        kwargs['test_params'] = kwargs.get('test_params', [])
    except Exception as e:
        print e
        return

    # Set placement and style of values
    tm_branch = dict(x=30, y=25, w=178-30, h=10, align='C')
    product_name = dict(x=31, y=50, w=104-31, h=15, align='L')
    product_ASE_pn = dict(x=105, y=50, w=104-31, h=15, align='L')

    make_date = dict(x=31, y=65, w=104-31, h=8, align='L')
    test_date = dict(x=31, y=73, w=104-31, h=8, align='L')
    exp_period = dict(x=31, y=81, w=104-31, h=9, align='L')

    lot_no = dict(x=105, y=65, w=104-31, h=8, align='L')
    amount = dict(x=105, y=73, w=104-31, h=8, align='L')
    tester = dict(x=105, y=81, w=104-31, h=9, align='L')


    # Create PDF
    FPDF = myPDF('P','mm','A4')
    FPDF.set_compression(False)
    FPDF.set_creator('TM_2014')
    FPDF.set_title(u'Quality inspection report for lot# {}'.format(kwargs['lot_no']))
    FPDF.set_author(u'Taimau Chemicals')
    FPDF.set_subject(kwargs['lot_no'])
#    FPDF.set_subject(u'{} {}'.format(kwargs['product'], kwargs['lot_no']), isUTF8=True)
    FPDF.alias_nb_pages()
    FPDF.add_page() # Adding a page also creates a page break from last page


    FPDF.add_font(family=u'SimHei', style='', fname=font, uni=True) # Only .ttf and not .ttc

    FPDF.set_font(family=u'SimHei', style='', size=16)
    FPDF.xycell(txt=kwargs['company'], **tm_branch)

    FPDF.set_font(family=u'SimHei', style='B', size=13)
    FPDF.xycell(txt=u'產品: {}'.format(kwargs['product']), **product_name)
    FPDF.xycell(txt=u'料號: {}'.format(kwargs['ASE_pn']), **product_ASE_pn)

    FPDF.xycell(txt=u'製造日期: {}'.format(kwargs['make_date']), **make_date)
    FPDF.xycell(txt=u'檢驗日期: {}'.format(kwargs['test_date']), **test_date)
    FPDF.xycell(txt=u'保存期間: {}'.format(kwargs['exp_period']), **exp_period)

    FPDF.xycell(txt=u'批號: {}'.format(kwargs['lot_no']), **lot_no)
    FPDF.xycell(txt=u'生產數量: {}'.format(kwargs['amount']), **amount)
    FPDF.xycell(txt=u'取樣人員: {}'.format(kwargs['tester']), **tester)

    FPDF.set_left_margin(30)
    FPDF.set_xy(x=30, y=105)
    for (a, b, c) in kwargs['test_params']:
        if a+b+c == u'':
            break
        FPDF.cell(49, 10, txt=a, align='C')
        FPDF.cell(49, 10, txt=b, align='C')
        FPDF.cell(49, 10, txt=c, align='C')
        FPDF.ln()
    FPDF.cell(49)
    FPDF.cell(49, 10, txt=u'以下空白', align='C')




    initialfilename = u'QC_{}_{}'.format(kwargs['product'], kwargs['lot_no'])
    FILE_OPTS = dict(
        title = u'PDF name and location.',
        defaultextension = '.pdf',
        initialdir = os.path.expanduser('~') + '/Desktop/',
        initialfile = initialfilename,
    )
    if settings.load().get(u'pdfpath'):
        FILE_OPTS['initialdir'] = settings.load()[u'pdfpath']

    outfile = os.path.normpath(tkFileDialog.asksaveasfilename(**FILE_OPTS))


    if os.path.exists(outfile):
        os.remove(outfile)
    if outfile and not os.path.exists(outfile):
        FPDF.output(name=outfile)

        try:
            subprocess.call(['start', outfile],
                             shell=True)
            return
        except:
            pass

        try:
            print u'Trying alternate subprocess command.'
            subprocess.call(['start', '/D'] +
                            list(os.path.split(outfile)),
                            shell=True)
            return
        except UnicodeEncodeError:
            pass

        try:
            os.startfile(outfile)
            return
        except:
            pass

        print u'Failed to autoload PDF after creation.'
        return
    else:
        head = u'Cancelled'
        body = u'Canceled PDF creation.'
        tkMessageBox.showinfo(head, body)
 def generate_pdf(spacing, transaction_id):
     try:
         pdf = FPDF()
         pdf.set_font('Arial', size=12)
         pdf.add_page()
         col_width = pdf.w / 4.5
         row_height = pdf.font_size
         pdf.cell(200, 5, 'V.L Super Market', ln=1, align='C')
         pdf.cell(200, 5, 'Thanks for Shopping', ln=2, align='C')
         pdf.cell(200, 5, 'Your Bill Details', ln=3, align='C')
         pdf.cell(200,
                  5,
                  'Total Amount : ' + str(total_payable_amount),
                  ln=4,
                  align='C')
         pdf.cell(200,
                  5,
                  'Transaction ID : ' + str(transaction_id),
                  ln=5,
                  align='C')
         for row in print_items_list:
             for item in row:
                 pdf.cell(col_width,
                          row_height * spacing,
                          txt=item,
                          border=1,
                          align='C')
             pdf.ln(row_height * spacing)
         file_name = 'pdf_files/' \
                     + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S_') \
                     + transaction_id + '.pdf'
         pdf.output(file_name)
         messagebox.showinfo('PDF Generation',
                             'PDF Generated Successfully...')
         messagebox.showinfo(
             'Transaction Successful',
             'Your Transaction is Successful with transation number : {}, Thanks for Shopping, Please Visit Again'
             .format(transaction_id))
         mail = send_email.Transaction_email()
         mail.send_mail(customer_email, file_name, customer_name,
                        transaction_id)
         # for to_email in emails_list:
         #     try:
         #         threading.Thread(target=mail.send_mail, args=(to_email, file_name),
         #                          name='sending_to_{}'.format(to_email)).start()
         #         print(threading.current_thread().getName())
         #         print(threading.enumerate())
         #     except Exception as e:
         #         error_log.report_error_log(__file__, e.__str__())
         #         continue
     except Exception as e:
         messagebox.showerror(
             'PDF Generation',
             'Print Generation Failed Please Try again...')
         error_log.report_error_log(__file__, e.__str__())
Example #46
0
class Report:
    def __init__(self, data: DataSet):
        self.output_path = os.path.join(data.data_path, "stats")
        self.dataset_name = os.path.basename(data.data_path)
        self.io_handler = data.io_handler

        self.mapi_light_light_green = [210, 245, 226]
        self.mapi_light_green = [5, 203, 99]
        self.mapi_light_grey = [218, 222, 228]
        self.mapi_dark_grey = [99, 115, 129]

        self.pdf = FPDF("P", "mm", "A4")
        self.pdf.add_page()

        self.title_size = 20
        self.h1 = 16
        self.h2 = 13
        self.h3 = 10
        self.text = 10
        self.small_text = 8
        self.margin = 10
        self.cell_height = 7
        self.total_size = 190

        self.stats = self._read_stats_file("stats.json")

    def save_report(self, filename):
        bytestring = self.pdf.output(dest="S")
        with self.io_handler.open(os.path.join(self.output_path, filename),
                                  "wb") as fwb:
            fwb.write(bytestring)

    def _make_table(self, columns_names, rows, row_header=False):
        self.pdf.set_font("Helvetica", "", self.h3)
        self.pdf.set_line_width(0.3)

        columns_sizes = [int(self.total_size / len(rows[0]))] * len(rows[0])

        if columns_names:
            self.pdf.set_draw_color(*self.mapi_light_grey)
            self.pdf.set_fill_color(*self.mapi_light_grey)
            for col, size in zip(columns_names, columns_sizes):
                self.pdf.rect(
                    self.pdf.get_x(),
                    self.pdf.get_y(),
                    size,
                    self.cell_height,
                    style="FD",
                )
                self.pdf.set_text_color(*self.mapi_dark_grey)
                self.pdf.cell(size, self.cell_height, col, align="L")
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.cell_height)

        self.pdf.set_draw_color(*self.mapi_light_grey)
        self.pdf.set_fill_color(*self.mapi_light_light_green)

        for row in rows:
            for i, (col, size) in enumerate(zip(row, columns_sizes)):
                if i == 0 and row_header:
                    self.pdf.set_draw_color(*self.mapi_light_grey)
                    self.pdf.set_fill_color(*self.mapi_light_grey)
                self.pdf.rect(
                    self.pdf.get_x(),
                    self.pdf.get_y(),
                    size,
                    self.cell_height,
                    style="FD",
                )
                self.pdf.set_text_color(*self.mapi_dark_grey)
                if i == 0 and row_header:
                    self.pdf.set_draw_color(*self.mapi_light_grey)
                    self.pdf.set_fill_color(*self.mapi_light_light_green)
                self.pdf.cell(size, self.cell_height, col, align="L")
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.cell_height)

    def _read_stats_file(self, filename):
        file_path = os.path.join(self.output_path, filename)
        with self.io_handler.open_rt(file_path) as fin:
            return io.json_load(fin)

    def _make_section(self, title):
        self.pdf.set_font("Helvetica", "B", self.h1)
        self.pdf.set_text_color(*self.mapi_dark_grey)
        self.pdf.cell(0, self.margin, title, align="L")
        self.pdf.set_xy(self.margin, self.pdf.get_y() + 1.5 * self.margin)

    def _make_subsection(self, title):
        self.pdf.set_xy(self.margin, self.pdf.get_y() - 0.5 * self.margin)
        self.pdf.set_font("Helvetica", "B", self.h2)
        self.pdf.set_text_color(*self.mapi_dark_grey)
        self.pdf.cell(0, self.margin, title, align="L")
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def _make_centered_image(self, image_path, desired_height):

        with tempfile.TemporaryDirectory() as tmp_local_dir:
            local_image_path = os.path.join(tmp_local_dir,
                                            os.path.basename(image_path))
            with self.io_handler.open(local_image_path, "wb") as fwb:
                with self.io_handler.open(image_path, "rb") as f:
                    fwb.write(f.read())

            width, height = PIL.Image.open(local_image_path).size
            resized_width = width * desired_height / height
            if resized_width > self.total_size:
                resized_width = self.total_size
                desired_height = height * resized_width / width

            self.pdf.image(
                local_image_path,
                self.pdf.get_x() + self.total_size / 2 - resized_width / 2,
                self.pdf.get_y(),
                h=desired_height,
            )
            self.pdf.set_xy(self.margin,
                            self.pdf.get_y() + desired_height + self.margin)

    def make_title(self):
        # title
        self.pdf.set_font("Helvetica", "B", self.title_size)
        self.pdf.set_text_color(*self.mapi_light_green)
        self.pdf.cell(0, self.margin, "OpenSfM Quality Report", align="C")
        self.pdf.set_xy(self.margin, self.title_size)

        # version number
        try:
            out, _ = subprocess.Popen(
                ["git", "describe", "--tags"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            ).communicate()
            version = out.strip().decode()
        except BaseException as e:
            logger.warning(
                f"Exception thrwon while extracting 'git' version, {e}")
            version = ""

        # indicate we don't know the version
        version = "unknown" if version == "" else version

        self.pdf.set_font("Helvetica", "", self.small_text)
        self.pdf.set_text_color(*self.mapi_dark_grey)
        self.pdf.cell(0,
                      self.margin,
                      f"Processed with OpenSfM version {version}",
                      align="R")
        self.pdf.set_xy(self.margin, self.pdf.get_y() + 2 * self.margin)

    def make_dataset_summary(self):
        self._make_section("Dataset Summary")

        rows = [
            ["Dataset", self.dataset_name],
            ["Date", self.stats["processing_statistics"]["date"]],
            [
                "Area Covered",
                f"{self.stats['processing_statistics']['area']/1e6:.6f} km²",
            ],
            [
                "Processing Time",
                f"{self.stats['processing_statistics']['steps_times']['Total Time']:.2f} seconds",
            ],
        ]
        self._make_table(None, rows, True)
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def _has_meaningful_gcp(self):
        return (self.stats["reconstruction_statistics"]["has_gcp"]
                and "average_error" in self.stats["gcp_errors"])

    def make_processing_summary(self):
        self._make_section("Processing Summary")

        rec_shots, init_shots = (
            self.stats["reconstruction_statistics"]
            ["reconstructed_shots_count"],
            self.stats["reconstruction_statistics"]["initial_shots_count"],
        )
        rec_points, init_points = (
            self.stats["reconstruction_statistics"]
            ["reconstructed_points_count"],
            self.stats["reconstruction_statistics"]["initial_points_count"],
        )

        geo_string = []
        if self.stats["reconstruction_statistics"]["has_gps"]:
            geo_string.append("GPS")
        if self._has_meaningful_gcp():
            geo_string.append("GCP")

        ratio_shots = rec_shots / init_shots * 100 if init_shots > 0 else -1
        rows = [
            [
                "Reconstructed Images",
                f"{rec_shots} over {init_shots} shots ({ratio_shots:.1f}%)",
            ],
            [
                "Reconstructed Points",
                f"{rec_points} over {init_points} points ({rec_points/init_points*100:.1f}%)",
            ],
            [
                "Reconstructed Components",
                f"{self.stats['reconstruction_statistics']['components']} component",
            ],
            [
                "Detected Features",
                f"{self.stats['features_statistics']['detected_features']['median']} features",
            ],
            [
                "Reconstructed Features",
                f"{self.stats['features_statistics']['reconstructed_features']['median']} features",
            ],
            ["Geographic Reference", " and ".join(geo_string)],
        ]

        row_gps_gcp = [" / ".join(geo_string) + " errors"]
        geo_errors = []
        if self.stats["reconstruction_statistics"]["has_gps"]:
            geo_errors.append(
                f"{self.stats['gps_errors']['average_error']:.2f}")
        if self._has_meaningful_gcp():
            geo_errors.append(
                f"{self.stats['gcp_errors']['average_error']:.2f}")
        row_gps_gcp.append(" / ".join(geo_errors) + " meters")
        rows.append(row_gps_gcp)

        self._make_table(None, rows, True)
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

        topview_height = 130
        topview_grids = [
            f for f in self.io_handler.ls(self.output_path)
            if f.startswith("topview")
        ]
        self._make_centered_image(
            os.path.join(self.output_path, topview_grids[0]), topview_height)

        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def make_processing_time_details(self):
        self._make_section("Processing Time Details")

        columns_names = list(
            self.stats["processing_statistics"]["steps_times"].keys())
        formatted_floats = []
        for v in self.stats["processing_statistics"]["steps_times"].values():
            formatted_floats.append(f"{v:.2f} sec.")
        rows = [formatted_floats]
        self._make_table(columns_names, rows)
        self.pdf.set_xy(self.margin, self.pdf.get_y() + 2 * self.margin)

    def make_gps_details(self):
        self._make_section("GPS/GCP Errors Details")

        # GPS
        for error_type in ["gps", "gcp"]:
            rows = []
            columns_names = [error_type.upper(), "Mean", "Sigma", "RMS Error"]
            if "average_error" not in self.stats[error_type + "_errors"]:
                continue
            for comp in ["x", "y", "z"]:
                row = [comp.upper() + " Error (meters)"]
                row.append(
                    f"{self.stats[error_type + '_errors']['mean'][comp]:.3f}")
                row.append(
                    f"{self.stats[error_type +'_errors']['std'][comp]:.3f}")
                row.append(
                    f"{self.stats[error_type +'_errors']['error'][comp]:.3f}")
                rows.append(row)

            rows.append([
                "Total",
                "",
                "",
                f"{self.stats[error_type +'_errors']['average_error']:.3f}",
            ])
            self._make_table(columns_names, rows)
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

    def make_features_details(self):
        self._make_section("Features Details")

        heatmap_height = 60
        heatmaps = [
            f for f in self.io_handler.ls(self.output_path)
            if f.startswith("heatmap")
        ]
        self._make_centered_image(os.path.join(self.output_path, heatmaps[0]),
                                  heatmap_height)
        if len(heatmaps) > 1:
            logger.warning("Please implement multi-model display")

        columns_names = ["", "Min.", "Max.", "Mean", "Median"]
        rows = []
        for comp in ["detected_features", "reconstructed_features"]:
            row = [comp.replace("_", " ").replace("features", "").capitalize()]
            for t in columns_names[1:]:
                row.append(
                    f"{self.stats['features_statistics'][comp][t.replace('.', '').lower()]:.0f}"
                )
            rows.append(row)
        self._make_table(columns_names, rows)

        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def make_reconstruction_details(self):
        self._make_section("Reconstruction Details")

        rows = [
            [
                "Average Reprojection Error (normalized / pixels)",
                (f"{self.stats['reconstruction_statistics']['reprojection_error_normalized']:.2f} / "
                 f"{self.stats['reconstruction_statistics']['reprojection_error_pixels']:.2f}"
                 ),
            ],
            [
                "Average Track Length",
                f"{self.stats['reconstruction_statistics']['average_track_length']:.2f} images",
            ],
            [
                "Average Track Length (> 2)",
                f"{self.stats['reconstruction_statistics']['average_track_length_over_two']:.2f} images",
            ],
        ]
        self._make_table(None, rows, True)
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 1.5)

        residual_histogram_height = 60
        residual_histogram = [
            f for f in self.io_handler.ls(self.output_path)
            if f.startswith("residual_histogram")
        ]
        self._make_centered_image(
            os.path.join(self.output_path, residual_histogram[0]),
            residual_histogram_height,
        )
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def make_camera_models_details(self):
        self._make_section("Camera Models Details")

        for camera, params in self.stats["camera_errors"].items():
            residual_grids = [
                f for f in self.io_handler.ls(self.output_path)
                if f.startswith("residuals_" + str(camera.replace("/", "_")))
            ]
            if not residual_grids:
                continue

            initial = params["initial_values"]
            optimized = params["optimized_values"]
            names = [""] + list(initial.keys())

            rows = []
            rows.append(["Initial"] + [f"{x:.4f}" for x in initial.values()])
            rows.append(["Optimized"] +
                        [f"{x:.4f}" for x in optimized.values()])

            self._make_subsection(camera)
            self._make_table(names, rows)
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

            residual_grid_height = 100
            self._make_centered_image(
                os.path.join(self.output_path, residual_grids[0]),
                residual_grid_height)

    def make_rig_cameras_details(self):
        self._make_section("Rig Cameras Details")

        columns_names = [
            "Translation X",
            "Translation Y",
            "Translation Z",
            "Rotation X",
            "Rotation Y",
            "Rotation Z",
        ]
        for rig_camera_id, params in self.stats["rig_errors"].items():
            initial = params["initial_values"]
            optimized = params["optimized_values"]

            rows = []
            r_init, t_init = initial["rotation"], initial["translation"]
            r_opt, t_opt = optimized["rotation"], optimized["translation"]
            rows.append([
                f"{t_init[0]:.4f} m",
                f"{t_init[1]:.4f} m",
                f"{t_init[2]:.4f} m",
                f"{r_init[0]:.4f}",
                f"{r_init[1]:.4f}",
                f"{r_init[2]:.4f}",
            ])
            rows.append([
                f"{t_opt[0]:.4f} m",
                f"{t_opt[1]:.4f} m",
                f"{t_opt[2]:.4f} m",
                f"{r_opt[0]:.4f}",
                f"{r_opt[1]:.4f}",
                f"{r_opt[2]:.4f}",
            ])

            self._make_subsection(rig_camera_id)
            self._make_table(columns_names, rows)
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

    def make_tracks_details(self):
        self._make_section("Tracks Details")
        matchgraph_height = 80
        matchgraph = [
            f for f in self.io_handler.ls(self.output_path)
            if f.startswith("matchgraph")
        ]
        self._make_centered_image(
            os.path.join(self.output_path, matchgraph[0]), matchgraph_height)

        histogram = self.stats["reconstruction_statistics"][
            "histogram_track_length"]
        start_length, end_length = 2, 10
        row_length = ["Length"]
        for length, _ in sorted(histogram.items(), key=lambda x: int(x[0])):
            if int(length) < start_length or int(length) > end_length:
                continue
            row_length.append(length)
        row_count = ["Count"]
        for length, count in sorted(histogram.items(),
                                    key=lambda x: int(x[0])):
            if int(length) < start_length or int(length) > end_length:
                continue
            row_count.append(f"{count}")

        self._make_table(None, [row_length, row_count], True)

        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def add_page_break(self):
        self.pdf.add_page("P")

    def generate_report(self):
        self.make_title()
        self.make_dataset_summary()
        self.make_processing_summary()
        self.add_page_break()

        self.make_features_details()
        self.make_reconstruction_details()
        self.add_page_break()

        self.make_tracks_details()
        self.make_camera_models_details()
        self.make_rig_cameras_details()
        self.add_page_break()

        self.make_gps_details()
        self.make_processing_time_details()
Example #47
0
def add_pdf(type_of_analysis):
    legend = [
        'Total number of billionaires per country. (Top 30)',
        'Top 15 fields of work most responsible for the wealth of their billionaires.',
        'Top 15 of countries which hold more billions of dollars by its billionaires.',
        'Percentage of billions of dollars distributed by gender.',
        'Ratio of billionaires with and without studies.'
    ]

    resume_analysis = [
        'the US dominated the list with nearly 600 billionaires followed by China with over 350. Last positions were occupied by Denmark and Ireland',
        'the two most profitable work fields are technology and fashion & retail industry. Last positions were occupied by Telecom and Construction.',
        'the US is the country that holds more billions with a record of over 3000 billions followed by china responsible for over 1000 billion.',
        'about 90% of billionaire fortunes belong to men.',
        "about 70% of the billionaires don't have university studies."
    ]
    pdf = FPDF()
    count = 1
    for image in glob.glob('../data/results/results*.jpg'):
        pdf.add_page()
        header(pdf)
        pdf.image(image, x=10, y=60, w=180)
        pdf.set_font('Arial', size=8)
        pdf.ln(170)  # move 170 down
        if type_of_analysis < 6 and re.match(
                '../data/results/results[0-9].jpg', image):
            pdf.cell(200, 10, txt='', ln=1)
            pdf.cell(ln=0,
                     h=5.0,
                     align='L',
                     w=0,
                     txt=f"Figure {count}: {legend[type_of_analysis-1]}",
                     border=0)
            pdf.ln(5)
            pdf.cell(
                ln=0,
                h=5.0,
                align='L',
                w=0,
                txt=f"In this graphic, {resume_analysis[type_of_analysis - 1]}",
                border=0)
        elif type_of_analysis == 6 and re.match(
                "../data/results/results[0-9].jpg", image):
            pdf.cell(200, 10, txt='', ln=1)
            pdf.cell(ln=0,
                     h=5.0,
                     align='L',
                     w=0,
                     txt=f"Figure {count}: {legend[count-1]}",
                     border=0)
            pdf.ln(5)
            pdf.cell(ln=0,
                     h=5.0,
                     align='L',
                     w=0,
                     txt=f"In this graphic, {resume_analysis[count-1]}",
                     border=0)
        else:
            continue
        footer(pdf)
        count += 1
    for i in glob.glob('../data/results/z*.jpg'):
        pdf.add_page()
        header(pdf)
        pdf.image(i, x=10, y=60, w=180)
        pdf.set_font('Arial', size=8)
        pdf.ln(170)  # move 170 down
        with open(i, 'r+b') as f:
            with Image.open(f) as image:
                cover = resizeimage.resize_cover(image, [200, 100])
                cover.save('1image.jpg', image.format)
        pdf.cell(
            200,
            10,
            txt=
            f"Figure {count}: In {num_position}.º place is {re.sub('_', ' ', df['name'][num_position])} who had a fortune of {df['worth(BUSD)'][num_position]} billions of dollars in 2018.",
            ln=1)
        #pdf.write(500,f"Figure {count}: In {num_position}.º place is {re.sub('_', ' ', df['name'][num_position])} who had a fortune of {df['worth(BUSD)'][num_position]} billions of dollars in 2018.")
        footer(pdf)
    pdf.output('../data/results/results.pdf')
def makePDF(client, accountDetails):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 10)
    pdf.cell(0, 10, 'Economusic')

    pdf.set_font('Arial', 'B', size=20)
    pdf.cell(0, 10, 'Rental Invoice', 0, 0, "R")
    pdf.ln()

    pdf.set_font("Arial", size=9)
    dateText = datetime.datetime.today().strftime("%b %d, %Y")
    fullText = "# Rental Invoice " + dateText
    pdf.cell(0, 5, fullText, 0, 0, "R")
    pdf.ln()
    pdf.cell(0, 5, (client["name"] + " " + client["surname"]), 0, 0, "R")
    pdf.ln()
    pdf.ln()

    pdf.cell(125, 5, "Bill To: ")
    pdf.cell(0, 5, "Date:")
    pdf.cell(0, 5, dateText, 0, 0, "R")
    pdf.ln()

    pdf.set_font('Arial', 'B', 11)
    pdf.cell(125, 5, (client["name"] + " " + client["surname"]))
    pdf.set_font("Arial", size=9)
    pdf.cell(0, 5, "Payment Terms:")
    pdf.cell(0, 5, "EFT", 0, 0, "R")
    pdf.ln()

    pdf.cell(125, 5, "")
    pdf.cell(0, 5, "")
    pdf.cell(0, 5, "", 0, 0, "R")
    pdf.ln()

    pdf.set_fill_color(220, 220, 220)
    pdf.set_font("Arial", "B", 11)
    pdf.cell(125, 7, "")
    pdf.cell(0, 7, "Balance Due:", 0, 0, 0, True)
    assets = []
    total = 0
    for rental in client["rentals"]:
        total = total + rental["rent"]
        assets.append({
            "name": rental["assetName"],
            "qty": 1,
            "rent": rental["rent"]
        })

    pdf.cell(0, 7, ("R " + str(total)), 0, 0, "R")
    pdf.ln()
    pdf.ln()

    pdf.set_fill_color(0, 0, 0)
    pdf.set_text_color(255, 255, 255)
    pdf.cell(98, 7, "Item", "LTB", 0, 0, True)
    pdf.cell(40, 7, "Quantity", "TB", 0, 0, True)
    pdf.cell(32, 7, "Rate", "TB", 0, 0, True)
    pdf.cell(20, 7, "Amount", "TRB", 0, 0, True)
    pdf.ln()

    pdf.set_font("Arial", size=11)
    pdf.set_text_color(0, 0, 0)
    for asset in assets:
        pdf.cell(98, 6, asset["name"])
        pdf.cell(40, 6, str(asset["qty"]))
        pdf.cell(32, 6, "R " + str(asset["rent"]))
        pdf.cell(20, 6, "R " + str(asset["rent"]))
        pdf.ln()
    pdf.ln()
    pdf.ln()

    pdf.cell(125, 5, "")
    pdf.cell(0, 5, "Subtotal:")
    pdf.cell(0, 5, "R " + str(total), 0, 0, "R")
    pdf.ln()

    pdf.cell(125, 5, "")
    pdf.cell(0, 5, "Total:")
    pdf.cell(0, 5, "R " + str(total), 0, 0, "R")
    pdf.ln()

    pdf.cell(0, 10, "Notes")
    pdf.ln()
    pdf.cell(0, 5, accountDetails["name"])
    pdf.ln()
    pdf.cell(0, 5, accountDetails["bank"])
    pdf.ln()
    pdf.cell(0, 5, accountDetails["num"])
    pdf.ln()

    final = os.path.join(os.path.dirname(__file__),
                         '../files/batched/' + client["clientId"] + '.pdf')
    pdf.output(final, 'F')
Example #49
0
  if (col >= cols):
    pdf.ln()
    col = 0
    row += 1
    if (row >= rows):
      pdf.add_page()
      row = 0

  cellx = leftmargin + (col * (cellwidth + cellgapx))
  celly = topmargin + (row * (cellheight + cellgapy))

  pdf.set_font('Helvetica', '', 8.5)

  if debug:
    pdf.set_xy(cellx, celly)
    pdf.cell(cellwidth, cellheight, "", border=1, align="C")

  lineheight = 3.4
  height = len(label.split("\n")) * lineheight
  top = celly + ((lineheight + cellheight - height) / 2)
#celly + 6

  n = 0
  for line in label.split("\n"):
    if n == 0:
      pdf.set_text_color(0, 0, 192)
      pdf.set_font('', 'B', 14)
    else:
      pdf.set_font('', '', 9)

    if "Uplink" in line:
#What does this code do????
#---------------------------
#this code creates a pdf with 3 lines
# each line has a different alignment
#This code also prints the information from a text file.

from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=20)
pdf.cell(200, 10, txt="This is line number 1", ln=1, align="C")
pdf.cell(200, 10, txt="This is line number 2", ln=2, align="L")
pdf.cell(200, 10, txt="This is line number 3", ln=3, align="R")

file = open("newfile.txt", "r")
for line in file:
    pdf.cell(200, 10, txt=line, ln=1, align="C")
#the code will print the information from a file
pdf.output("Demo1.pdf")
#Demo.pdf will be your file name
Example #51
0
#!/usr/bin/env python

"Simple test to check alias_nb_pages replacement under unicode fonts"

from fpdf import FPDF

pdf=FPDF()

# set default alias: {nb} that will be replaced with total page count
pdf.alias_nb_pages()

# Add a Unicode font (uses UTF-8)
pdf.add_font('DejaVu','','DejaVuSansCondensed.ttf',uni=True)
pdf.set_font('DejaVu','',14)

for i in range(5):
    pdf.add_page()
    pdf.set_font('Arial','B',16)
    pdf.cell(40,10,'Hello World! {nb}')
    pdf.set_font('DejaVu','',14)
    pdf.cell(40,10,'Hello World! unicode {nb}')
    
fn = 'nb_pages.pdf'
pdf.output(fn, 'F')

import os
try:
    os.startfile(fn)
except:
    os.system("xdg-open \"%s\"" % fn)
Example #52
0
                  os.path.abspath('.') + '/app/pdf/' +
                  title_font_data['path'],
                  uni=True)
 title_font = title_font_data['name']
 # font for plain text
 if text_font_data['type'] == 'embeded':
     pdf.add_font(text_font_data['name'],
                  '',
                  os.path.abspath('.') + '/app/pdf/' +
                  text_font_data['path'],
                  uni=True)
 text_font = text_font_data['name']
 # header section
 # left
 pdf.set_font(title_font, '', font_size['header_title'])
 pdf.cell(1, line_height['section'] + 1, data['header']['name'], ln=2)
 pdf.set_font_size(font_size['header_sub_title'])
 pdf.set_text_color(grey)
 pdf.cell(1, line_height['text'] + 1, data['header']['title'], ln=2)
 pdf.set_font_size(font_size['text'] + 2)
 online_text = data['pdf']['online']['text']
 pdf.cell(pdf.get_string_width(online_text),
          line_height['text'] + 1,
          online_text,
          ln=0)
 pdf.set_text_color(*blue)
 pdf.cell(1,
          line_height['text'] + 1,
          data['pdf']['online']['url'],
          ln=2,
          link=data['pdf']['online']['url'])
Example #53
0
imgFondo = "FONDOCARNET.jpg"
imgLogo = "HOSPITALC.JPG"
imgFoto = '/media/serv_coromoto/NominaShc/FotosE/F0011951.jpg'

apellidos = 'GARCIA DIAZ'
nombres = 'CARLOS ALBERTO'

#Agrego las Imagenes
pdf.image(imgFondo, 0,0,55,85)
pdf.image(imgBandera,0,10,60,10.5)

pdf.ln(13)
#Primer Texto y tipo de letra
pdf.set_font('Arial', 'B', 7)
pdf.set_text_color(255,0,0)
pdf.cell(w=0,h=0,txt='REPUBLICA BOLIVARIANA DE VENEZUELA',border=0,ln=1,align='C')

#Segundo Texto y tipo de letra
pdf.set_font('Arial', 'B', 9)
pdf.set_text_color(255,0,0)
pdf.cell(w=0,h=7,txt='PDV SERVICIOS DE SALUD S.A.',border=0,ln=1,align='C')

#Imagen del Logo
pdf.image(imgLogo,5, 29, w=9, h=12)

#Tercer Texto y tipo de letra
pdf.set_font('Arial', 'B', 12)
pdf.cell(0,4, 'HOSPITAL', 0, 1, 'C')
pdf.cell(0,8,'COROMOTO', 0, 1, 'C')

#Imagen de la Foto
Example #54
0
w_img = 150
h_img = 100

h_line = 5
h_text = 10
line_inc = 1

for x in f:

    if 'save plot' in x:

        #change page, if image is too large

        img_path = x.split(' -> ')[1]
        print(pdf.get_y())
        pdf.cell(200, h_line, txt='', ln=line_inc, align='L')
        line_inc = h_img / h_line
        pdf.cell(200, h_line, txt='', ln=line_inc, align='L')
        y_img = pdf.get_y()
        pdf.image(img_path[:-1], 10, y_img, w_img, h_img, type='jpg')
        line_inc = 1

        print('plot, line count: ' + str(line_count))
    else:
        print('text only, line count: ' + str(line_count))
        #pdf.text(0, line_count*h_text, txt = x)

        pdf.cell(200, h_line, txt=x, ln=line_inc, align='L')
        line_inc = 1
Example #55
0
    def makepdf(location):
        pdf = FPDF()
        counter = 0
        pdf.add_page()
        pdf.set_font('Arial', '', 16)
        pdf.cell(50, 10, 'Testbed Results', 1)
        pdf.add_page()
        image_list.sort()

        new_list = []

        new_list = image_list

        # In this case, we are only doing one set of tests, using TCP and UDP we are using RTP. So the pattern to sort it is different.

        # This code is for when there are tests for both UDP and TCP, but that doesn't apply when I am using my streaming code. 
        # a = 0
        # while a < len(image_list):
        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1 
        #     new_list.append(image_list[a])
        #     a += 5

        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a -= 7

        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 5

        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1
        #     new_list.append(image_list[a])
        #     a += 1

        for image in new_list:
            print('Adding image: {}'.format(image)) 
            if counter == 4:
                pdf.add_page()
                counter = 0

            if counter == 0:
                pdf.cell(50, 10, '{}'.format(get_title(image)), 1)
                pdf.image(image,10,70,80,60)
            elif counter == 1:
                pdf.image(image, 110, 70, 80, 60)
            elif counter == 2:
                pdf.image(image, 10, 170, 80, 60)
            elif counter == 3: 
                pdf.image(image, 110, 170, 80, 60)

            counter += 1

        pdf.output('{}/charts.pdf'.format(location), 'F')
Example #56
0
def tab_create(Onsets,Filename_):
    quantisation_per_beat=4
    bars_per_line=4
    notation=['x','o','o']
    pre_trackname=Filename_.split('/')
    TrackName=pre_trackname[len(pre_trackname)-1].split('.')[0]+' Drum Tab'
    
    subprocess.call(["DBNDownBeatTracker","single","-o","DB.txt",Filename_])

    DBFile=open("DB.txt")
    DBFile=DBFile.read().split('\n')
    DBFile=DBFile[:len(DBFile)-1]
    for i in range(len(DBFile)):
        DBFile[i]=DBFile[i].split('\t')
        DBFile[i]=np.array([float(DBFile[i][0]),int(DBFile[i][1])])
        
    grid=[]
    if len(DBFile)>0:
        max_beat=np.max(np.array(DBFile),0)[1]
        beat_dif=1/float(quantisation_per_beat)
        for i in range(len(DBFile)-1):
            k=np.arange(DBFile[i][0],DBFile[i+1][0],(DBFile[i+1][0]-DBFile[i][0])/float(quantisation_per_beat))
            beat_poss=DBFile[i][1]
            for j in k:
               if beat_poss >= max_beat:
                   beat_poss=0
               grid.append([j,beat_poss])
               beat_poss+=beat_dif
               
        quantisation_per_bar=int(max_beat*quantisation_per_beat)
        
        grid=np.array(grid)
        
        num_bars=np.ceil(grid.shape[0]/float(quantisation_per_bar))
        bar_grid=[]
        bar_start=np.expand_dims(np.transpose(['HH','SD','KD']),1)
        bar_end=np.expand_dims(np.transpose(['|','|','|']),1)
        for i in range(3):
            bar_grid.append(['|'])
            for j in range(quantisation_per_bar):
                    bar_grid[i].append('-')
        
        
        num_lines=np.int(np.floor(num_bars/float(bars_per_line)))
        last_line=num_bars%float(bars_per_line)
        lines=[]
        lines_new=[]
        for i in range(num_lines):
            lines.append(np.concatenate((bar_start,np.tile(bar_grid,int(bars_per_line)),bar_end),1))
            lines_new.append([])
            for j in range(len(lines[i])):
                lines[i][j]=list(lines[i][j])
        
        
        
        if last_line > 0:
            i+=1
            lines.append(np.concatenate((bar_start,np.tile(bar_grid,int(last_line)),bar_end),1))
            lines_new.append([])
            for j in range(len(lines[i])):
                lines[i][j]=list(lines[i][j])
        
                    
        
        
        onset_locations=[]
        onset_line=[]
        onset_bar_location=[]
        onset_tab_location=[]
        
        for i in range(len(Onsets)):
            onset_locations.append([])
            onset_line.append([])
            onset_tab_location.append([])
            onset_bar_location.append([])
            for j in range(len(Onsets[i])):
                onset_locations[i].append(np.argmin(np.abs(grid[:,0]-Onsets[i][j])))
                onset_line[i].append(np.floor(onset_locations[i][j]/(float(quantisation_per_bar*bars_per_line))))
                onset_bar_location[i].append((onset_locations[i][j]-((onset_line[i][j])*quantisation_per_bar*bars_per_line)))
                onset_tab_location[i].append(onset_bar_location[i][j]+2)
                for k in range(bars_per_line-1):
                    if onset_bar_location[i][j]>=(k+1)*quantisation_per_bar:
                        onset_tab_location[i][j]+=1
                lines[int(onset_line[i][j])][i][int(onset_tab_location[i][j])]=notation[i]
            
        lines_new=[]
        
        for i in range(len(lines)):
            lines_new.append([])
            for j in range(len(lines[i])):
                lines_new[i].append(''.join(lines[i][j]))        
        
        
        pdf = FPDF(format='A4')
        pdf.add_page()
        pdf.set_font("Courier", size=12)
        pdf.cell(200, 10, txt=TrackName,ln=1, align="C")
        pdf.set_font("Courier", size=10)
        
        for i in range(len(lines_new)):
            for j in range(len(lines_new[i])):
                pdf.cell(0,3,txt=lines_new[i][j],ln=1,align="C")
            pdf.cell(0,5,txt='',ln=1,align="C")
        pdf.output(pre_trackname[len(pre_trackname)-1].split('.')[0]+'_drumtab.pdf')
        
        
        os.remove("DB.txt")
    else: 
        print('Error: No beat detected')
Example #57
0
def tab_create(Onsets,Filename_,save_dir_):
    quantisation_per_beat=4
    bars_per_line=4
    notation=['x','o','o']
    pre_trackname=Filename_.split('/')
    TrackName=pre_trackname[len(pre_trackname)-1].split('.')[0]+' Drum Tab'
    wav=Filename_.split('.')[0]+'.wav'
    subprocess.call(["DBNDownBeatTracker","single","-o","DB.txt",wav])

    DBFile=open("DB.txt")
    DBFile=DBFile.read().split('\n')
    DBFile=DBFile[:len(DBFile)-1]
    for i in range(len(DBFile)):
        DBFile[i]=DBFile[i].split('\t')
        DBFile[i]=np.array([float(DBFile[i][0]),int(DBFile[i][1])])
        
    grid=[]
    if len(DBFile)>0:
        max_beat=np.max(np.array(DBFile),0)[1]
        beat_dif=1/float(quantisation_per_beat)
        for i in range(len(DBFile)-1):
            k=np.arange(DBFile[i][0],DBFile[i+1][0],(DBFile[i+1][0]-DBFile[i][0])/float(quantisation_per_beat))
            beat_poss=DBFile[i][1]
            for j in k:
               if beat_poss >= max_beat:
                   beat_poss=0
               grid.append([j,beat_poss])
               beat_poss+=beat_dif
               
        quantisation_per_bar=int(max_beat*quantisation_per_beat)
        
        grid=np.array(grid)
        
        num_bars=np.ceil(grid.shape[0]/float(quantisation_per_bar))
        bar_grid=[]
        bar_start=np.expand_dims(np.transpose(['HH','SD','KD']),1)
        bar_end=np.expand_dims(np.transpose(['|','|','|']),1)
        for i in range(3):
            bar_grid.append(['|'])
            for j in range(quantisation_per_bar):
                    bar_grid[i].append('-')
        
        
        num_lines=np.int(np.floor(num_bars/float(bars_per_line)))
        last_line=num_bars%float(bars_per_line)
        lines=[]
        lines_new=[]
        for i in range(num_lines):
            lines.append(np.concatenate((bar_start,np.tile(bar_grid,int(bars_per_line)),bar_end),1))
            lines_new.append([])
            for j in range(len(lines[i])):
                lines[i][j]=list(lines[i][j])
        
        
        
        if last_line > 0:
            i+=1
            lines.append(np.concatenate((bar_start,np.tile(bar_grid,int(last_line)),bar_end),1))
            lines_new.append([])
            for j in range(len(lines[i])):
                lines[i][j]=list(lines[i][j])
        
                    
        
        
        onset_locations=[]
        onset_line=[]
        onset_bar_location=[]
        onset_tab_location=[]
        
        for i in range(len(Onsets)):
            onset_locations.append([])
            onset_line.append([])
            onset_tab_location.append([])
            onset_bar_location.append([])
            for j in range(len(Onsets[i])):
                onset_locations[i].append(np.argmin(np.abs(grid[:,0]-Onsets[i][j])))
                onset_line[i].append(np.floor(onset_locations[i][j]/(float(quantisation_per_bar*bars_per_line))))
                onset_bar_location[i].append((onset_locations[i][j]-((onset_line[i][j])*quantisation_per_bar*bars_per_line)))
                onset_tab_location[i].append(onset_bar_location[i][j]+2)
                for k in range(bars_per_line-1):
                    if onset_bar_location[i][j]>=(k+1)*quantisation_per_bar:
                        onset_tab_location[i][j]+=1
                lines[int(onset_line[i][j])][i][int(onset_tab_location[i][j])]=notation[i]
            
        lines_new=[]
        
        for i in range(len(lines)):
            lines_new.append([])
            for j in range(len(lines[i])):
                lines_new[i].append(''.join(lines[i][j]))  
                
        os.remove("DB.txt")
        if save_dir_!=None:
            current_dir=os.getcwd()
            os.chdir(save_dir_)
        pdf = FPDF(format='A4')
        pdf.add_page()
        pdf.set_font("Courier", size=12)
        pdf.cell(200, 10, txt=TrackName,ln=1, align="C")
        pdf.set_font("Courier", size=10)
        
        for i in range(len(lines_new)):
            for j in range(len(lines_new[i])):
                pdf.cell(0,3,txt=lines_new[i][j],ln=1,align="C")
            pdf.cell(0,5,txt='',ln=1,align="C")
        pdf.output(pre_trackname[len(pre_trackname)-1].split('.')[0]+'_drumtab.pdf')
        if save_dir_!=None:
            os.chdir(current_dir)
        
        
    else: 
        print('Error: No beat detected')
Example #58
0
def report(thandle, gain_tweets, loss_tweets):
    """
    Write report.
    """
    from fpdf import FPDF
    import textwrap

    print('Writing report...')
    pdf = FPDF()

    # Add a page
    pdf.add_page()

    # set style and size of font
    # that you want in the pdf
    pdf.set_font("Arial", size=16)

    # create a cell
    pdf.cell(200,
             10,
             txt='Ads that likely caused some loss of Followers:\n\n',
             ln=1,
             align='L')
    pdf.cell(200, 10, txt='', ln=2, align='L')

    # add another cell
    pdf.set_font("Arial", size=14)
    tweet_string = ''
    fact = 3
    count = 0
    tweets = []
    while count < fact:
        random.shuffle(loss_tweets)
        rand_tweet = loss_tweets[-1]
        tweets.append(rand_tweet)
        mask = [(tweet != rand_tweet) for tweet in loss_tweets]
        loss_tweets = [
            loss_tweets[i] for i in range(len(loss_tweets)) if mask[i]
        ]
        count += 1

    for i, d in enumerate(tweets):
        string_encode = d.encode('ascii', 'ignore')
        string_decode = string_encode.decode()
        d = textwrap.wrap(string_decode, width=65)

        for j in d:
            pdf.cell(200, 10, txt=j, ln=fact, align='L')
            fact += 0.5
        pdf.cell(200, 10, txt='', ln=fact, align='L')
        fact += 1

    pdf.output('{}/lossy_tweets.pdf'.format(thandle))
    pdf.close()

    pdf = FPDF()

    dupes_gain = set(
        [x for n, x in enumerate(gain_tweets) if x in gain_tweets[:n]])

    # Add a page
    pdf.add_page()

    # set style and size of font
    # that you want in the pdf
    pdf.set_font("Arial", size=16)

    # create a cell
    pdf.cell(200,
             10,
             txt='Ads that likely caused some gain in Followers:\n\n',
             ln=1,
             align='L')
    pdf.cell(200, 10, txt='', ln=2, align='L')

    # add another cell
    pdf.set_font("Arial", size=14)
    tweet_string = ''
    fact = 3
    count = 0
    tweets = []
    while count < fact:
        random.shuffle(gain_tweets)
        rand_tweet = gain_tweets[-1]
        tweets.append(rand_tweet)
        mask = [(tweet != rand_tweet) for tweet in gain_tweets]
        gain_tweets = [
            gain_tweets[i] for i in range(len(gain_tweets)) if mask[i]
        ]
        count += 1

    for i, d in enumerate(tweets):
        string_encode = d.encode('ascii', 'ignore')
        string_decode = string_encode.decode()
        d = textwrap.wrap(string_decode, width=65)

        for j in d:
            pdf.cell(200, 10, txt=j, ln=fact, align='L')
            fact += 0.5
        pdf.cell(200, 10, txt='', ln=fact, align='L')
        fact += 1

    pdf.output('{}/gainy_tweets.pdf'.format(thandle))
    pdf.close()

    print('Done!\n')
Example #59
0
# -*- coding: utf-8 -*-
from fpdf import FPDF

pdf=FPDF()
#Adicionando página
pdf.add_page()
#Adicionando configurações de Fonte
pdf.set_font('Arial','B',16)
#Inserindo linhas cell by cell.
pdf.cell(0,10,'CONTRATO DE LOCAÇÃO RESIDENCIAL', 1,1 , 'C')

#Locador
pdf.set_font('Arial','I',8)
pdf.cell(33,5,'LOCADOR(A):',1,1 , 'L')
pdf.cell(0,5,'..................................., brasileiro, solteiro, comerciante,', 0,1 , 'J')
pdf.cell(0,5,'portador da cédula de identidade RG ....................../SSP.SP e inscrito no CPFMF sob nº ................', 0,1 , 'J')
#Locatario
pdf.cell(33,5,'LOCATÁRIO(A):',1,1 , 'L')
pdf.cell(0,5,'................................................, brasileiro, casado, autônomo,', 0,1 , 'J')
pdf.cell(0,5,', portador da cédula de identidade RG .................SSP/SP e inscrito no CPFMF sob nº ................... ', 0,1 , 'J')
pdf.ln(5)
#Objeto
pdf.set_font('Arial','B',8)
pdf.cell(0,5,'OBJETO:',1,1 , 'L')
pdf.set_font('Arial','',9)
pdf.cell(0,5,'A CASA SOB Nº ....., DA RUA ............................., ou A UNIDADE RESIDENCIAL SOB N ....., SITIO NA RUA', 0,1 ,'')
pdf.cell(0,5,' ............. N ...,,0,1,'')
pdf.ln(5)
#--
pdf.set_font('Arial','I',8)
pdf.cell(0,5,'Por este particular instrumento, as partes supraqualificadas resolvem, de comum acordo e de livre e espontânea',0,1,'L')
Example #60
0
from fpdf import FPDF

pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Welcome to Python!", ln=1, align="C")
pdf.output("simple_demo.pdf")