Esempio n. 1
1
def dotest(outputname, nostamp):
    # filename - output filename
    # nostamp - do no use stamp in result file
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font('Arial', '', 16)
    pdf.write(8, "Test template")
    pdf.output(outputname, 'F')
Esempio n. 2
0
    def __init__(self):
        FPDF.__init__(self)
        FPDF.AliasNbPages(self, "{nb}")

        self.toc = []
        self.toc_auto_num = [0]
        self.toc_current_level = 0
Esempio n. 3
0
def imprimir(fac,mat,dni):
    pdf = FPDF()
    pdf.add_page()
    header(pdf,fac,mat,dni)
    body(pdf,fac)
    pdf.output('prueba.pdf','F')
    os.system('/usr/bin/evince prueba.pdf')
Esempio n. 4
0
    def test_ScaleFont(self):
        self.do_for_each_DocItem_class(InlineMathBlock())

        pdf = FPDF()
        initPDF(pdf)
        
        block = InlineMathBlock()
        block.appendItem(MathFunction('tan'))
        block.appendItem(MathVariable('x'))
        block.appendItem(MathSign('='))
        block.appendItem(MathFunction('sin'))
        block.appendItem(MathVariable('x'))
        block.appendItem(MathSign('/'))
        block.appendItem(MathFunction('cos'))
        block.appendItem(MathVariable('x'))
        
        block.resizePDF(pdf, 10, 20)
        block.cellPDF(pdf)
        
        block.scaleFont(0.8)
        block.resizePDF(pdf, 10, 30)
        block.cellPDF(pdf)
        
        block.scaleFont(2.0)
        block.resizePDF(pdf, 10, 40)
        block.cellPDF(pdf)
        
        pdf.output('out/document/test_ScaleFactor.pdf', 'F')
Esempio n. 5
0
    def test_MathBrackets(self):
        tmp = MathBrackets()
        tmp.appendItem(MathVariable('x'))
        self.do_for_each_DocItem_class(tmp)

        pdf = FPDF()
        initPDF(pdf)
        
        block = InlineMathBlock()
        block.appendItem(MathVariable('x'))
        block.appendItem(MathSign('+'))
        block.appendItem(MathVariable('y'))

        brackets = MathBrackets()
        brackets.appendItem(block)

        brackets.resizePDF(pdf, 10, 10)
        brackets.cellPDF(pdf)
        
        p = MathPower()
        p.appendItem(brackets)
        p.appendItem(MathVariable('q'))
        p.resizePDF(pdf, 10, 20)
        p.cellPDF(pdf)

        pdf.output('out/document/test_MathBrackets.pdf', 'F')
Esempio n. 6
0
    def test_MathSubSuperscript(self):
        self.do_for_each_DocItem_class(MathSubSuperscript(MathVariable('x'),MathVariable('2')))

        pdf = FPDF()
        initPDF(pdf)
        
        #----------------------------
        sss = MathSubSuperscript(MathVariable('x'),MathVariable('n'),MathVariable('2'))
        sss.resizePDF(pdf, 10, 10)
        sss.cellPDF(pdf)
        
        #----------------------------
        sss = MathSubSuperscript(MathVariable('x'),MathVariable('i'))
        sss.resizePDF(pdf, 10, 20)
        sss.cellPDF(pdf)
        
        #----------------------------
        block = InlineMathBlock()
        block.appendItem(MathVariable('x'))
        block.appendItem(MathSign('+'))
        block.appendItem(MathVariable('y'))

        brackets = MathBrackets()
        brackets.appendItem(block)

        sss = MathSubSuperscript(brackets,None,MathVariable('p'))
        sss.resizePDF(pdf, 10, 40)
        sss.cellPDF(pdf)
        
        pdf.output('out/document/test_MathSubSuperscript.pdf', 'F')
Esempio n. 7
0
 def test_InlineMathParser(self):
     pdf = FPDF()
     lp.initPDF(pdf)
     
     def tester(pdf,s, y):
         p = lp.InlineMathParser()
         p.match( s )
         self.assertTrue( p.hasMatch() )
         par = p.docItem
         par.resizePDF(pdf,10,y)
         par.cellPDF(pdf)
         
     tester(pdf, 'a+b-1', 10)
     tester(pdf, r'\frac{ \sin(2\alpha) }{\cos\alpha}', 20)
     tester(pdf, r'\sum_{i=0}^{N/2} x', 40)
     tester(pdf, r'\prod_{j=1}^{\Omega} (j+1)', 60)
     tester(pdf, r'\prod_{j} (j+1)', 80)
     tester(pdf, r'\prod^{\Omega} (j+1)', 100)
     tester(pdf, r'x^{y}', 120)
     tester(pdf, r'1+x_{i}^{j}', 140)
     tester(pdf, r'\sum_{j}j^{2}',160)
     #self.assertRaises(Exception, tester(pdf, '\frac{}{}', 170))
     tester(pdf, r'x^{\sum_{j}j^{2}}',180)
     
     pdf.output('out/latex/test_inline_maths.pdf', 'F')
Esempio n. 8
0
def imprimir(fac,mat,dni):
    pdf = FPDF()
    pdf.add_page()
    header(pdf,fac,mat,dni)
    archivo='Factura'+fac+'.pdf'
    pdf.output(archivo,'F')
    os.system('/usr/bin/evince '+archivo)
Esempio n. 9
0
    def test_Two_Paragraphs(self):
        
        s = long_string
        pdf = FPDF()
        lp.initPDF(pdf)

        p1 = lp.ParagraphParser()
        p1.match( s )
        self.assertTrue( p1.hasMatch() )
        par1 = p1.docItem
        par1.resizePDF(pdf)
        par1.cellPDF(pdf)
        par1.showRect(pdf)

        p2 = lp.ParagraphParser()
        p2.match( s )
        self.assertTrue( p1.hasMatch() )
        par2 = p2.docItem
        par2.resizePDF(pdf, 0, par1.rect.height() + 5)
        par2.cellPDF(pdf)
        
        par2.resizePDF(pdf, 0, 40)
        par2.cellPDF(pdf)
        
        par2.width = -1
        par2.resizePDF(pdf, 20, 60)
        par2.cellPDF(pdf)
        
        pdf.output('out/latex/test_Two_Paragraphs.pdf', 'F')
Esempio n. 10
0
    def test_Word_cellPDF(self):
        
        p = lp.WordParser()
        s = r'alpha\beta'
        p.match(s)
        self.assertTrue( p.hasMatch() )
        self.assertEquals( p.getMatch(s), 'alpha')
        pdf=FPDF()
        initPDF(pdf)
        
        p.docItem.resizePDF( pdf )
        p.docItem.cellPDF( pdf )

        p.docItem.resizePDF( pdf, p.docItem.rect.x1() + 10, p.docItem.rect.y0() )
        p.docItem.cellPDF( pdf )

        p.docItem.resizePDF( pdf, p.docItem.rect.x1() + 10, p.docItem.rect.y0() )
        p.docItem.cellPDF( pdf )
        
        r = p.docItem.rect

        p = lp.CommandParser(lp.ParagraphItemCreator)
        p.match(r'\alpha')
        setFontPDF(pdf,'symbol')
        #pdf.set_font('DejaVu','',11)

        p.docItem.resizePDF( pdf, r.x1() + 10, r.y0() )
        p.docItem.cellPDF( pdf )
        
        pdf.output('out/latex/test_Word_cellPDF.pdf', 'F')
Esempio n. 11
0
 def __init__(self, nomcom, pdfconfig, translations):
     FPDF.__init__(self)
     self.toc_entries = []
     self.appendix_entries = []
     self.commune = nomcom
     self.translations = translations
     self.pdfconfig = pdfconfig
     self.communelogopath = 'ecussons\\' + str(self.commune) + '.jpg'
Esempio n. 12
0
def imprimir(fac,mat,dni):
    pdf = FPDF()
    pdf.add_page()
    header(pdf,fac,mat,dni)
    precio = cuerpo(pdf,fac)
    footer(pdf,precio)
    pdf.output('factura'+fac+'.pdf','F')
    os.system('/usr/bin/evince factura'+fac+'.pdf')
Esempio n. 13
0
 def __init__(self, theme, theme_dir):
     FPDF.__init__(self, orientation="L")
     self.theme = theme
     self.theme_dir = theme_dir
     self.set_margins(self.theme["lmargin-slide"],
                      self.theme["tmargin-slide"])
     self.img = None
     self.slide_title = None
Esempio n. 14
0
    def __init__(self, datosPersonal):
        '''Parametros recibidos:1, Tipo Lista (ficha, nombre, tipov, cedula)
        Se ejecuta el metodo __init__ de la clase DetrasMyPDF()'''

        #Se ejecuta el init de la clase Padre
        FPDF.__init__(self, orientation='P',unit='mm',format=(55,84))
        
        #Se guarda el parametro pasado
        self.datosPersonal = datosPersonal
Esempio n. 15
0
def imprimir(fac,mat,dni):
    pdf = FPDF()
    pdf.add_page()
    header(pdf,fac,mat,dni)
    cuerpo(pdf,fac)
    footer(pdf)
    factura = 'Factura'+fac+'.pdf'
    pdf.output(factura,'F')
    os.system('/usr/bin/evince %s' % factura)
Esempio n. 16
0
def imprimir(fac,mat,dni):
    
    pdf = FPDF()
    pdf.add_page()
    header(pdf,fac,mat,dni)
    nombreArchivo = 'Factura'+fac+'.pdf'
    
    pdf.output('/home/dloirport/facturas/'+nombreArchivo,dest='F')
    ruta = '/usr/bin/evince /home/dloirport/facturas/'+nombreArchivo
    os.system(ruta)
Esempio n. 17
0
    def test_MathBigBrackets1(self):

        pdf = FPDF()
        initPDF(pdf)
        
        brackets = MathBigBrackets('(',')', b( f(n('1'),n('2'))) )
        brackets.resizePDF(pdf, 10, 20)
        brackets.cellPDF(pdf)
        
        pdf.output('out/document/test_MathBigBrackets1.pdf', 'F')
Esempio n. 18
0
 def test_TitleParser(self):
     pdf = FPDF()
     lp.initPDF(pdf)
     s = r'\title {The Title}  ' 
     p = lp.TitleParser()
     p.match( s )
     self.assertTrue( p.hasMatch() )
     p.docItem.resizePDF(pdf)
     p.docItem.cellPDF(pdf)
     pdf.output('out/latex/test_TitleParser.pdf', 'F')
Esempio n. 19
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()
Esempio n. 20
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))
Esempio n. 21
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)
Esempio n. 22
0
def generar_codigos(provincia,ciudad,numeroInicial,cantidad):
	total_imagenes = cantidad * 2
	paginas =  calcular_cantidad_paginas(total_imagenes)
	archivo = FPDF('P','mm','A4')
	archivo.add_page()
	for pagina in range(0,paginas):
		eje_x = 0
		for linea in range(0,12):
			if(cantidad <= 0):
				break
			for codigo in range(0,2):
				if(cantidad <= 0):
					break
				numero =  completar(str(numeroInicial))
				numero = str(provincia) + str(ciudad) + numero
				digito = digitoverificador(numero)
				numero = numero + str(digito)
				for imagen in range(0,2):
					archivo.image(crear_barcode(numero),eje_x * 50, linea * 25 , TAMANIO_CODIGO)
					eje_x += 1
				cantidad = cantidad -1
				numeroInicial += 1
			eje_x = 0
		if(cantidad > 0):
			archivo.add_page()
	archivo.output(os.path.join('generated','codigos.pdf'),'F')
	shutil.rmtree(os.path.join('generated','temp'))
Esempio n. 23
0
def gen_pdf():
    pdf = FPDF()
    pdf.add_page()
    xPos = 0
    yPos = 1    
    for i in range(1, numOfCircles + 1):
        increments = 200 / numOfCircles
        cv2.imwrite(str(i) + 'circle.png', gen_single_circle(500+100, ((increments * i)+100)))
        cv2.imshow('circle.png', gen_single_circle(500+100, ((increments * i)+100)))
        
        k = cv2.waitKey(200) & 0xFF
        xPos += 1
        x = (xPos * (circleDiameter + (circleDiameter / 5)))-circleDiameter
        y = (yPos * (circleDiameter + (circleDiameter / 5)))
        sys.stdout.write('(' + str(x) + ' , ' + str(y) + ') ')
        pdf.image(str(i) + 'circle.png', x, y, circleDiameter + 3, circleDiameter + 3, 'png')    
        
        os.remove(str(i) + 'circle.png');
        
        if xPos > numberPerRow-1:
            print ""
            yPos += 1
            xPos = 0
        if yPos > numberPerColum:
            if (i != (numOfCircles)):
                pdf.add_page()
                print "-------------------------------------"
                xPos = 0
                yPos = 1
    pdf.output('BETA.pdf', 'F')
Esempio n. 24
0
 def test_Title(self):
     
     pdf = FPDF()
     lp.initPDF(pdf)
     title = lp.Title()
     title.appendItem(lp.Word('The'))
     title.appendItem(lp.Word('Title'))
     title.resizePDF(pdf)
     title.cellPDF(pdf)
     title.showRect(pdf)
     pdf.output('out/latex/test_Title.pdf', 'F')
Esempio n. 25
0
 def test_initPDF(self):
     
     p = lp.ParagraphParser()
     s = 'The year 1866 was marked by a bizarre development'
     s += r' \alpha, \beta, \gamma Hello!'
     p.match( s )
     self.assertTrue( p.hasMatch() )
     doc = p.docItem
     pdf=FPDF()
     lp.initPDF(pdf)
     doc.resizePDF(pdf)
     doc.cellPDF(pdf)
     pdf.output('out/latex/test_initPDF.pdf', 'F')
Esempio n. 26
0
    def test_MathBelowAndAbove(self):
        tmp = MathBelowAndAbove()
        tmp.appendItem(MathVariable('x'))
        self.do_for_each_DocItem_class(tmp)
        
        pdf = FPDF()
        initPDF(pdf)
        
#        block = InlineMathBlock()
#        block.appendItem(MathVariable('n'))
#        block.appendItem(MathSign('='))
#        block.appendItem(MathVariable('0'))
        
        sigma = Symbol('Sigma')
        sigma.scaleFont(2.0)

        s = MathBelowAndAbove()
        s.appendItem(sigma)
        s.appendItem(InlineMathBlock(MathVariable('n'),MathSign('='),MathNumber('0')))
        s.appendItem(MathVariable('N'))
        
        s.resizePDF(pdf, 10, 10)
        s.cellPDF(pdf)
        
        pi = Symbol('Pi')
        pi.scaleFont(2.0)

        prod = MathBelowAndAbove(pi,
                                 InlineMathBlock(MathVariable('i'),MathSign('='),MathNumber('1')),
                                 MathVariable('M')
                                 )
        
        prod.resizePDF(pdf, 10, 40)
        prod.cellPDF(pdf)
        
        lim = MathBelowAndAbove(MathFunction('lim'),
                                InlineMathBlock(MathVariable('x'),MathSign('->'),MathVariable('4'))
                                )
        
        lim.resizePDF(pdf, 10, 60)
        lim.cellPDF(pdf)
        
        tilde = MathBelowAndAbove(Symbol('beta'),
                                  None,
                                  MathSign('~')
                                  )
        
        tilde.resizePDF(pdf, 10, 80)
        tilde.cellPDF(pdf)
        
        pdf.output('out/document/test_MathBelowAndAbove.pdf', 'F')
Esempio n. 27
0
    def test_MathColumn(self):
        self.do_for_each_DocItem_class(MathColumn())

        pdf = FPDF()
        initPDF(pdf)
        
        block = MathColumn(InlineMathBlock(MathVariable('x'),MathSign('='),MathVariable('0')),
                           InlineMathBlock(MathVariable('y'),MathSign('='),MathVariable('0')),
                           InlineMathBlock(MathVariable('z'),MathSign('='),MathVariable('0'))
                           )
        
        block.resizePDF(pdf, 10, 20)
        block.cellPDF(pdf)
        pdf.output('out/document/test_MathColumn.pdf', 'F')
Esempio n. 28
0
    def test_MathSum(self):
        self.do_for_each_DocItem_class(MathSum())

        pdf = FPDF()
        initPDF(pdf)
        
        summ = MathSum(InlineMathBlock(MathVariable('i'),MathSign('='),MathVariable('1')),
                     MathVariable('M')
                     )
        
        summ.resizePDF(pdf, 10, 20)
        summ.cellPDF(pdf)
        
        pdf.output('out/document/test_MathSum.pdf', 'F')
Esempio n. 29
0
    def test_MathProd(self):
        self.do_for_each_DocItem_class(MathProd())

        pdf = FPDF()
        initPDF(pdf)
        
        prod = MathProd(InlineMathBlock(MathVariable('i'),MathSign('='),MathVariable('1')),
                     MathVariable('M')
                     )
        
        prod.resizePDF(pdf, 10, 10)
        prod.cellPDF(pdf)
        
        pdf.output('out/document/test_MathProd.pdf', 'F')
Esempio n. 30
0
    def test_Word(self):
        self.do_for_each_DocItem_class(Word('word'))

        w = Word('word')
        pdf = FPDF()
        initPDF(pdf)
        # the bounding rect is't empty
        w.resizePDF(pdf, 1, 2)
        self.assertGreater(w.rect.x1(), w.rect.x0())
        self.assertGreater(w.rect.y1(), w.rect.y0())
        self.assertEqual(w.text, 'word')
        self.assertEqual(w.style, 'body')
        w.cellPDF(pdf)
        pdf.output('out/document/test_Word.pdf', 'F')
Esempio n. 31
0
# https://pyfpdf.readthedocs.io/en/latest/
# !pip3 install fpdf
from fpdf import FPDF
from api.pokedex import pokedex
import pandas as pd

# FPDF('P', 'mm', 'A4')
pdf = FPDF()
pdf.add_page()

# fpdf.set_font(family, style = '', size = 0)
pdf.set_font("Arial", "B", 12)

# fpdf.text(x: float, y: float, txt: str)
pdf.text(10, 10, "Hello, World!")
pdf.text(10, 15, "Hola, Mundillo!")

# fpdf.set_xy(x: float, y: float)
pdf.set_xy(10, 20)

# fpdf.cell(w, h = 0, txt = '', border = 0, ln = 0, align = '', fill = False, link = '')
pdf.cell(0,
         h=10,
         txt='Snorlax Evolutive Line',
         border=1,
         ln=1,
         align='C',
         fill=False,
         link='')

poke_data = pokedex("snorlax")
 def write_into_pdf(self, input):
     for code in input:
         print("Gift Code: ", code)
         pdf = FPDF()
         pdf.add_page()
         pdf.add_font('Raleway', '', r'./font/Raleway-SemiBold.ttf', uni=True)
         pdf.set_font(family='Raleway', size=12)
         # TODO: setting for Kiwi Bank
         pdf.set_text_color(0, 61, 54)
         pdf.text(59, 259.5, code)
         # pdf.text(59, 259.8, code)
         pdf.output('./gift-codes/a5-portrait/gift-code-{}.pdf'.format(code))
Esempio n. 33
0
# Create a ZipFile Object and load sample.zip in it
file_name1 = "theHarvester.zip"
with ZipFile(file_name1, 'r') as zipObj:
    # Get list of ZipInfo objects
    listOfiles = zipObj.infolist()
    listOfiles = sorted(listOfiles, key=lambda x: x.file_size)

# TODO delete all folders properly
for element in listOfiles:
    if (element.filename[-1:] == '/'):
        listOfiles.remove(element)
        # print(fileName)

        # listOfiles.remove('theHarvester-master/bin/')
        # Iterate of over the list of ZipInfo objects & access members of the object
for elem in listOfiles:
    print(elem.filename + ' : ', elem.file_size)

from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 0)
pdf.set_font('arial', 'B', 10.0)
for i in range(1, 10):
    text = '\n' + str(
        i) + 'file name: ' + listOfiles[i].filename + '  size: ' + str(
            listOfiles[i].file_size)
    pdf.cell(ln=i, h=5.0, align='M', w=0, txt=text, border=0)
pdf.output('analyzed results.pdf', 'F')
Esempio n. 34
0
def mergeBookmarks(bookmarks: dict, out_file: str):
    pdf = FPDF(orientation="P", unit="pt", format="A4")
    for y, (chapter, files) in enumerate(bookmarks.items()):
        files.sort(
            key=lambda file: int(
                re.search(r"\d+", os.path.splitext(os.path.split(file)[1])[0])[0]
            )
        )

        for i, imagef in enumerate(files):
            logger.debug(
                f"pdf: adding file {i + 1}/{len(files)} of chapter {y + 1}/{len(bookmarks.items())}"
            )
            try:
                with Image.open(imagef) as image:
                    if image.width > image.height:
                        pdf.add_page("vertical")
                        pdf.image(imagef, x=0, y=00, w=842, h=596)
                    else:
                        tilled = tile(imagef)
                        for image in tilled:
                            pdf.add_page()
                            try:
                                if stretch or len(tilled) == 1:
                                    pdf.image(image, x=0, y=00, h=842, w=596)
                                else:
                                    pdf.image(image, x=0, y=00, w=596)  # h=842,
                            except Exception as e:
                                logger.error(
                                    f"pdf: failed to add image {image} to pdf, a blank page is added"
                                )
            except OSError as e:
                pdf.add_page()
            yield min(i / len(files), 0.9)
    yield 0.9
    pdf.output(out_file, "F")
Esempio n. 35
0
def download(id):
    post = get_post(id)
    title = post['title']
    body = post['body']
    print('>>>>>>>>>>', title)
    print('>>>>>>>>>>', body)

    pdf = FPDF()
    pdf.add_page()
    pdf.set_xy(0, 0)
    pdf.set_font('arial', 'B', 20.0)
    pdf.cell(0, 10, txt=title, ln=1, align="C")
    pdf.set_font('arial', 'B', 13.0)
    line = ''
    for text in body:
        if text == '\n':
            pdf.cell(0, 10, txt=line, ln=1, align="L")
            line = ''
        else:
            line += text
    if len(line) != 0:
        pdf.cell(0, 10, txt=line, ln=1, align="L")
    pdf.output('{}.pdf'.format(title), 'F')
    return send_file('/home/dev/.venv/try flask/flaskapp/{}.pdf'.format(title),
                     attachment_filename='{}.pdf'.format(title))
Esempio n. 36
0
def get_pdf_factura(factura, empresaid, usuario):
    empresa = Empresa.objects.get(pk=empresaid)
    params = empresa.parametros()
    invoice = representacion_factura_str(factura)
    fecha = invoice['fecha']
    pdf = FPDF()
    # pdf.compress = False
    pdf.add_page(orientation=params.orientacion)
    pdf.set_font(params.fuente_tipo, '', params.fuente_tamano)
    pdf.text(params.factura_fecha_x, params.factura_fecha_y, fecha)
    pdf.text(params.cliente_telefono_x, params.cliente_telefono_y, invoice['cliente']['telefono'])

    if len(invoice['cliente']['nombre']) < 50:
        pdf.text(params.cliente_nombre_x, params.cliente_nombre_y, invoice['cliente']['nombre'])
    else:
        pdf.text(params.cliente_nombre_x1, params.cliente_nombre_y1, invoice['cliente']['nombre'][:51] + ' - ')
        pdf.text(params.cliente_nombre_x2, params.cliente_nombre_y2, invoice['cliente']['nombre'][51:])

    if len(invoice['cliente']['domicilio']) < 50:
        pdf.text(params.cliente_direccion_x, params.cliente_direccion_y, invoice['cliente']['domicilio'])
    else:
        pdf.text(params.cliente_direccion_x1, params.cliente_direccion_y1, invoice['cliente']['domicilio'][:51] + ' - ')
        pdf.text(params.cliente_direccion_x2, params.cliente_direccion_y2, invoice['cliente']['domicilio'][51:])

    pdf.text(params.cliente_ruc_x, params.cliente_ruc_y, invoice['cliente']['identificacion'])

    i = 0
    for detalle in invoice['detalles']:
        pdf.text(params.cantidad_x, params.cantidad_y + (i * 5), str(int(detalle['cantidad'])))
        if detalle['valor_descuento']:
            pdf.text(params.cantidad_x + 2, params.cantidad_y + (i * 5), "(*)")
        if detalle['producto']:
            pdf.text(params.producto_x, params.producto_y + (i * 5), fix_productos_str(detalle['producto']))
        elif detalle['servicio']:
            pdf.text(params.producto_x, params.producto_y + (i * 5), fix_servicios_str(detalle['servicio']))
        else:
            pdf.text(params.producto_x, params.producto_y + (i * 5), fix_paquetes_str(detalle['paquete']))
        pdf.text(params.precio_x, params.precio_y + (i * 5), "$ {}".format(detalle['precio']))
        pdf.text(params.valor_x, params.valor_y + (i * 5), "$ {}".format(detalle['valor']))
        i += 1

    pdf.text(params.factura_enletras_x, params.factura_enletras_y, invoice['enletras'])
    pdf.text(params.factura_subtotal_x, params.factura_subtotal_y, "$ {}".format(invoice['subtotal']))
    pdf.text(params.factura_iva_x, params.factura_iva_y, "$ {}".format(invoice['iva']))
    pdf.text(params.factura_total_x, params.factura_total_y, "$ {}".format(invoice['total']))

    pdfname = 'factura' + invoice['numero'] + '_' + datetime.now().date().strftime('%Y%m%d_%H%M%S') + '.pdf'
    output_folder = os.path.join(JR_USEROUTPUT_FOLDER, usuario)
    try:
        os.makedirs(output_folder)
    except:
        pass
    pdf.output(os.path.join(output_folder, pdfname))

    return pdfname
Esempio n. 37
0
def i_proof(isbn, media_path):
    image_directory = media_path + "/art/upload/" + isbn

    if path.exists(image_directory):
        images = 'resized'
        basewidth = 400
        margin = 10
        imagelist = []
        location = ''
        outfile = ''
        imagePath = ''

        # out = 'resized'
        for dirName, subdirList, fileList in os.walk(image_directory):
            for fname in fileList:
                LowerCaseFileName = fname.lower()
                if LowerCaseFileName.endswith(
                        ".jpg") or LowerCaseFileName.endswith(
                            ".eps") or LowerCaseFileName.endswith(
                                ".gif") or LowerCaseFileName.endswith(
                                    ".png") or LowerCaseFileName.endswith(
                                        ".tif") or LowerCaseFileName.endswith(
                                            ".tiff"
                                        ) or LowerCaseFileName.endswith(
                                            ".jpeg"):
                    imagelist.append(dirName + "/" + fname)
            imagelist1 = []
            for infile in imagelist:
                im = Image.open(os.path.join(image_directory, infile))
                wpercent = (basewidth / float(im.size[0]))
                hsize = int((float(im.size[1]) * float(wpercent)))
                im = im.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
                location = os.path.dirname(infile)
                if not (os.path.exists(os.path.join(location, images))):
                    os.mkdir(os.path.join(location, images))
                outfile = os.path.join(
                    location, images,
                    os.path.splitext(os.path.basename(infile))[0] + ".png")
                imagelist1.append(outfile)
                out = im.convert("RGB")
                out.save(outfile, "PNG")

        margin = 30
        pdf = FPDF('P', 'mm', 'A4')
        x, y, w, h = 40, 40, 200, 250

        for imagePath in imagelist1:
            pdf.add_page()
            pdf.image(imagePath, 10, margin)
            pdf.set_font('Arial', 'B', 12)
            caption = os.path.splitext(os.path.basename(imagePath))[0]
            pdf.cell(10, 10, txt=caption)
            os.unlink(imagePath)

        pdf.output(image_directory + "/" + isbn + "_art_proof.pdf", "F")

        for dirName, subdirList, fileList in os.walk(image_directory):
            if images in dirName:
                os.rmdir(dirName)
        return "Art proofs generated succesfully! Path: art/upload/{}/{}_art_proof.pdf".format(
            isbn, isbn)
    else:
        return "Images are not available for ISBN {} inside art/upload folder.".format(
            isbn)
Esempio n. 38
0
#     self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')

from fpdf import FPDF

page_width = 210
page_height = 297

page_left_margin = 10
page_right_margin = 10
page_top_margin = 10
page_bottom_margin = 10

page_x_area = page_width - page_left_margin - page_right_margin
page_y_area = page_height - page_top_margin - page_bottom_margin

pdf = FPDF(orientation='P', unit='mm', format='A4')

pdf.set_author("Author Test Terminal")
pdf.set_creator("Creator Test Terminal")
pdf.set_subject("Exam Results")

pdf.add_page(orientation='P', format='A4', same=False)
pdf.set_left_margin(margin=10)
pdf.set_right_margin(margin=10)

pdf.alias_nb_pages()

# Draw border
pdf.line(10, 10, 200, 10)
pdf.line(10, 277, 200, 277)
pdf.line(10, 10, 10, 277)
Esempio n. 39
0
from fpdf import FPDF
pdf = FPDF()
pdf = FPDF(orientation='L', format='A5')
pdf.add_page()
#===================Adding Page Border Through Line===================
pdf.line(5, 5, 205, 5)  # Top Line
pdf.line(5, 5, 5, 143)  # Left Line
pdf.line(5, 143, 205, 143)  # Bottom Line
pdf.line(205, 5, 205, 143)  # Right Line
#====================Adding Some Candidate Details====================
pdf.set_font("Arial", style='UBI', size=18)
pdf.cell(200, 10, txt="Identity Card", align="C")
pdf.set_font("Arial", style='B', size=12)
pdf.text(x=15, y=50, txt="Name")
pdf.set_font("Arial", size=11)
pdf.text(x=50, y=50, txt=":Gagan Aggarwal")
pdf.set_font("Arial", style='B', size=12)
pdf.text(x=15, y=60, txt="Course")
pdf.set_font("Arial", size=11)
pdf.text(x=50, y=60, txt=":MCA (Master of Computer Application)")
pdf.set_font("Arial", style='B', size=15)
pdf.text(x=150, y=40, txt="Candidate Pic")
pdf.image(name="Gagan.jpg", x=140, y=45, w=50, h=50, type='jpg')
pdf.set_font("Arial", style='B', size=12)
pdf.text(x=15, y=70, txt="College")
pdf.set_font("Arial", size=11)
pdf.text(x=50, y=70, txt=":RBMI Greater Noida")
pdf.set_font("Arial", style='B', size=12)
pdf.text(x=15, y=80, txt="Address")
pdf.set_font("Arial", size=11)
pdf.text(x=50, y=80, txt=":Gamma 2, Greater Noida")
Esempio n. 40
0
#We have imported all the functions, that we have used in our program here.
from Scrapper import *
from exporting_excel import *
from xlwt import *
import requests
from bs4 import BeautifulSoup
from random import *
from pickle import *
from edit_med import *
import os
from fpdf import FPDF
import datetime
pdf = FPDF()
from pickle import *
from re import *
import PIL
from PIL import ImageTk, Image
import pyzbar.pyzbar as pbar
import requests
import cv2
import matplotlib as plt
title = Image.open("clinix logo.png")
import numpy as np
from tkinter import *
import tkinter.messagebox
x = 1
while x:

    class Everything:
        #This class generate a label along with three entries so that whenever we replace a value in a quantity
        #then it automatically generate a label for price.
Esempio n. 41
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')
Esempio n. 42
0
from fpdf import FPDF
from PIL import Image
from tqdm import tqdm


def resize(png):
    img = Image.open(png)
    new_width = 1920
    new_height = 1080
    img = img.resize((new_width, new_height), Image.ANTIALIAS)
    img.save(f'{png}_resized.png')  # format may what


imgdir = sys.argv[1]

images = [
    f for f in os.listdir(imgdir) if f.endswith('.png') and '_resized' not in f
]

h = int(297 / 1920 * 1080)
w = 297
print(f'{w}x{h}')
pdf = FPDF('L', 'mm', (h, w))

for f in tqdm(sorted(images)):
    pdf.add_page()
    png = os.path.join(imgdir, f)
    resize(png)
    pdf.image(f'{png}_resized.png', x=0, y=0, w=297, h=h)
pdf.output('output.pdf', 'F')

def atoi(text):
    return int(text) if text.isdigit() else text


def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    return [atoi(c) for c in re.split(r'(\d+)', text)]


#remove a dummy file which pops up
onlyfiles.remove('.DS_Store')
onlyfiles.sort(key=natural_keys)

print(onlyfiles)

pdf = FPDF()
pdf.add_page()

for img in onlyfiles:
    path = dir_path + img
    print(path)
    # pdf.image(path,None,None,210,297)
    pdf.image(path, None, None, 0, 0)

pdf.output('Aawaj_ki_tabahi.pdf', 'F')
def parameters_and_thresholds(params):
	
	pdf = FPDF()
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "Parameters and Thresholds", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)
	pdf.set_font('Arial', '', 16)
	for key in params:
		if key not in ['inputPLINK', 'phenoFile', 'outDir', 'projectName', 'config']:
			pdf.multi_cell(0, 8, str(key)+':     '+str(params[key]), 0, 1, 'L')

	return pdf
Esempio n. 45
0
def dotest(outputname, nostamp):
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.add_page()
    pdf.set_font('Arial', '', 14)
    pdf.ln(10)
    if nostamp:
        data = "TEST-TEST-TEST"
    else:
        data = sys.version

    #áéíóúüñ
    # This string converted with errors in py2.x
    pdf.write(5, ('hello world %s áéíóúüñ' % data))

    pdf.output(outputname, 'F')
Esempio n. 46
0
def createPDF(user_id):
    data_values = []
    data_names = []

    pdf = FPDF(orientation='P', format='A4')
    pdf.set_font("Arial", size=20)
    pdf.add_page()
    col_width = pdf.w / 4.5
    row_height = pdf.font_size
    pdf.cell(col_width, row_height, txt='Financial report(outcome)')
    pdf.ln(2 * row_height)
    pdf.set_font("Arial", size=15)

    if statpdf1(user_id):
        pdf.cell(col_width, row_height, txt='Average by every item')
        pdf.ln(2 * row_height)
        pdf.set_font("Arial", size=8)
        res = statpdf1(user_id)
        for i in res:
            name, val = i
            val = round(float(val), 1)
            pdf.cell(50, row_height, txt=name)
            pdf.cell(20, row_height, txt=str(val))
            pdf.ln(row_height)

    pdf.ln(2 * row_height)

    if statpdf2(user_id):
        pdf.set_font("Arial", size=15)
        pdf.cell(col_width, row_height, txt='Ratio by every item')
        pdf.ln(2 * row_height)
        pdf.set_font("Arial", size=8)
        res = statpdf2(user_id)
        print(res)
        for i in res:
            name, val = i
            val = round(float(val), 3)
            pdf.cell(50, row_height, txt=name)
            pdf.cell(20, row_height, txt=str(val))
            pdf.ln(row_height)
            data_values.append(val)
            data_names.append(name)

    mpl.rcParams.update({'font.size': 9})
    dpi = 80
    fig = plt.figure(dpi=dpi, figsize=(512 / dpi, 384 / dpi))
    plt.title('')
    plt.pie(data_values,
            autopct='%.1f',
            radius=1.1,
            explode=[0.15] + [0 for _ in range(len(data_names) - 1)])

    plt.legend(bbox_to_anchor=(-0.16, 0.45, 0.25, 0.25),
               loc='lower left',
               labels=data_names)

    fig.savefig('pie.png')
    pdf.image('pie.png')
    pdf.output('report{}.pdf'.format(user_id))
Esempio n. 47
0
def status_chart(request):
    """
    Show the staus chart.

    :param request:
    :return:
    """
    image_base64 = ''
    if request.method == 'POST':
        machines = request.POST['machines']
        start_timestamp = request.POST['start_timestamp']
        end_timestamp = request.POST['end_timestamp']
        email = request.POST['email']
        mail_send = request.POST['mail_send']
        if machines == '' or start_timestamp == '' or end_timestamp == '':
            messages.error(request, 'Input Chat Machine List and Period')
        else:
            print(machines)
            machine_list = machines.split(',')

            for i in range(len(machine_list)):
                label = ''
                query = "select ml.name, ms.* from machines_list as ml, machines_state as ms " + \
                        "where ml.id in(%s) and ml.id = ms.machine_id " % machine_list[i] + \
                        "and ml.created_at > '%s' and ml.created_at < '%s'" % (start_timestamp, end_timestamp)
                print(start_timestamp)
                print(end_timestamp)
                print(query)
                data = query_to_dicts(query)
                x_data = []
                y_data = []
                for item in data:
                    x_data.append(item['created_at'])
                    y_data.append(item['status'])
                    label = item['name']

                if label == '':
                    machine = Machines.objects.get(id=machine_list[i])
                    label = machine.name

                plt.plot(x_data, y_data, marker='o', markerfacecolor=[round(random.uniform(0, 1), 1), round(random.uniform(0, 1), 1), round(random.uniform(0, 1), 1)],
                         markersize=12, color=[round(random.uniform(0, 1), 1), round(random.uniform(0, 1), 1), round(random.uniform(0, 1), 1)],
                         linewidth=4, label=label)
                grid(True)
            #plt.xlim(start_timestamp, end_timestamp)
            plt.legend()
            #plt.show()
            buf = BytesIO()
            plt.savefig(buf, format='png', dpi=300)
            plt.savefig(os.path.join(os.getcwd(), 'pdfs', 'chart.png'), dpi=300)
            image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8').replace('\n', '')
            buf.close()
            plt.clf()
            pdf = FPDF()
            pdf.add_page()
            pdf.set_font("Arial", size=12)
            pdf.cell(200, 10, txt="Machine Static", ln=1, align="C")
            pdf.cell(200, 10, txt="Start Time:"+start_timestamp, ln=1, align="L")
            pdf.cell(200, 10, txt="End Time:"+end_timestamp, ln=1, align="L")

            pdf.image(os.path.join(os.getcwd(), 'pdfs', 'chart.png'), x=60, y=60, w=100)
            pdf.set_font("Arial", size=12)
            pdf.ln(85)  # move 85 down
            pdf.cell(200, 8, txt="{}".format('Status Chart'), ln=3, align='C')
            pdf.output(os.path.join(os.getcwd(), 'pdfs', "simple_demo.pdf"))
            # if mail_send != '':
            #     print(email)
            #     regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
            #     print(re.search(regex, email))
            #     if email != '' and re.search(regex, email):
            #         to = [email]
            #         subject = settings.EMAIL_TPLS['mat_graph'][0]
            #         email_body = settings.EMAIL_TPLS['mat_graph'][1] % ('test')
            #             #"<img src='data:image/png;base64,"+image_base64+"' alt='some text to display to your users when the image does not show correctly' width=500 height=auto />")
            #
            #         DataHelper.send_email(to, subject, email_body)
            #     else:
            #         messages.error(request, 'Input Email.')


    machines = Machines.objects.all()

    return render(request, "status_chart.html", {
        "machines": machines,
        "image_base64": image_base64
    })
def pruning(dictLD):
	pdf = FPDF() # create new PDF
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "LD Pruning", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)
	pdf.set_font('Arial', '', 12)
	pdf.multi_cell(0, 5, 'Pruning SNPs based upon linkage equilibrium is senstive to race/ethnicity.  Therefore, LD-pruning is performed \
		independently on each ethnic group in the data set.', 0, 1, 'J')
	pdf.multi_cell(0, 5, '\n', 0, 1, 'J')
	pdf.set_font('Arial', 'B', 16)
	pdf.set_fill_color(200)
	
	# iterate through all ethnic groups for LD pruning stats
	for key, value in dictLD.iteritems():
		pdf.multi_cell(0, 8, str(key), 1, 'L', True)
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs analyzed:  ' +  str(value[0]), 1, 1, 'L')
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs Passing:  ' +  str(value[1]) + ' (' + str("%.2f" % round((float(value[1])/float(value[0]))*100, 2)) + '%)', 1, 1, 'L')
		pdf.multi_cell(0, 8, '\n\n', 0, 1, 'J')


	return pdf
 def write_into_pdf(self, input):
     for code in input:
         print("Gift Code: ", code)
         pdf = FPDF()
         pdf.add_page()
         pdf.add_font('Raleway', '', r'./font/Raleway-SemiBold.ttf', uni=True)
         pdf.set_font(family='Raleway', size=12)
         pdf.text(85.0, 289.2, code)
         pdf.output('./gift-codes/a5-horizontal/gift-code-{}.pdf'.format(code))
Esempio n. 50
0
def merge(images_paths, out_file):
    images_paths.sort(key=lambda file: int(
                re.search(r"\d+", os.path.splitext(os.path.split(file)[1])[0])[0]
            ))

    pdf = FPDF(orientation="P", unit="pt", format="A4")
    chunk_bookmarks = {}
    i = 0
    for imagef in images_paths:
        i += 1
        if imagef in chunk_bookmarks.keys():
            chunk_bookmarks[imagef] += 1
        else:
            chunk_bookmarks[imagef] = 1

        try:
            with Image.open(imagef) as image:
                if image.width > image.height:
                    pdf.add_page("vertical")
                    pdf.image(imagef, x=0, y=00, w=842, h=596)
                else:
                    tilled = tile(imagef)
                    for image in tilled:
                        pdf.add_page()
                        if stretch or len(tilled) == 1:
                            pdf.image(image, x=0, y=00, h=842, w=596)
                        else:
                            pdf.image(image, x=0, y=00, w=596)  # h=842,
        except OSError as e:
            pdf.add_page()

        yield i / len(images_paths)

    yield 0.9
    pdf.output(out_file, "F")
Esempio n. 51
0
def generate_pdf(token_number_container):
    global pdf

    pdf = FPDF()
    pdf.add_page()

    for items in token_number_container:
        pdf.set_font("Arial", size=15)

        pdf.cell(200, 10, txt="PRABHAT ENTERPRISES", ln=1, align='C')

        pdf.set_font("Arial", size=40)
        pdf.cell(200, 10, txt=f"{items}", ln=1, align='C')

        pdf.set_font("Arial", size=12)
        # add another cell
        pdf.cell(200,
                 10,
                 txt="CSC AADHAR CENTRE PRABHAT ENTERPRISES",
                 ln=1,
                 align='C')

        pdf.set_font("Arial", size=10)
        pdf.cell(
            200,
            10,
            txt="BARDAD CHAURAHAH NAUSAD GORAKHPUR 273401, Mob- 9956509913",
            ln=1,
            align='C')

        pdf.set_font("Arial", size=10)
        pdf.cell(
            200,
            10,
            txt=
            "--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"
            ""
            ""
            "",
            ln=1,
            align='C')

        pdf.set_font("Arial", size=10)
        pdf.cell(
            200,
            10,
            txt=
            "                                                                                ",
            ln=1,
            align='C')

    publish_pdf(pdf, token_number_container)
    token_number_container.clear()
Esempio n. 52
0
from fpdf import FPDF
pdf = FPDF('P', 'mm', 'A4')
pdf.add_page()
pdf.set_font('Arial', '', 16)
pdf.cell(0, 15, 'Vermelho', 0, 1)
pdf.cell(0, 15, 'Verde', 0, 1)
pdf.cell(0, 15, 'Marrom', 0, 1)
pdf.cell(0, 15, 'Laranja', 0, 1)
pdf.output('cores.pdf', 'F')
#
#
#
pdf2 = FPDF('P', 'mm', 'A4')
pdf2.add_page()
pdf2.set_font('Times', 'B', 20)
pdf2.set_text_color(255, 0, 0)
pdf2.cell(0, 15, 'Vermelho', 0, 1)
pdf2.set_font('Arial', 'I', 14)
pdf2.set_text_color(0, 255, 0)
pdf2.cell(0, 15, 'Verde', 0, 1)
pdf2.set_font('Arial', 'U', 12)
pdf2.set_text_color(102, 51, 0)
pdf2.cell(0, 15, 'Marrom', 0, 1)
pdf2.set_font('Times', '', 25)
pdf2.set_text_color(255, 102, 0)
pdf2.cell(0, 15, 'Laranja', 0, 1)
pdf2.output('cores_1.pdf', 'F')
#
#
#
pdf3 = FPDF('P', 'pt', 'Letter')
 def write_into_pdf(self, input):
     for code in input:
         print("Gift Code: ", code)
         pdf = FPDF()
         pdf.add_page()
         pdf.add_font('Raleway', '', r'./font/Raleway-SemiBold.ttf', uni=True)
         pdf.set_font(family='Raleway', size=9)
         pdf.text(38.6, 273.4, code)
         pdf.output('./gift-codes/a6-portrait/gift-code-{}.pdf'.format(code))
Esempio n. 54
0
def create_pdf(name,
               orientation,
               gender,
               speed,
               fig1_dest,
               fig2_dest,
               fig3_dest,
               destination=temp_destination):

    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    pdf.set_text_color(r=0, g=40, b=70)
    pdf.ln()
    pdf.ln()

    title = "Dolphin Kick Analysis for {name}".format(name=name)
    pdf.cell(0, 8, title, 0, 1, 'C')

    pdf.set_font('Arial', '', 10)
    pdf.set_text_color(r=60, g=60, b=60)
    gender_text = "Gender: {gender}".format(gender=gender)
    orientation_text = "Orientation: {orientation}".format(
        orientation=orientation)
    speed_text = "Speed: {speed}".format(speed=speed)
    subtitle = gender_text + "       " + orientation_text + "      " + speed_text
    pdf.cell(0, 8, subtitle, 0, 1, 'C')
    pdf.ln()

    pdf.set_font('Arial', '', 11)
    pdf.set_text_color(r=50, g=50, b=50)
    graph1_title = 'Vertical Variation Over Time'
    graph3_title = 'Time Decomposition'
    pdf.cell(90, 8, graph1_title, 0, 0, 'C')
    pdf.cell(120, 8, graph3_title, 0, 1, 'C')

    pdf.image(fig1_dest, x=7, y=42, h=70)
    pdf.image(fig3_dest, x=102, y=42, h=66)

    pdf.set_xy(x=24, y=110)
    pdf.set_font('Arial', '', 9)
    pdf.set_text_color(r=0, g=0, b=0)
    graph3_explanation = 'Time interval between key points of kick. See below for \ndefinitions of key points'
    graph1_explanation = 'All displacement values calculated relative to hip'
    pdf.cell(50, 8, graph1_explanation, 0, 0, 'C')
    pdf.set_xy(x=115, y=110)
    pdf.multi_cell(0, 4, graph3_explanation, 0, 1, 'R')

    graph2_title = 'Statistical Analysis of Vertical Displacement'
    graph2_subtitle = 'Figure shows comparison of vertical displacement of key joints on swimmers body with average vertical displacement of key joints from professional swimmers during four distinct time points within the kick. All statistically significant differences are marked red.'
    pdf.set_xy(x=10, y=123)
    pdf.set_font('Arial', '', 13)
    pdf.set_text_color(r=50, g=50, b=50)
    pdf.cell(0, 8, graph2_title, 0, 1, 'C')
    pdf.set_font('Arial', '', 9)
    pdf.set_text_color(r=0, g=0, b=0)

    pdf.image(fig2_dest, x=15, y=130, w=190)
    pdf.set_xy(x=20, y=255)
    pdf.multi_cell(0, 5, graph2_subtitle, 0, 1, 'C')

    file_name = name + "_dolphinkickanalyis" '.pdf'
    save_path = os.path.join(destination, file_name)

    pdf.output(save_path, 'F')

    return pdf
def hwe(dictHWE, thresh, outDir):
	pdf = FPDF() # create new PDF
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "Hardy-Weinberg Equilibrium", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)
	pdf.set_x(20)
	pdf.set_font('Arial', '', 12)
	pdf.multi_cell(0, 5, 'Hardy-Weinberg equilibrium is only used to remove SNPs with extreme p-values are that are likely \
		to occur due to sequencing, genotyping, or study-design errors.  This calculation is sensitive to different ethinic groups \
		and races.  Therefore, it is independently calculated for each ethnic group.  The current p-value threshold that was used to determine \
		whether a SNP was removed was  ' + str(thresh) + '.  This calculation will only consider founders; nonfounders are ignored.' , 0, 1, 'J')
	pdf.multi_cell(0, 5, '\n', 0, 1, 'J')
	pdf.set_font('Arial', 'B', 16)
	pdf.set_fill_color(200)
	
	# iterate through all ethnic groups for HWE stats
	for key, value in dictHWE.iteritems():
		pdf.multi_cell(0, 8, str(key), 1, 'L', True)
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs analyzed:  ' +  str(value[0]), 1, 1, 'L')
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs Passing:  ' +  str(value[1]) + ' (' + str("%.2f" % round((float(value[1])/float(value[0]))*100, 2)) + '%)', 1, 1, 'L')
		pdf.multi_cell(0, 8, '\n\n', 0, 1, 'J')

	
	# NOTE hweFile is before filtering by HWE threshold and prior to removal of SNPs failing threshold
	# these plot the observed vs expected from pre-filter HWE and the associated p-values
	# red fail threhold
	for key, value in dictHWE.iteritems():
		hweFile_dataframe = pd.read_table(value[2], delim_whitespace=True)	
		figure = plt.figure(1)
		num_phenos = len(list(set(list(hweFile_dataframe['TEST'])))) # for use in automating number of subplots to include in figure
		for phenotypes in list(set(list(hweFile_dataframe['TEST']))):
			pheno_subset = hweFile_dataframe.loc[hweFile_dataframe['TEST'] == phenotypes]
			colors = np.where(pheno_subset.P < thresh, 'r', 'k')
			plt.subplot(220 + num_phenos)
			plt.scatter(pheno_subset['E(HET)'], pheno_subset['O(HET)'], c=colors, s=8)
			plt.xlabel('expected(het)', fontsize=8)
			plt.ylabel('observed(het)', fontsize=8)
			plt.title(phenotypes + ':  observed(het) vs expected(het) of HWE', fontsize=8)
			num_phenos = num_phenos - 1
		plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
		plt.savefig(outDir+'/'+'hwe_'+str(key)+'.png')
		plt.close()
		pdf.add_page()
		pdf.set_margins(20, 10, 20)
		pdf.set_font('Arial', 'B', 14)
		pdf.set_x(20)
		pdf.multi_cell(0, 10, "HWE Plots for "+str(key) +" population", 0, 1, 'L')
		pdf.line(20, 32, 190, 32)
		pdf.set_x(20)
		pdf.image(outDir+'/'+'hwe_'+str(key)+'.png', x=10, y=50, w=190, h=150)
			
	
	return pdf
Esempio n. 56
0
def printContract(studentLists, projectLists):
    # from fpdf import FPDF
    pdf = FPDF(format='letter', unit='in')
    pdf.add_page()
    pdf.set_font('Times', '', 10.0)
    effectivePageWidth = pdf.w - 2 * pdf.l_margin

    # contract text
    pdf.multi_cell(effectivePageWidth, 0.15,
                   f'Dear {projectLists.client_FirstName},')
    pdf.multi_cell(
        effectivePageWidth, 0.15,
        'These students digitally signed the IP+NDA agreement "UC Merced Innovate to Grow Program - Student Registration and Agreement" with UC Merced ID credentials:'
    )
    pdf.multi_cell(effectivePageWidth, 0.15, '\n')

    # student information table
    studentTableTitle = ['Timestamp', 'First Name', 'Last Name', 'Email']
    th = pdf.font_size
    columnWidth = effectivePageWidth / 4

    for row in studentTableTitle:
        # enters data in columns
        pdf.set_font('Times', 'B', 10.0)
        pdf.cell(columnWidth, th, str(row), border=2)
    pdf.ln(th)
    for eachStudent in studentLists:
        pdf.set_font('Times', '', 10.0)
        finalList = [
            eachStudent.student_Timestamp, eachStudent.student_FirstName,
            eachStudent.student_LastName, eachStudent.student_Email
        ]
        for datum in finalList:
            pdf.cell(columnWidth, th, str(datum), border=2)
        pdf.ln(th)

    # new line
    pdf.multi_cell(effectivePageWidth, 0.15, '\n')

    # project information table
    projectTable = [
        ['Project ID:', projectLists.project_ID],
        [
            'Project Title:',
            projectLists.project_Title,
        ], ['Team #:', projectLists.project_TeamNumber],
        ['Organization:', projectLists.client_OrganizationName],
        ['Primary Contact First Name:', projectLists.client_FirstName],
        ['Primary Contact Last Name:', projectLists.client_LastName],
        ['Primary Conract Email:', projectLists.client_Email]
    ]

    for projectData in projectTable:
        for projectInfo in projectData:
            pdf.cell(columnWidth, th, str(projectInfo), border=2)
        pdf.ln(th)

    # contract text cont.
    pdf.multi_cell(effectivePageWidth, 0.15, '\n')
    pdf.multi_cell(
        effectivePageWidth, 0.15,
        '''We have a digital record and timestamp of their agreement: the table above includes their credentials and time of acceptance. For your reference this is the language of the agreement that the students digitally signed.
Thank you for your participation in the Innovate to Grow program. Please let us know if you have any questions, or special circumstances to address.
Stefano Foresti
+1-801-971-3680
[email protected]
University of California Merced, Director of Innovation -> engineering.ucmerced.edu '''
    )
    pdf.ln(0.5)
    pdf.output(
        'data/output/contracts/2019-July-Fall-CAP-StudentAgreement-Team' +
        projectLists.project_TeamNumber + '-' +
        projectLists.client_OrganizationName + '-' + projectLists.project_ID +
        '.pdf', 'F')
Esempio n. 57
0
def output(player, q_list, a_list, c_list):
    pdf = FPDF()
    pdf.add_page()

    pdf.add_font('Roboto', '', 'font/Roboto-Regular.ttf', uni=True)
    pdf.set_font('Roboto', '', 20)

    pdf.cell(200, 10, f'Hráč {player}', 0, 1, 'C')

    pdf.set_font('Roboto', '', 10)
    
    for idx, line in enumerate(q_list):
        # Otázka
        pdf.set_text_color(0, 0, 0)
        pdf.cell(40, 10, q_list[idx], 0, 1)

        # Odpověď
        try:
            if c_list[idx] == 1:
                pdf.set_text_color(0, 255, 0)
            else:
                pdf.set_text_color(255, 0, 0)
            pdf.cell(180, 10, a_list[idx], 0, 1, 'R')
        except IndexError:
            raise Exception("Program byl příliš brzo ukončen!")

        if idx == 11:
            pdf.cell(40, 10, '', 0, 1)

    pdf.output(f'hrac{player}.pdf', 'F')
Esempio n. 58
0
# Python program to create a pdf file 
from fpdf import FPDF 

# save FPDF() class into a 
# variable pdf 
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 = 60) 

# create a cell 
pdf.cell(200, 10, txt = "Neema Nama", 
		ln = 1, align = 'C') 

pdf.set_font("Arial", size = 25) 
# add another cell 
pdf.cell(200, 10, txt = "She is Sitting.", 
		ln = 2, align = 'C') 

# save the pdf with name .pdf 
pdf.output("GFG.pdf") 
Esempio n. 59
0
def generate_report(player_dict):

    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', '', 15)
    avatar_fname = player_dict.get('avatar', None)
    if avatar_fname:
        pdf.image(name=str(IMG_PATH / avatar_fname), w=70, h=70)

    for k in ('username', 'gender', 'email', 'total_sessions',
              'total_victories', 'total_defeats', 'total_time'):
        pdf.cell(70, 10, f'{k}: {player_dict[k]}', ln=1)
    path = str(PDF_PATH / f"{player_dict['id']}.pdf")
    pdf.output(path).encode('latin-1')
    return path
Esempio n. 60
0
    def generate_invoice(self, cart):
        pdf = FPDF(orientation="P", unit="pt", format="A4")
        pdf.add_page()

        pdf.set_font(family='Arial', size=24, style='B')
        pdf.cell(w=0, h=80, txt=cart.user.name, border=1, align="C", ln=1)
        pdf.cell(w=100, h=40, txt="Period:", border=1)
        # pdf.cell(w=150, h=40, txt=bill.period, border=1, ln=1)
        # pdf.cell(w=0, h=30, txt="", border=0, ln=1)
        # pdf.cell(w=150, h=40, txt=flatmate1.name, border=0)
        # pdf.cell(w=50, h=40, txt=str(flatmate1.pays(bill, flatmate2)), border=0, ln=1)
        # pdf.cell(w=150, h=40, txt=flatmate2.name, border=0)
        # pdf.cell(w=50, h=40, txt=str(flatmate2.pays(bill, flatmate1)), border=0, ln=1)

        pdf.output(self.filename)
        return True