Exemplo n.º 1
4
def dotest(outputname, nostamp):
    try:
        from bidi.algorithm import get_display
    except ImportError:
        from unittest import SkipTest
        raise SkipTest("Need python-bidi")
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)

    pdf.compress = False
    pdf.add_page()
    pdf.add_font('DejaVu', '', \
        os.path.join(common.basepath, 'font/DejaVuSans.ttf'), uni=True)
    pdf.set_font('DejaVu', '', 14)
    # this will be displayed wrong as actually it is stored LTR:
    text= u"این یک متن پارسی است. This is a Persian text !!"
    pdf.write(8, text)
    pdf.ln(8)
    # Reverse the RLT using the Bidirectional Algorithm to be displayed correctly:
    # (http://unicode.org/reports/tr9/)
    rtl_text = get_display(text)
    pdf.write(8, rtl_text)

    pdf.output(outputname, 'F')
Exemplo n.º 2
1
def pdf_convert(fname, data):
    pdf = FPDF()
    pdf.set_margins(left=10, top=15, right=10)
    pdf.add_page()
    pdf.add_font('calibri', fname=r'c:\Windows\Fonts\calibri.ttf', uni=True)
    pdf.image('gables.jpg', x=90, w=30)
    pdf.set_font("calibri", size=12)
    pdf.multi_cell(0, 5, txt=data)
    pdf.output(fname)
Exemplo n.º 3
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')
Exemplo n.º 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))
Exemplo n.º 5
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)
Exemplo n.º 6
0
def generate(pdfname):
    datamanager = DataManager('127.0.0.1', 27017) 

    pdf = FPDF()

    pdf.add_page()
    pdf.set_author('GRE Master')
    pdf.set_title('GRE Word')
    #pdf.set_font('Arial', 'B', 16)

    pdf.add_font('eunjin', '', 'Eunjin.ttf', uni=True)
    pdf.set_font('eunjin', '', 16)

    pdf.add_font('bangwool', '', 'Bangwool.ttf', uni=True)
    pdf.set_font('bangwool', '', 16)

    #pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
    #pdf.set_font('DejaVu', '', 16)

    for row in datamanager.find():
        text = row['text']
        meanings = row['meaning']
        synonyms = row['synonyms']

        meaning = ','.join(meanings)
        synonym = u','.join(synonyms)

        line = '%s : %s \n synonyms : %s' % (text, meaning, synonym)

        #pdf.cell(20, 10, row['text'], 0, 0)# + '  ' + ','.join(row['meaning']))
        pdf.multi_cell(0, 8, line, 1, 'J')
    pdf.output(pdfname, 'F')
Exemplo n.º 7
0
 def label_with_big_barcode(self, serial):
     pdf = FPDF(format=(60,30))
     pdf.add_page()
     self.create_barcode(serial)
     pdf.image('barcode.png', 1, 1, w=58)
     pdf.output('label_big_barcode.pdf')
     self.print_barcode('label_big_barcode.pdf')
Exemplo n.º 8
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()
Exemplo n.º 9
0
def write_cover_letter(cover_letter, skills):

    # open csv file and read input
    with open(skills) as skills_csv:

        reader = csv.reader(skills_csv)
        rownum = 0

        for row in reader:

            pdf = FPDF('P', 'mm', 'A4')  # portrait mode, mm , A4 size paper
            pdf.add_page()  # new blank page
            pdf.set_font('Arial', '', 12)  # font, Style (B,U,I) , fontsize in pt.

            #ignore the header row
            if rownum == 0:
                pass

            else:
                model_cover_letter = open(cover_letter, 'r')

                for line in model_cover_letter:

                    line = line.replace('#website', row[0])
                    line = line.replace('#inserttools', ','.join(row[1].split('#')))  # skills are seperated by '#' split and join them
                    line = line.replace('#toolproficient', row[2])
                    line = line.replace('#toolyr', row[3])
                    line = line.replace('#company', row[4])

                    pdf.write(6, line)

                pdf.output('cover_letters/Cover Letter - ' + row[4] + '.pdf', 'F')
                pdf.close()

            rownum = rownum + 1
Exemplo n.º 10
0
def render_images_to_pdf(image_list):
    pdf = FPDF(orientation='P', unit='mm', format='A4')
    pdf.add_page(format='A4')
    pdf.image('/Users/kangtian/Documents/Master/tinydoc/page.jpg', 0, 0, 210)
    pdf.output('/Users/kangtian/Documents/Master/tinydoc/page.pdf')
    for img in image_list:
        pass
Exemplo n.º 11
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
Exemplo n.º 12
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')
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()
Exemplo n.º 14
0
	def createPdfFile(self,imageList,folderName):
		pdf = FPDF()
		# imagelist is the list with all image filenames
		for image in imageList:
			pdf.add_page()
			pdf.image(image,0,0,210)
		pdf.output(folderName+".pdf", 'F')
Exemplo n.º 15
0
def issue_student_admission_letter(Student, body):
    """
    Print letter for Student at time of admission
    Contains details as provided by the Student
    """

    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page('P')
    pdf.set_font('Times', 'B', 14)

    pdf.multi_cell(0, 5, 'Student Admission Letter')
    pdf.ln()
    pdf.multi_cell(0, 5, ('Name: %s' % Student.name))
    pdf.ln()
    pdf.multi_cell(0, 5, ('Address: %s' % Student.address))
    pdf.ln()
    pdf.multi_cell(0, 5, ('Contact Number: %s' % Student.contact_number))
    pdf.ln()
    pdf.multi_cell(0, 5, ('Hall Allotted: %s' % str(db.get("hall", Student.hall_ID, "name")[0])))
    pdf.ln()
    pdf.multi_cell(0, 5, ('Room Allotted: %s' % Student.room_no))
    pdf.ln()
    pdf.ln()
    pdf.multi_cell(0, 5, ('%s' % body))
    pdf.ln()

    # Write generated output file to PDF
    pdf.output(('admission_letter_%s.pdf' % Student.student_ID), 'F')
Exemplo n.º 16
0
def print_receipt(Student):
    """
    Print receipts related to specified Student
    Contain all three amounts paid - mess fees, room rent, amenities charge
    """

    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page('P')
    pdf.set_font('Times', 'B', 14)

    pdf.multi_cell(0, 5, 'Student Dues Payment Receipt')
    pdf.ln()
    pdf.multi_cell(0, 5, ('Student ID: %s' % Student.student_ID))
    pdf.ln()
    pdf.multi_cell(0, 5, ('Name: %s' % Student.name))
    pdf.ln()
    pdf.multi_cell(0, 5, ('Mess Fees: %s' % Student.mess_charge))
    pdf.ln()

    if Student.room_type == "S":
        room_rent = db.get("hall", Student.hall_ID, "single_room_rent")[0]
    elif Student.room_type == "D":
        room_rent = db.get("hall", Student.hall_ID, "double_room_rent")[0]

    pdf.multi_cell(0, 5, ('Room Rent: %s' % room_rent))
    pdf.ln()

    pdf.multi_cell(0, 5, ('Amenities Charge: %s' % str(db.get("hall", Student.hall_ID, "amenities_charge")[0])))
    pdf.ln()

    pdf.multi_cell(0, 5, ('Total Amount Paid: %s' % str(Student.total_dues)))
    pdf.ln()

    # Write generated output file to PDF
    pdf.output(('receipt_%s.pdf' % Student.hall_ID), 'F')
Exemplo n.º 17
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'))
Exemplo n.º 18
0
def print_results(top_hosts,hosts):
    pdf=FPDF()
    pdf.add_page()
    pdf.set_font('Arial','B',24)
    pdf.cell(60,10,'PCAP Analysis results','C')
    pdf.ln(20)
    for i in range(1,len(top_hosts)):
        pdf.set_font('Arial','B',16)
        pdf.ln(10)
        pdf.cell(70,20,"top%d"%i)
        pdf.ln(10)
        pdf.set_font('Arial','B',12)
        pdf.cell(70,20,"host:"+str(top_hosts[i-1][0]))
        pdf.ln(10)
        pdf.cell(70,20,"num:"+str(hosts[top_hosts[i-1][0]]['num']))
        pdf.ln(10)
        pdf.cell(70,20,"start static time:"+str(hosts[top_hosts[i-1][0]]['start_time']))
        pdf.ln(10)
        pdf.cell(70,20,"end static time:"+str(hosts[top_hosts[i-1][0]]['start_time']))
        pdf.ln(10)
        pdf.cell(70,20,"flow:"+str(float(hosts[top_hosts[i-1][0]]['flow'])/1024)+"kb")
        pdf.ln(10)
        pdf.cell(70,20,"visitors:")
        pdf.set_font('Arial','B',10)
        for visitor in hosts[top_hosts[i-1][0]]['visitors']:
            pdf.ln(7)
            pdf.cell(200,20,"     time: "+time.strftime('%Y-%m-%d',time.localtime(float(visitor[0])))+"     srcip: "+str(visitor[1])+"     country: "+str(visitor[2])+"     dstip: "+str(visitor[3])+"     country:"+str(visitor[4]))
    pdf.output('result.pdf','F')
def gerarPDF(qtd_img, Tamanho, qtd_Arq, diretorio):

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


	pdf.set_font(u'Arial', size=18)
	pdf.set_line_width(0.1)
	#   evita quebra automatica da pagina, ao chegar perto da borda inferior
	pdf.set_auto_page_break(False)

	pdf.set_margins(8, 8)
	pdf.add_page()

	pdf.text(60, 50, txt=u'Relatório de Contagem de Imagens')
	pdf.ln("")
	pdf.set_font_size(size=10)
	pdf.text(10, 60, txt=u'Total de Imagens = %s' %qtd_img)
	pdf.text(80, 60, txt=u'Espaço Ocupado = %s' %Tamanho)
	pdf.text(150, 60, txt=u'Total de Arquivos = %s' %qtd_Arq)

	pdf.text(10, 70, txt=u'Data = %s às %s' %(datetime.datetime.now().date().__format__(u'%d/%m/%Y'), datetime.datetime.now().time().__format__(u'%H:%M:%S')))
	pdf.ln("")
	pdf.text(10, 80, txt=u'Diretório Raiz= %s' %diretorio)

	pdf.output(u'./relatório.pdf', u'F')

# gerarPDF(0,0,0,0)
Exemplo n.º 20
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)
Exemplo n.º 21
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')
Exemplo n.º 22
0
	def generate_pdf(self,qrs,pdf_filename):
		self.progress.setValue(0)
		self.label.setText('Writing PDF...')
		pdf=FPDF()
		pdf.add_page()
		col = 10
		row = 20
		pdf.set_font('Arial','B',20)
		pdf.text(10, 10, 'QRS')
		pdf.set_font('Arial','',5)
		c = 1
		for qr in qrs:
			if col > 250:
				row = row + 40
				col = 10
			pdf.text(col+3,row-3,qr)
			pdf.image('qrs/'+qr+'.png',col,row,30)
			col = col + 40
			self.progress.setValue((c*100)/len(qrs))
			c = c + 1
		try: 
			if not os.path.exists('pdfs'):
				os.makedirs('pdfs')
			pdf.output('pdfs/'+pdf_filename+'.pdf','F')
			self.messageBox('PDF', 'Pdf is Done! ' + 'pdfs/'+pdf_filename+'.pdf')
			self.label.setText('')

			path = os.getcwd()
			os.startfile(path.replace('\\','/')+'/pdfs/'+pdf_filename+'.pdf')

		except Exception as e:
			self.messageBox('PDF.', str(e))
Exemplo 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')
Exemplo n.º 24
0
def generate_salary_list(Hall):
    """
    Print list of all employees and respective salary details for specified hall
    Take dict of Worker objects as parameter
    """

    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page('P')
    pdf.set_font('Times', 'B', 14)

    pdf.multi_cell(0, 5, ('Hall Salary List: Hall %s' % Hall.hall_ID))
    pdf.ln()

    worker_list = dbr.rebuild("worker")
    title = "Role"
    wage = 0
    for key in worker_list:
        if worker_list[key].hall_ID == Hall.hall_ID:
            if isinstance(worker_list[key], mess_manager.MessManager):
                title = "Mess Manager"
                wage = worker_list[key].monthly_salary
            elif isinstance(worker_list[key], clerk.Clerk):
                title = "Clerk"
                wage = worker_list[key].monthly_salary
            elif isinstance(worker_list[key], attendant.Attendant):
                title = "Attendant"
                wage = worker_list[key].daily_wage

            pdf.multi_cell(0, 5, ('%s: %s (%s) - Rs. %s' % (worker_list[key].worker_ID,
                                  worker_list[key].name, title, wage)))
            pdf.ln()

    # Write generated output file to PDF
    pdf.output(('hall_salary_%s.pdf' % Hall.hall_ID), 'F')
Exemplo n.º 25
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')
Exemplo n.º 26
0
 def test_pdf_write(self):
     pdf=FPDF()
     pdf.add_page()
     pdf.set_font('Arial','',12)
     pdf.write(30, 'small text')
     pdf.set_font('Arial','',24)
     pdf.write(30, 'Large text')
     pdf.output('out/fpdf/test_pdf_write.pdf', 'F')
Exemplo n.º 27
0
    def render(self, outfile):
        pdf = FPDF()
        pdf.add_page();
        pdf.set_font('Arial','B',16);

        for field in self.fields.values():
            self.handlers[field['type'].upper()](pdf, **field)

        pdf.output(outfile,"F")
Exemplo n.º 28
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)
Exemplo n.º 29
0
 def test_ttf(self):
     pdf=FPDF()
     pdf.add_font('test','','font/lmroman7-italic.ttf',uni=True)
     pdf.add_page()
     pdf.set_font('test', '', 14)
     pdf.write(10, 'hello')
     pdf.set_font('test', '', 24)
     pdf.write(10, 'hello')
     pdf.output('out/fpdf/test_ttf.pdf', 'F')
Exemplo n.º 30
0
def pdfGen(Input,fontName,Output):
    pdf = FPDF()
    pdf.add_page()
    ttfName=fontName+'.ttf'
    pdf.add_font(fontName, '', ttfName, uni=True) 
    pdf.set_font(fontName, '', 14)
    linestring = open(Input, 'r').read()
    pdf.write(8,linestring)
    pdf.ln(20)
    pdf.output(Output, 'F')
Exemplo n.º 31
0
import pandas as pd

# Out report
summary_csv = open('data/auto_summary.csv', 'a')


def print_and_write(txt):
    print(txt)
    summary_csv.write(txt)
    summary_csv.write('\n')


filename = '79_1892.pdf'
# --- Create lines
linePDF = FPDF()
linePDF.add_page(orientation='P', format='A4')
linePDF.set_fill_color(0, 0, 0)
linePDF.rect(18.5, 122, 0.25, 91, 'F')
linePDF.set_fill_color(0, 0, 0)
linePDF.rect(56, 122, 0.25, 91, 'F')
linePDF.set_fill_color(0, 0, 0)
linePDF.rect(69.5, 122, 0.25, 91, 'F')
linePDF.set_fill_color(0, 0, 0)
linePDF.rect(90, 122, 0.25, 79, 'F')
linePDF.set_fill_color(0, 0, 0)
linePDF.rect(103.5, 122, 0.25, 79, 'F')

linePDF.set_fill_color(0, 0, 0)
linePDF.rect(18.5, 206, 51, 0.25, 'F')
linePDF.set_fill_color(0, 0, 0)
linePDF.rect(18.5, 212, 51, 0.25, 'F')
Exemplo n.º 32
0
def png_to_pdf(png):
    pdf = FPDF()
    pdf.add_page()
    pdf.image(png, 0, 0, 210, 300)
    pdf.output(png.replace('.png', '_temp_darkmode.pdf'), "F")
    pdf.close()
Exemplo n.º 33
0
def prescription_generator(output_path,
                           first_name=None,
                           last_name=None,
                           locale="fr_FR",
                           pseudonymize=False,
                           **kwargs):
    """Generates a fake medical prescription
    Arguments:
        output_path {Path} -- path the ouput pdf file
        patient_name {str} -- patient name to use
        year {int} -- year of the prescription
    """
    directory = os.path.dirname(output_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

    fake = Factory.create(locale)
    pdf = FPDF(format="A4")
    pdf.add_page()
    font = choice(MAIN_FONTS)
    pdf.set_font(font, size=11)

    # Arguments processing

    try:
        nb_medics = len(kwargs["medication"])
    except KeyError:
        nb_medics = randint(1, 5)

    field_group_values = {
        "doc_attributes": {
            "city": fake.city(),
            "date": fake.date(pattern="%d/%m/%Y"),
        },
        "medical_centre": {
            "city": fake.city(),
            "street_address": fake.street_address(),
            "postal_code": randint(1000, 10000) * 10,
            "phone_number": fake.phone_number(),
        },
        "doctor": {
            "first_name": fake.first_name(),
            "last_name": fake.last_name(),
            "street_address": fake.street_address(),
            "postal_code": randint(1000, 10000) * 10,
            "city": fake.city(),
            "phone_number": fake.phone_number(),
        },
        "patient": {
            "first_name": first_name or fake.first_name(),
            "last_name": last_name or fake.last_name(),
            "age": randint(10, 100),
            "weight": randint(30, 110),
        },
        "medication": [],
    }

    for _ in range(nb_medics):
        field_group_values["medication"].append({
            "name":
            choice(MEDIC),
            "dose":
            5 * randint(1, 10),
            "poso_qty":
            randint(1, 3),
            "poso_type":
            choice(POSO_TYPE),
            "poso_freq":
            choice(POSO_FREQ),
            "poso_duration":
            choice(POSO_DURATION),
        })

    for group_name in {
            "doc_attributes", "medical_centre", "doctor", "patient"
    }:
        for field_name in field_group_values[group_name]:
            try:
                field_group_values[group_name][field_name] = kwargs[
                    group_name][field_name]
            except KeyError:
                pass

    if "medication" in kwargs.keys():
        for i in range(nb_medics):
            for field_name in field_group_values["medication"][i]:
                try:
                    field_group_values["medication"][i][field_name] = kwargs[
                        "medication"][i][field_name]
                except KeyError:
                    pass

    for group_name, group_values in kwargs.items():
        if not group_name in field_group_values:
            print(f"Attributes group '{group_name}' is not recognized.")
        elif group_name in {
                "doc_attributes", "medical_centre", "doctor", "patient"
        }:
            for field_name in group_values.keys():
                if not field_name in field_group_values[group_name]:
                    print(
                        f"Attribute '{field_name}' from group '{group_name}' is not recognized."
                    )
        else:
            assert group_name == "medication", f"Unexpected argument."
            assert (
                type(kwargs["medication"]) == list
            ), f"Wrong argument type : 'medication' argument must be a list of dictionnaries."
            for i in range(nb_medics):
                for field_name in kwargs["medication"][i].keys():
                    if not field_name in field_group_values["medication"][
                            i].keys():
                        print(
                            f"Attribute '{field_name}' from medication #{i} is not recognized."
                        )

    # En-tête

    header = f"""À {field_group_values["doc_attributes"]["city"]}, le {field_group_values["doc_attributes"]["date"]}     


    """
    add_block(pdf, header, align="R")

    # Centre médical

    medical_center_details = f"""
Centre Médical de {field_group_values["medical_centre"]["city"]}
{field_group_values["medical_centre"]["street_address"]}
{field_group_values["medical_centre"]["postal_code"]} {field_group_values["medical_centre"]["city"]}
{field_group_values["medical_centre"]["phone_number"]}
"""

    pdf.set_font(font, "B", size=11)
    add_block(pdf, medical_center_details, align="C")
    pdf.set_font(font, size=11)

    # Docteur

    doctor_details = f"""
        Docteur {field_group_values["doctor"]["last_name"]}
        {field_group_values["doctor"]["street_address"]}
        {field_group_values["doctor"]["postal_code"]} {field_group_values["doctor"]["city"]}
        Tél. : {field_group_values["doctor"]["phone_number"]}
"""
    add_block(pdf, doctor_details)

    # Patient

    patient_details = f"""
        {field_group_values["patient"]["first_name"]} {field_group_values["patient"]["last_name"]}
        {field_group_values["patient"]["age"]} ans, {field_group_values["patient"]["weight"]} kg
    """
    add_block(pdf, patient_details)

    # Prescription

    prescription_details = ""
    for i in range(nb_medics):
        medication_details = f"""
        {field_group_values["medication"][i]["name"]} {field_group_values["medication"][i]["dose"]}"""
        prescription_details = f"{prescription_details}\n{medication_details}"
        pdf.set_font(font, "B", size=11)
        add_block(pdf, medication_details)

        posologie_details = f"""          {field_group_values["medication"][i]["poso_qty"]} {field_group_values["medication"][i]["poso_type"]} {field_group_values["medication"][i]["poso_freq"]} {field_group_values["medication"][i]["poso_duration"]}\n"""
        prescription_details = f"{prescription_details}\n{posologie_details}"
        pdf.set_font(font, size=11)
        add_block(pdf, posologie_details)

    # Signature

    font_size = randint(20, 40)
    pdf.add_font("Signature", "", choice(SIGNATURE_FONTS), uni=True)
    pdf.set_font("Signature", size=font_size)

    if pseudonymize:
        signature_details = ""
    else:
        signature_details = f"""
{signature(field_group_values["doctor"]['last_name'])}          {int((40 - font_size) / 20) * randint(0, 20) * ' '}
"""
    add_block(pdf, signature_details, align="R")

    pdf.output(output_path)
    return f"{header}{medical_center_details}{doctor_details}{patient_details}{prescription_details}{signature_details}"
Exemplo n.º 34
0
def cr_generator(output_path, locale="fr_FR", pseudonymize=False, **kwargs):
    """Generates a fake medical report
    Arguments:
        output_path {Path} -- path the ouput pdf file
        patient_name {str} -- patient name to use
        year {int} -- year of the prescription
    """
    directory = os.path.dirname(output_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

    fake = Factory.create(locale)
    pdf = FPDF(format="A4")
    pdf.add_page()
    font = choice(MAIN_FONTS)
    pdf.set_font(font, size=10)

    # Arguments processing

    try:
        nb_medics = len(kwargs["medication"])
    except KeyError:
        nb_medics = randint(1, 5)

    try:
        nb_ant = len(kwargs["antecedent"])
    except KeyError:
        nb_ant = randint(1, 3)

    choice_hospitalization = randint(0, len(HOSP) - 1)
    last_date = fake.date_between()
    duration = randint(0, 16)
    first_date = last_date - timedelta(days=duration)

    field_group_values = {
        "doc_attributes": {
            "city": fake.city(),
            "date": fake.date(pattern="%d/%m/%Y"),
        },
        "medical_centre": {
            "city": fake.city(),
            "street_address": fake.street_address(),
            "postal_code": randint(1000, 10000) * 10,
            "phone_number": fake.phone_number(),
        },
        "doctor": {
            "first_name": fake.first_name(),
            "last_name": fake.last_name(),
            "street_address": fake.street_address(),
            "postal_code": randint(1000, 10000) * 10,
            "city": fake.city(),
            "phone_number": fake.phone_number(),
        },
        "patient": {
            "first_name": fake.first_name(),
            "last_name": fake.last_name(),
            "age": randint(10, 100),
            "weight": randint(30, 110),
        },
        "hospitalization": {
            "reason": HOSP[choice_hospitalization][0],
            "hospitalization": HOSP[choice_hospitalization][1],
        },
        "date": {
            "last_date":
            last_date.strftime("%d/%m/%Y"),
            "first_date":
            first_date.strftime("%d/%m/%Y"),
            "birth_date":
            fake.date_between(start_date="-80y",
                              end_date=first_date).strftime("%d/%m/%Y"),
        },
        "medication": [],
        "antecedent": [],
    }

    for _ in range(nb_medics):
        field_group_values["medication"].append({
            "name":
            choice(MEDIC),
            "dose":
            5 * randint(1, 10),
            "poso_qty":
            randint(1, 3),
            "poso_type":
            choice(POSO_TYPE),
            "poso_freq":
            choice(POSO_FREQ),
            "poso_duration":
            choice(POSO_DURATION),
        })

    for _ in range(nb_ant):
        field_group_values["antecedent"].append(choice(ANT))

    for group_name in {
            "doc_attributes",
            "medical_centre",
            "doctor",
            "patient",
            "hospitalization",
            "date",
    }:
        for field_name in field_group_values[group_name]:
            try:
                field_group_values[group_name][field_name] = kwargs[
                    group_name][field_name]

            except KeyError:
                pass

    if "medication" in kwargs.keys():
        for i in range(nb_medics):
            for field_name in field_group_values["medication"][i]:
                try:
                    field_group_values["medication"][i][field_name] = kwargs[
                        "medication"][i][field_name]
                except KeyError:
                    pass
    if "antecedent" in kwargs.keys():
        for i in range(nb_ant):
            try:
                field_group_values["antecedent"][i] = kwargs["antecedent"][i]
            except:
                pass

    for group_name, group_values in kwargs.items():
        if not group_name in field_group_values:
            print(f"Attributes group '{group_name}' is not recognized.")
        elif group_name in {
                "doc_attributes",
                "medical_centre",
                "doctor",
                "patient",
                "date",
                "hospitalization",
        }:
            for field_name in group_values.keys():
                if not field_name in field_group_values[group_name]:
                    print(
                        f"Attribute '{field_name}'' from group '{group_name}' is not recognized."
                    )
        elif group_name == "antecedent":
            pass
        else:
            assert group_name == "medication", f"Unexpected argument."
            assert (
                type(kwargs["medication"]) == list
            ), f"Wrong argument type : 'medication' argument must be a list of dictionnaries."
            for i in range(nb_medics):
                for field_name in kwargs["medication"][i].keys():
                    if not field_name in field_group_values["medication"][
                            i].keys():
                        print(
                            f"Attribute '{field_name}' from medication #{i} is not recognized."
                        )

    # Centre médical

    medical_center_details = f"""
Centre Médical de {field_group_values["medical_centre"]["city"]}
{field_group_values["medical_centre"]["street_address"]}
{field_group_values["medical_centre"]["postal_code"]} {field_group_values["medical_centre"]["city"]}
{field_group_values["medical_centre"]["phone_number"]}
"""
    pdf.set_font(font, "B", size=11)
    add_block(pdf, medical_center_details, align="L")
    pdf.set_font(font, size=10)

    # Docteur
    doctor_details = f"""
Docteur {field_group_values["doctor"]["last_name"]}
{field_group_values["doctor"]["street_address"]}
{field_group_values["doctor"]["postal_code"]} {field_group_values["doctor"]["city"]}
Tél. : {field_group_values["doctor"]["phone_number"]}
"""
    add_block(pdf, doctor_details)

    # Date
    date_details = f"""À {field_group_values["medical_centre"]["city"]}, le {field_group_values["date"]["last_date"]}     
        """
    add_block(pdf, date_details, align="R")

    # Objet
    object_details = (
        f"   Objet : Compte-rendu d'hospitalisation de {field_group_values['patient']['first_name']} "
        +
        f"{field_group_values['patient']['last_name']} du {field_group_values['date']['first_date']} au "
        + f"{field_group_values['date']['last_date']}\n\n")

    add_block(pdf, object_details, align="L")

    # Hospitalisation
    pdf.set_font(font, size=10)
    hospit_details = field_group_values["hospitalization"]["hospitalization"]
    add_block(pdf, hospit_details, align="L")

    # Signature
    font_size = randint(20, 40)
    pdf.add_font("Signature", "", choice(SIGNATURE_FONTS), uni=True)
    pdf.set_font("Signature", size=font_size)

    if pseudonymize:
        signature_details = ""
    else:
        signature_details = f"""
    {signature(field_group_values["doctor"]['last_name'])}          {int((40 - font_size) / 20) * randint(0, 20) * ' '}
    """
    add_block(pdf, signature_details, align="R")

    pdf.output(output_path)
    return f"{medical_center_details}{doctor_details}{date_details}{object_details}{hospit_details}{signature_details}"
Exemplo n.º 35
0
def process_single_report(path,
                          student_id,
                          gradebook,
                          exam_str,
                          percentile_dict,
                          admin=False):
    '''
    Takes a single row of the gradebook and processes it into a PDF. This requires several components to work,
    namely, a path to where the file should be generated, the ID of the student, the gradebook itself, the
    structure of the exam, and the dictonary of all the percentiles for question scores. These are listed
    clearly below. If this function is called through process_gradebook, it shouldn't have a problem with the
    arguements.

    input: (inherited from process_gradebook when called from the above function unless otherwise specified)
    path: Path to where the file should be put.
    student_id: the ID of the student in order to isolate the row
    gradebook: the dataframe of student scores on the exam.
    exam_str: the exam structure as read from exam_details.json in the structure_files subfolder.
    percentile_dict: a dictonary of percentiles for each question and section. Keys are question or
                     section names, which gives way to a nested dictonary that has possible scores as
                     the keys, and the percentiles that those scores place the sutdent in as values.
    admin: Whether or not we are generating the admin (overall) report.

    returns:
    None: Does not return anything, instead outputs a PDF file which has the same name as the studentID.
    '''

    # generated regardless of type
    tag = list(exam_str.keys())[0]

    # the highest possible score for the exam
    out_of = exam_str[tag][1]

    if admin:
        # We want to get some meta-data in order to view different aspects of the overall report,
        # the basic statistics we aggregate are median and mean for each question.
        exam_to_process = gradebook.agg(["median", 'mean'])
        total_score_mean = exam_to_process.loc['mean', 'Total Score']
        total_score_median = exam_to_process.loc['median', 'Total Score']

        #file_name = "Overall_Student_Report_"+tag.replace(" ", "") + ".pdf"
        filename = 'admin_report'
        grader = "Admin Report"

        intro = '''This is the overall exam report for %s.''' % (tag)

        score_report = '''
        Average Score: %.2f out of %s
        Median Score: %s out of %s''' % (total_score_mean, out_of,
                                         total_score_median, out_of)

        produce_distplot(path,
                         gradebook['Total Score'],
                         int(total_score_median),
                         file_tag="Overall_Graph",
                         out_of=out_of,
                         admin=admin)

    else:
        # filter DF into series for easy manipulation
        exam_to_process = gradebook[gradebook['Student ID'] == student_id]
        exam_to_process = exam_to_process.iloc[-1]

        # extract repeated information
        grader = exam_to_process['Grader']

        # we extract the first name of the student as the filename
        names = exam_to_process['name'].split()

        #last_name = exam_to_process['name'].split()[-1].strip()

        separator = '_'

        filename = separator.join(names)

        #file_name = exam_to_process['name'].strip()+"_"+tag+".pdf"
        total_score = exam_to_process['Total Score']

        # set up text info
        intro = '''Hello %s,
        \t\tThis is your exam report for the %s. Your grader was %s, so please feel free 
        to reach out to them if you have additional questions about the exam.''' % (
            exam_to_process['name'], tag, grader)

        comment_typecast = str(exam_to_process["Exam Comment"].encode(
            'UTF-8', 'ignore'))
        comment_typecast = comment_typecast[slice(2,
                                                  len(comment_typecast) - 1)]

        score_report = '''
        Overall: %s out of %s
        Which places you at the %s percentile.\n\n
        Overall Comment: %s''' % (
            exam_to_process['Total Score'], out_of,
            percentile_dict['Total Score'][str(total_score)], comment_typecast)

        print("*" * 50, "\n", path, "\n", "*" * 50)

        # create a distribution for the overall score.
        produce_distplot(path,
                         gradebook['Total Score'].astype(float),
                         exam_to_process['Total Score'],
                         file_tag="Overall_Graph",
                         out_of=out_of)

    # initiate PDF object, format header

    pdf = FPDF()
    pdf.add_page()
    pdf.image("./structure_files/nycdsalogo.png", x=55, y=8, w=100)

    pdf.set_line_width(0.5)
    pdf.set_fill_color(255, 0, 0)
    pdf.line(10, 35, 200, 35)

    pdf.set_font("Arial", size=12)
    pdf.ln(30)
    pdf.multi_cell(190, 6, txt=intro, align="L")
    pdf.ln(2)

    y_image = pdf.get_y()

    pdf.ln(2)
    pdf.set_font("Arial", size=12)
    pdf.multi_cell(95, 6, txt=score_report, align="L")

    pdf.set_font("Arial", size=10)

    pdf.set_y(y_image)
    pdf.image(path + "images/Overall_Graph.png", x=110, w=90)

    pdf.line(10, pdf.get_y(), 200, pdf.get_y())

    pdf.ln(2)

    pdf.line(10, pdf.get_y(), 200, pdf.get_y())

    # a brief note on the alternating format of the PDF: we handle this via an if/else
    # below, where if alignment is either "L" or "R", it is switched to be the opposite.
    # this allows us to easily go between the left handed and right handed formats. We decide to
    # start with "R", which will give us "L" when formatting the first section or question.
    alignment = "R"

    for item in exam_str[tag][0].items():
        alignment = "L" if alignment == "R" else "R"
        if type(item[1][0]) == dict:
            ## process section
            print("Section name:", item[0])
            fmt_section(path=path,
                        pdf=pdf,
                        section_name=item[0],
                        section_str=item[1][0],
                        gradebook=gradebook,
                        exam_to_process=exam_to_process,
                        out_of=item[1][1],
                        percentile_dict=percentile_dict,
                        align=alignment,
                        admin=admin)

        elif type(item[1][0] == str):
            ## process question
            print("Question name:", item[0])
            fmt_question(path=path,
                         pdf=pdf,
                         question_name=item[0],
                         question_text=item[1][0],
                         gradebook=gradebook,
                         exam_to_process=exam_to_process,
                         out_of=item[1][1],
                         align=alignment,
                         admin=admin)

        pdf.ln(2)
        y_space = pdf.get_y()
        pdf.line(10, y_space, 200, y_space)

    # make sure the path to the reports exists!
    if not os.path.isdir(path + "reports/"):
        os.makedirs(path + "reports/")

    # and then generate the report, along with printing the pdf_path for a quick sanity check.
    pdf_path = path + "reports/" + filename + ".pdf"
    #pdf_path = path+"reports/"+student_id+".pdf"
    #pdf_path = pdf_path.replace('\u2019', "")
    print(pdf_path)
    print("Report generated!\n\n\n\n", "*" * 50)
    pdf.output(pdf_path)
Exemplo n.º 36
0
    def add_files_to_pdf(
        self,
        files: list = None,
        target_document: str = None,
    ) -> None:
        """Add images and/or pdfs to new PDF document

        Image formats supported are JPEG, PNG and GIF.

        The file can be added with extra properties by
        denoting `:` at the end of the filename.add()

        Supported extra properties are:

        - for PDF, the page numbers to be included in the new PDF document
        - for images, the position of the image in the new PDF document

        **Examples**

        **Robot Framework**

        .. code-block:: robotframework

            ***Settings***
            Library    RPA.PDF

            ***Tasks***
            Add files to pdf
                ${files}=    Create List
                ...    ${TESTDATA_DIR}${/}invoice.pdf
                ...    ${TESTDATA_DIR}${/}approved.png:center
                ...    ${TESTDATA_DIR}${/}robot.pdf:1
                ...    ${TESTDATA_DIR}${/}approved.png:x=0,y=0
                ...    ${TESTDATA_DIR}${/}robot.pdf:2-10,15
                ...    ${TESTDATA_DIR}${/}approved.png
                Add Files To PDF    ${files}    newdoc.pdf

        **Python**

        .. code-block:: python

            from RPA.PDF import PDF

            pdf = PDF()

            list_of_files = [
                'invoice.pdf',
                'approved.png:center',
                'robot.pdf:1',
                'approved.png:x=0,y=0',
            ]
            def example_keyword():
                pdf.add_files_to_pdf(
                    files=list_of_files,
                    target_document="output/output.pdf"
                )

        :param files: list of filepaths to add into PDF (can be either images or PDFs)
        :param target_document: filepath of target PDF
        """
        writer = PyPDF2.PdfFileWriter()

        for f in files:
            file_to_add = Path(f)
            namesplit = file_to_add.name.rsplit(":", 1)
            basename = namesplit[0]
            parameters = namesplit[1] if len(namesplit) == 2 else None
            file_to_add = file_to_add.parent / basename
            image_filetype = imghdr.what(str(file_to_add))
            self.logger.info("File %s type: %s" %
                             (str(file_to_add), image_filetype))
            if basename.endswith(".pdf"):
                reader = PyPDF2.PdfFileReader(str(file_to_add), strict=False)
                pagecount = reader.getNumPages()
                pages = self._get_pages(pagecount, parameters)
                for n in pages:
                    try:
                        page = reader.getPage(n - 1)
                        writer.addPage(page)
                    except IndexError:
                        self.logger.warning("File %s does not have page %d" %
                                            (file_to_add, n))
            elif image_filetype in ["png", "jpg", "jpeg", "gif"]:
                temp_pdf = os.path.join(tempfile.gettempdir(), "temp.pdf")
                pdf = FPDF()
                pdf.set_margin(0)
                pdf.add_page()
                x, y, width, height = self._get_image_coordinates(
                    str(file_to_add), parameters)
                pdf.image(name=file_to_add, x=x, y=y, w=width, h=height)
                pdf.output(name=temp_pdf)

                reader = PyPDF2.PdfFileReader(temp_pdf)
                writer.addPage(reader.getPage(0))

        with open(target_document, "wb") as f:
            writer.write(f)
Exemplo n.º 37
0
def generate_pdf(id, message):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    pdf.cell(40, 10, message)
    pdf.output(str(id) + '.pdf', 'F')
Exemplo n.º 38
0
def create_pdf(input):

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

    pdf.add_font('DGUVMeta-Normal', '', 'DGUVMeta-Normal.ttf', uni=True)
    pdf.add_font('DGUVMeta-Bold', '', 'DGUVMeta-Bold.ttf', uni=True)
    pdf.add_font('DGUVMeta-NormalItalic', '', 'DGUVMeta-NormalItalic.ttf', uni=True)

    pdf.image("newtemplate3_seite1.jpg", x=-4, y=-8, w=217, h=313)

    data = {}
    input = input.get("data")

    # Kopffragen

    data["arbeitsstelle"] = input.get('#/properties/arbeitsstelle-arbeitsort')
    data["datum_uhrzeit"] = input.get('#/properties/datum-und-uhrzeit')
    data["person_anlageverantwortlichkeit"] = input.get('#/properties/person-in-der-rolle-des-anlagenverantwortlichen')
    data["person_arbeitsverantwortlichkeit"] = input.get('#/properties/person-in-der-rolle-des-arbeitsverantwortlichen')
    data["person_arbeitsausfuehrung"] = input.get('#/properties/arbeitsausfuhrende-person')

    if 'gegen elektrischen Schlag' in input.get('#/properties/zusatzliche-personliche-schutzausrustung-bei-der-1'):
        data["zusaetzliche_schutzausrüstung_elektrischerschlag"] = "x"
    else:
        data["zusaetzliche_schutzausrüstung_elektrischerschlag"] = ""

    if 'gegen Störlichtbogen' in input.get('#/properties/zusatzliche-personliche-schutzausrustung-bei-der-1'):
        data["zusaetzliche_schutzausrüstung_stoerlichtbogen"] = "x"
    else:
        data["zusaetzliche_schutzausrüstung_stoerlichtbogen"] = ""

    if input.get('#/properties/stehen-andere-anlagenteile-weiterhin-unter') == "ja":
        data["abgrenzung_arbeitsbereich_ja"] = "x"
    else:
        data["abgrenzung_arbeitsbereich_ja"] = ""

    if input.get('#/properties/stehen-andere-anlagenteile-weiterhin-unter') == "nein":
        data["abgrenzung_arbeitsbereich_nein"] = "x"
    else:
        data["abgrenzung_arbeitsbereich_nein"] = ""

    # 1A

    data["art_der_freischaltung1a"] = input.get('#/properties/edi6a8f77755207467090eddf15f6a21e87')

    if data["art_der_freischaltung1a"] == "NH-Sicherungen":
        data["ausloesestrom1a"] = input.get('#/properties/edibedde3faf5304b9bb0101e9b23f5d284')
    elif data["art_der_freischaltung1a"] == "NH-Lastschaltleiste":
        data["ausloesestrom1a"] = input.get('#/properties/edi78c896ef894445108dc67298d8b3318c')
    elif data["art_der_freischaltung1a"] == "Leistungsschalter":
        data["ausloesestrom1a"] = input.get('#/properties/edi58255093bbca48999e2aaae5462f3c82')
    else:
        data["ausloesestrom1a"] = "/"

    data["ort_der_freischaltung1a"] = input.get('#/properties/edi1c959df02d0e4f65ac31465aed4ed8c6')

    if data["ort_der_freischaltung1a"] == "Kabelverteilerschrank":
        data["nroderbezeichnung1a"] = input.get('#/properties/edi424a0be1228145318070ee2f83c7b639')
    elif data["ort_der_freischaltung1a"] == "Trafostation":
        data["nroderbezeichnung1a"] = input.get('#/properties/edi5a9acfa863614586845b7fd9918cafc8')
    elif data["ort_der_freischaltung1a"] == "Kompaktstation":
        data["nroderbezeichnung1a"] = input.get('#/properties/edi1af11b6f7ca74a85a9f8c1888071215f')

    data["zusaetzlichfreigeschaltet1a"] = input.get('#/properties/edi39026745e38e4279b3113e51c8d76d50')

    if data["zusaetzlichfreigeschaltet1a"] == ['im Hausanschlusskasten (wegen dezentraler Einspeisung, z. B. PV-Anlage, BHKW)']:
        data["zusaetzlichfreigeschaltet1a"] = 'im Hausanschlusskasten (wegen dezentraler Einspeisung, z. B. PV-Anlage, BHKW)'
    else:
        data["zusaetzlichfreigeschaltet1a"] = ''

    # 1B

    data["art_der_freischaltung1b"] = input.get('#/properties/ediaa9552464dcf4b7f96903f645ed53b63')

    if data["art_der_freischaltung1b"] == "NH-Sicherungen":
        data["ausloesestrom1b"] = input.get('#/properties/edi1cb1f54ea8e041ff85d4b19d46b54f2d')
    elif data["art_der_freischaltung1b"] == "NH-Lastschaltleiste":
        data["ausloesestrom1b"] = input.get('#/properties/edi378aec1700974f628e5a08c2b2f63d6c')
    elif data["art_der_freischaltung1b"] == "Leistungsschalter":
        data["ausloesestrom1b"] = input.get('#/properties/edi004df17a3e1e4d299e0bd5123f0f18d0')
    else:
        data["ausloesestrom1b"] = "/"

    data["ort_der_freischaltung1b"] = input.get('#/properties/edicda586dcbda14b88863b1e780bdcf787')

    if data["ort_der_freischaltung1b"] == "Kabelverteilerschrank":
        data["nroderbezeichnung1b"] = input.get('#/properties/edif856292285394eb7920585f54d02644a')
    elif data["ort_der_freischaltung1b"] == "Trafostation":
        data["nroderbezeichnung1b"] = input.get('#/properties/edi099d5d84e51e4e638fe8c175a2542e9f')
    elif data["ort_der_freischaltung1b"] == "Kompaktstation":
        data["nroderbezeichnung1b"] = input.get('#/properties/edi017c5fa9e6cc48f284d71bf87d3e9d7f')

    data["zusaetzlichfreigeschaltet1b"] = input.get('#/properties/edid0995ee6abad4deeb59519bfb7440c32')

    if data["zusaetzlichfreigeschaltet1b"] == ['im Hausanschlusskasten (wegen dezentraler Einspeisung, z. B. PV-Anlage, BHKW)']:
        data["zusaetzlichfreigeschaltet1b"] = 'im Hausanschlusskasten (wegen dezentraler Einspeisung, z. B. PV-Anlage, BHKW)'
    else:
        data["zusaetzlichfreigeschaltet1b"] = ''

    # 2A

    data["schloss2a"] = input.get('#/properties/edi6b58b8a2d67a43b69428560b9814730b')
    data["schalten_verboten2a"] = input.get('#/properties/edie1a1691433504d06ada6e73dbe580d80')

    # 2B

    data["schloss2b"] = input.get('#/properties/edibd10b6f4f90a4786b3753ed927e45f44')
    data["schalten_verboten2b"] = input.get('#/properties/edie9bfd532c7724f989e9841c8dc9b8425')

    # 3A

    data["spannungspruefer3a"] = input.get('#/properties/edi2ab6fcfb494f483bbc0d3bc735e7d8cd')

    # 3B

    data["spannungspruefer3b"] = input.get('#/properties/edi8c4fababb3cd4426894252045c83d088')

    # 3C

    data["pruefungsart3c"] = input.get('#/properties/edib201ffc9d8154fd5ba5982f8c1e9ad7a')

    if data["pruefungsart3c"] == "Andere Methode":
        data["erlauterung3c"] = input.get('#/properties/edi8b65c32610b7485aa4475e7aea8921b5')
    else:
        data["erlauterung3c"] = ""

    # 4

    data["euk_wo"] = input.get('#/properties/edice9c36613f404d818c5f11a72028d86e')

    if data["euk_wo"] == "Nicht geerdet und kurzentschlossen":
        data["euk_begruendung"] = input.get('#/properties/edi32732bbb05eb4ad6a23ad8ca3a6ce6af')

    # 5

    data["ziel_der_abdeckung"] = input.get('#/properties/edi083dd47e5405445d9d452b34d5bfd82c')

    if data["ziel_der_abdeckung"] == "teilweiser Berührungsschutz":
        data["art_der_abdeckung"] = ', '.join(input.get('#/properties/edic7f067d9bb594c618d6d8c5d96b1d9fc'))
    elif data["ziel_der_abdeckung"] == "vollständiger Berührungsschutz":
        data["art_der_abdeckung"] = ', '.join(input.get('#/properties/edi18d247e0ad8f4e90b205425be8b4f259'))
    elif data["ziel_der_abdeckung"] == "Abdeckung nicht notwendig":
        data["art_der_abdeckung"] = input.get('#/properties/edifa3e5b24ed8a433ea4f2b63fa2c9407f')
        if data.get("art_der_abdeckung") == "die Entfernung beträgt ca.:":
            data["entfernung"] = input.get('#/properties/edi448aa2c4d1dc4141bbe961fa1456cab2')
    else:
        data["art_der_abdeckung"] = ""

    # Title

    pdf.set_font('DGUVMeta-Bold', '', 20)
    pdf.set_text_color(0,73,148)
    pdf.set_xy(12.7, 63.25)
    pdf.cell(0, 0, 'Arbeiten an Kabeln in der Niederspannung')

    pdf.set_font('DGUVMeta-Bold', '', 14)
    pdf.set_text_color(0,140,142)
    pdf.set_xy(12.7, 83.5)
    pdf.cell(0, 0, 'EVU')

    # Kopffragen

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 107)
    pdf.set_text_color(0,0,0)
    pdf.cell(0, 0, data.get("arbeitsstelle"))

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 126)
    pdf.cell(0, 0, data.get("datum_uhrzeit"))

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 145)
    pdf.cell(0, 0, data.get("person_anlageverantwortlichkeit"))

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 164)
    pdf.cell(0, 0, data.get("person_arbeitsverantwortlichkeit"))

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(13, 183)
    pdf.cell(0, 0, data.get("person_arbeitsausfuehrung"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_xy(20, 208.5)
    pdf.cell(0, 0, "gegen elektrischen Schlag")

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(14.3, 208.3)
    pdf.cell(0, 0, data.get("zusaetzliche_schutzausrüstung_elektrischerschlag"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_xy(78, 208.5)
    pdf.cell(0, 0, "gegen Störlichbogen")

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(72.2, 208.3)
    pdf.cell(0, 0, data.get("zusaetzliche_schutzausrüstung_stoerlichtbogen"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_xy(20, 232)
    pdf.cell(0, 0, "ja")

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(14.4, 231.6)
    pdf.cell(0, 0, data.get("abgrenzung_arbeitsbereich_ja"))

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_xy(78, 232)
    pdf.cell(0, 0, "nein")

    pdf.set_font('DGUVMeta-Normal', '', 14)
    pdf.set_xy(72.2, 231.6)
    pdf.cell(0, 0, data.get("abgrenzung_arbeitsbereich_nein"))

    #Adding new page

    pdf.add_page()
    pdf.image("newtemplate7_seite2.jpg", x=-4, y=-8, w=217, h=313)

    # 1a Freigeschaltet Ausschaltstelle 1

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 29.2)
    pdf.cell(0, 0, 'Wie erfolgte die Freischaltung?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 34.2)
    pdf.cell(0, 0, data.get("art_der_freischaltung1a"))

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 40.7)
    pdf.cell(0, 0, 'Wo erfolgte die Freischaltung?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 45.7)
    pdf.cell(0, 0, data.get("ort_der_freischaltung1a"))

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 52.2)
    pdf.cell(0, 0, 'Nr. oder Bezeichnung:')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 57.2)
    pdf.cell(0, 0, data.get("nroderbezeichnung1a"))

    if data["zusaetzlichfreigeschaltet1a"] == 'im Hausanschlusskasten (wegen dezentraler Einspeisung, z. B. PV-Anlage, BHKW)':
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 63.7)
        pdf.cell(0, 0, 'Zusätzlich freigeschaltet:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 68.7)
        pdf.cell(0, 0, data.get("zusaetzlichfreigeschaltet1a"))
    else:
        data["zusaetzlichfreigeschaltet1a"] = ''

    # 1b Freigeschaltet Ausschaltstelle 2

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 89)
    pdf.cell(0, 0, 'Wie erfolgte die Freischaltung?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 94)
    pdf.cell(0, 0, data.get("art_der_freischaltung1b"))

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 100.5)
    pdf.cell(0, 0, 'Wo erfolgte die Freischaltung?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 105.5)
    pdf.cell(0, 0, data.get("ort_der_freischaltung1b"))

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 112)
    pdf.cell(0, 0, 'Nr. oder Bezeichnung:')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 117)
    pdf.cell(0, 0, data.get("nroderbezeichnung1b"))

    if data["zusaetzlichfreigeschaltet1b"] == 'im Hausanschlusskasten (wegen dezentraler Einspeisung, z. B. PV-Anlage, BHKW)':
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 123.5)
        pdf.cell(0, 0, 'Zusätzlich freigeschaltet:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 128.5)
        pdf.cell(0, 0, data.get("zusaetzlichfreigeschaltet1b"))
    else:
        data["zusaetzlichfreigeschaltet1b"] = ''

    # 2a Gegen Wiedereinschalten gesichert Ausschaltstelle 1

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 147.5)
    pdf.cell(0, 0, 'Wurde ein Vorhängeschloss am (Leistungs-) Schalter eingehängt und abgeschlossen?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 152.5)
    pdf.cell(0, 0, data.get("schloss2a"))

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 159)
    pdf.cell(0, 0, 'Wurde ein Schild "Schalten verboten" zusätzlich angebracht?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 164)
    pdf.cell(0, 0, data.get("schalten_verboten2a"))

    # 2b Gegen Wiedereinschalten gesichert Ausschaltstelle 2

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 196)
    pdf.cell(0, 0, 'Wurde ein Vorhängeschloss am (Leistungs-) Schalter eingehängt und abgeschlossen?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 201)
    pdf.cell(0, 0, data.get("schloss2b"))

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 207.5)
    pdf.cell(0, 0, 'Wurde ein Schild "Schalten verboten" zusätzlich angebracht?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 212.5)
    pdf.cell(0, 0, data.get("schalten_verboten2b"))

    # 3a Spannungsfreiheit allpolig festgestellt an der Ausschaltstelle1

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 256)
    pdf.cell(0, 0, 'Zweipoliger Spannungsprüfer:')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 261)
    pdf.cell(0, 0, data.get("spannungspruefer3a"))

    # Adding new page

    pdf.add_page()
    pdf.image("newtemplate7_seite3.jpg", x=-4, y=-8, w=217, h=313)

    # 3b Spannungsfreiheit allpolig festgestellt an der Ausschaltstelle 2

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 22)
    pdf.cell(0, 0, 'Zweipoliger Spannungsprüfer:')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 27)
    pdf.cell(0, 0, data.get("spannungspruefer3b"))

    # 3c Spannungsfreiheit allpolig festgestellt an der Arbeitsstelle

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 50)
    pdf.cell(0, 0, 'Wie wurde geprüft?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 55)
    pdf.cell(0, 0, data.get("pruefungsart3c"))

    if data["pruefungsart3c"] == "Andere Methode":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 61.5)
        pdf.cell(0, 0, 'Erläuterung der Methode')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 66.5)
        pdf.cell(0, 0, data.get("erlauterung3c"))

    # 4 Geerdet und kurzgeschlossen an den Ausschaltstellen

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 94)
    pdf.cell(0, 0, 'Wo wurde die EuK-Vorrichtung in die NH-Sicherungsunterteile eingebaut?')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 99)
    pdf.cell(0, 0, data.get("euk_wo"))

    if data["euk_wo"] == "Nicht geerdet und kurzentschlossen":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 105.5)
        pdf.cell(0, 0, 'Begründung:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 110.5)
        pdf.cell(0, 0, data.get("euk_begruendung"))

    # 5 Mit der Abdeckung soll erreicht werden

    pdf.set_font('DGUVMeta-Bold', '', 10)
    pdf.set_text_color(35,31,32)
    pdf.set_xy(12.7, 139)
    pdf.cell(0, 0, 'Mit der Abdeckung soll erreicht werden:')

    pdf.set_font('DGUVMeta-Normal', '', 10)
    pdf.set_text_color(0,0,0)
    pdf.set_xy(12.7, 144)
    pdf.cell(0, 0, data.get("ziel_der_abdeckung"))

    if data["ziel_der_abdeckung"] == "teilweiser Berührungsschutz":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 150.5)
        pdf.cell(0, 0, 'Art der Abdeckung:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 155.5)
        pdf.cell(0, 0, data.get("art_der_abdeckung"))
    elif data["ziel_der_abdeckung"] == "vollständiger Berührungsschutz":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 150.5)
        pdf.cell(0, 0, 'Art der Abdeckung:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 155.5)
        pdf.cell(0, 0, data.get("art_der_abdeckung"))
    elif data["ziel_der_abdeckung"] == "Abdeckung nicht notwendig":
        pdf.set_font('DGUVMeta-Bold', '', 10)
        pdf.set_text_color(35, 31, 32)
        pdf.set_xy(12.7, 150.5)
        pdf.cell(0, 0, 'Keine Abdeckung angebracht, weil:')

        pdf.set_font('DGUVMeta-Normal', '', 10)
        pdf.set_text_color(0, 0, 0)
        pdf.set_xy(12.7, 155.5)
        pdf.cell(0, 0, data.get("art_der_abdeckung"))

        if data.get("art_der_abdeckung") == "die Entfernung beträgt ca.:":
            pdf.set_font('DGUVMeta-Normal', '', 10)
            pdf.set_text_color(35, 31, 32)
            pdf.set_xy(12.7, 160.5)
            pdf.cell(0, 0, str(data.get("entfernung") + " Meter"))

    pdf.output("s138.pdf", "F")
Exemplo n.º 39
0
def autoscreen():
    if var1:
        os.startfile(file_path)
    else:
        subprocess.run(['open', file_path], check=True)
    if file_format:
        time.sleep(3)
    else:
        time.sleep(3)
        keyboard.press(Key.f5)
        time.sleep(2)
    i = True
    global k
    k = 0
    while i:
        myScreenshot = pyautogui.screenshot()
        myScreenshot.save(path + str(k) + '.png')
        im = pic.open(path + str(k) + '.png')
        pixels = im.getdata()  # get the pixels as a flattened sequence
        black_thresh = 260
        nblack = 0
        for pixel in pixels:
            if sum(pixel) < black_thresh:
                nblack += 1
        n = len(pixels)

        if (nblack / float(n)) > 0.5:
            i = False
        else:
            i = True
            l = im.size
            aspect = calculate_aspect(l[0], l[1])
            if ratio:
                multi = (aspect[0] - (4 * (aspect[1] / 3))) / 2
                w = l[0] / aspect[0]
                h = l[1]
                imn = im.crop((multi * w, 0, l[0] - multi * w, h))
            else:
                multi = (aspect[1] - (9 * (aspect[0] / 16))) / 2
                w = l[0]
                h = l[1] / aspect[0]
                imn = im.crop((0, multi * h, w, l[1] - multi * h))
            imn.save(path + str(k) + '.png', "PNG")
            k += 1

        keyboard.press(Key.space)
        time.sleep(wait)
    choose()
    fpdf = FPDF('L', 'mm', 'A4')
    while len(choosenimg) > 0:
        fpdf.add_page()
        print(len(choosenimg))
        if ratio:
            if len(choosenimg) > 3:
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 2, 136,
                           102)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 159, 2, 136,
                           102)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 106, 136,
                           102)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 159, 106,
                           136, 102)
            elif len(choosenimg) > 2:
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 2, 136,
                           102)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 159, 2, 136,
                           102)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 106, 136,
                           102)
            elif len(choosenimg) > 1:
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 2, 136,
                           102)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 159, 2, 136,
                           102)
            else:
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 2, 136,
                           102)
        else:
            if len(choosenimg) > 3:
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 2, 144,
                           81)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 151, 2, 144,
                           81)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 125, 144,
                           81)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 151, 125,
                           144, 81)
            elif len(choosenimg) > 2:
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 2, 144,
                           81)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 151, 2, 144,
                           81)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 125, 144,
                           81)
            elif len(choosenimg) > 1:
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 2, 144,
                           81)
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 151, 2, 144,
                           81)
            else:
                fpdf.image(path + str(choosenimg.pop(0)) + '.png', 2, 2, 144,
                           81)
    fpdf.output(pdfname + ".pdf", "F")
Exemplo n.º 40
0
            def create_pdf2(self):
                # Set up a logo
                shost = self.lineEdit.text()
                shost2 = self.lineEdit_2.text()
                shost3 = self.lineEdit_3.text()

                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, 130, ' ', 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,5, ' ', ln=1)
                pdf.cell(12)
                pdf.cell(0, 7, 'Chẩn đoán : %s'% (shost), ln=1)
                pdf.cell(12)
                pdf.cell(0, 7, 'Điều trị : %s'% (shost2), ln=1)
                pdf.cell(12)
                pdf.cell(0, 7, 'Chỉ định bác sĩ : %s'% (shost3), ln=1)

                pdf.set_x(120)
                pdf.cell(0, 14, " 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)"])))
                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()
                self.hide()
Exemplo n.º 41
0
        <meta http-equiv="refresh" content="0.3; URL=/table/"/>
    </head>
    <script>alert("Данные добавлены");</script>
    ''')  # Уведомляем пользователя о том, что данные уже добавлены и возвращаемя обратно к таблице
elif 'exportPdfButton' in form:     # Если нажата кнопка "Экспортировать таблицу в PDF"
    newPdf = FPDF()                 # Создаем pdf и добавляем шрифт для записи русских символов
    newPdf.add_font('Athena', '', 'font/new_athena_unicode.ttf', uni=True)
    cursor = db.cursor()  # Создаем курсор перед выполением запроса
    cursor.execute('''
        SELECT p.surname, p.name, p.patronymic, r.region, c.city, p.telephone, p.email FROM peoples p
        JOIN regions r ON p.regionId = r.id
        JOIN cities c ON (p.cityId=c.id AND p.regionId = c.regionId)
    ''')  # Получаем все данные с таблицы
    peoples = cursor.fetchall()                             # Забираем все найденные данные
    for i, person in enumerate(peoples):                    # Постепенно заполняем файл
        newPdf.add_page()                                   # Создаем новую страницу в файле (для резюме следующего человека из списка)
        newPdf.set_font(family="Athena", size=30)           # Устанавливаем шрифт
        newPdf.cell(0, 10, txt="Резюме {}".format(i+1), ln=1, align="C")    # Заголовок
        newPdf.cell(0, 10, txt="", ln=1, align="C")         # Новая строчка
        fio = ' '.join([person[0], person[1]])              # Имя и Фамилия соединятются через пробел
        if person[2] != '-':
            fio = ' '.join([fio, person[2]])                # Если указано и отчество, то присоединяем и отчество
        newPdf.cell(0, 10, txt=fio, ln=1, align="C")        # Вставляем строчку с ФИО
        newPdf.set_font(family="Athena", size=20)           # Устанавливаем шрифт (уменьшаем размер)
        location = ''
        if person[3] != '-' and person[4] == '-':
            location = person[3]
        elif person[3] == '-' and person[4] != '-':
            location = person[4]
        else:
            location = ', '.join([person[3], person[4]])
Exemplo n.º 42
0
 def pdf_generate(self, ref_no, account_no, garrentee_no, name, address,
                  date, Email_id):
     """
     This Function gives pdf output in a OutputData folder
     :param ref_no
     :param account_no
     :param garrentee_no
     :param name name
     :param address
     :param date is date of birth
     :param Email_id
     """
     pdf = FPDF(format='A4', unit='in')
     pdf.set_margins(1.0, 0.0, 0.8)
     pdf.add_page()
     pdf.set_font('arial', '', 10)
     column_width = 6.5
     column_spacing = 0.15
     ybefore = pdf.get_y()
     pdf.set_xy(column_width + pdf.l_margin + column_spacing, ybefore)
     pdf.cell(column_width, 1, txt="", ln=1)
     pdf.cell(column_width, 0.2, txt=("Ref No.  : " + str(ref_no)), ln=1)
     pdf.cell(column_width,
              0.2,
              txt=("Account No.: " + str(account_no)),
              ln=1)
     pdf.cell(column_width, 0.2, txt="", ln=1, align="L")
     pdf.set_font("arial", 'B', 12)
     pdf.cell(column_width,
              0.2,
              txt="Python Script to Write pdf".rjust(60, ' '),
              ln=1,
              align="L")
     pdf.cell(column_width, 0.2, txt="", ln=1, align="L")
     pdf.set_font("arial", size=10)
     pdf.cell(column_width, 0.2, txt=("Name :  " + name), ln=1, align="L")
     pdf.cell(column_width, 0.2, txt="", ln=1, align="C")
     pdf.cell(column_width,
              0.2,
              txt=("Address : ".ljust(7) + address),
              ln=1,
              align="L")
     pdf.cell(column_width,
              0.2,
              txt=("Date of birth : " + str(date)),
              ln=1,
              align="L")
     pdf.cell(column_width, 0.2, txt="", ln=1, align="L")
     pdf.cell(column_width,
              0.2,
              txt="Email Id : " + Email_id,
              ln=1,
              align="L")
     pdf.image(self.Basepath + '/InputImage/sign.jpg', x=1.0, y=3.3, w=2.5)
     pdf.line(3.4, 4.05, 1.1, 4.05)
     pdf.set_line_width(1)
     pdf.set_draw_color(255, 255, 255)
     pdf.cell(column_width, 0.91, txt="", ln=1, align="L")
     pdf.cell(column_width,
              0.2,
              txt="Authorized Signature",
              ln=1,
              align="L")
     pdf.ln(0.1)
     pdf.cell(column_width,
              0.4,
              txt="Visualizing Tabuler data in pdf all formate : " +
              str(garrentee_no),
              ln=1,
              align="L")
     pdf.ln(0.4)
     pdf.set_font("arial", 'B', 11)
     data = [['City No ', 'Work Permit To ', 'City No ', 'Work Permit To']]
     spacing = 1.5
     col_width = pdf.w / 5.5
     row_height = pdf.font_size
     for row in data:
         for item in row:
             pdf.cell(col_width, row_height * spacing, txt=item, border=1)
         pdf.ln(row_height * spacing)
     pdf.set_font("arial", '', 11)
     work_permit_no = [
         'Mum 43712-', 'bang 3712-', 'Hyd 43712-', 'Pune 171-',
         'delhi 371-', 'US 743-', 'UK 743712-'
     ]
     df = pd.DataFrame({
         'City No': [],
         'Work Permit To': [],
         'City No.': [],
         'Work Permit To.': []
     })
     for i, item in enumerate(work_permit_no):
         j = '{:d}'.format(i + 1).zfill(3)
         if (i + 1) % 2 == 0:
             df = df.append({
                 'City No ': j,
                 'Work Permit To ': item
             },
                            ignore_index=True)
         else:
             df = df.append({
                 'City No': j,
                 'Work Permit To': item
             },
                            ignore_index=True)
     df1 = df.dropna(subset=['City No'], how='all')
     df2 = df.dropna(subset=['City No '], how='all')
     result1 = pd.concat([df1['City No'], df1['Work Permit To']],
                         axis=1,
                         sort=False)
     result2 = pd.concat([df2['City No '], df2['Work Permit To ']],
                         axis=1,
                         sort=False)
     result1.reset_index(drop=True, inplace=True)
     result2.reset_index(drop=True, inplace=True)
     result = pd.concat([result1, result2], axis=1)
     result = result.to_string(justify='left',
                               index=False,
                               header=False,
                               col_space=30,
                               na_rep='',
                               float_format="%d")
     pdf.multi_cell(column_width, 0.30, result)
     data = os.path.isdir(self.Basepath + '\\' + 'OutputData')
     if data is False:
         os.mkdir(self.Basepath + '\\' + 'OutputData')
     pdf.output(self.Basepath + '/OutputData/pdf.pdf', 'F')
Exemplo n.º 43
0
y.addpages(x.pages)
y.write(uploaded_file)
pdf_writer = PdfFileWriter()
# pdf_writer = FPDF()

pdfFileObj = uploaded_file
pdfReader = PyPDF4.PdfFileReader(pdfFileObj)

totalpaginas = pdfReader.getNumPages()

#############

WIDTH = 210
HEIGHT = 297
pdf_background = FPDF()
pdf_background.add_page()
pdf_background.image("rect1.png", 10, 280, WIDTH - 50, HEIGHT - 100)
pdf_background.output("rect.pdf", "F")
pdf_background = PdfFileReader(open("rect.pdf", "rb"))
pdf_background.getPage(0)

for i in range(totalpaginas):

    pageObj = pdfReader.getPage(i)
    teste = pageObj.extractText().split()
    contador1 = 0
    contador2 = 0

    for j in teste:
        if j == 'dinheiro.':
            p = pdfReader.getPage(i)
#for python 3 install fpdf package "pip3 install fpdf".

from fpdf import FPDF

#class object FPDF() which is predefiend in side the package fpdf.
document = FPDF(orientation='P', unit='mm', format='A4')
# pdf = FPDF('P', 'mm', (100, 150)) with custom size

document.set_title("This is custom title")

document.set_margins(25, 20, 20)
# left, top, right...... Define before creating page, otherwise will ruin formatting

#There is no page for the moment, so we have to add one with add_page.
document.add_page()

#the bottom margin is simply left out of predefinition because it is part of the page break calculation process.
#Therefore, setting a bottom margin in itself is not possible, but it can be done using
#SetAutoPageBreak(boolean auto, [float margin])

#font size setting of the page
document.set_font("Arial", size=20)

document.set_text_color(255, 255, 255)

document.set_fill_color(20, 50, 80)
# cell fill colour, visible if cell property fill set to true

document.set_draw_color(190, 9, 30)
# border color, used for all drawing operations (lines, rectangles and cell borders)
Exemplo n.º 45
0
    def save(self, name, surname, adress, phone, email):

        # sprawdzamy czy pola nie sa puste
        if len(name) == 0 or len(surname) == 0 or len(adress) == 0 or len(
                phone) == 0 or len(email) == 0:
            messagebox.showwarning(title="Information",
                                   message="Fill all fields.")
            return False

        if self.cnx.is_connected() != True:
            # nie ma polaczenia wiec zrob reconnect
            self.cnx.reconnect()

        # generowanie numeru ean na podstawie imienia i nazwiska
        hash1 = hashlib.sha1()
        hash1.update(str(name + surname).encode('utf-8'))
        ean = str(int(hash1.hexdigest(), 16))[:13]

        # metoda generate_ean
        image = self.generate_ean(ean)

        # zapisz dane do bazy - metoda save()
        cursor = self.cnx.cursor()
        add_user = (
            "INSERT INTO users"
            "(name, surname, adress, phone, email, ean, created_at)"
            "VALUES (%(name)s, %(surname)s, %(adress)s, %(phone)s, %(email)s, %(ean)s, %(created_at)s)"
        )

        # aktualna data i czas
        now = datetime.now()

        data_user = {
            'name': name,
            'surname': surname,
            'adress': adress,
            'phone': phone,
            'email': email,
            'ean': int(ean),
            'created_at': now,
        }

        # dodajmy do bazy
        cursor.execute(add_user, data_user)

        # Make sure data is committed to the database
        self.cnx.commit()

        # rozlacz z bazą
        cursor.close()
        self.cnx.close()

        answer = messagebox.askquestion("Title",
                                        "Do you want print user card?")

        if answer == "yes":
            print(image)
            pdf = FPDF(orientation='P', unit='mm', format='A4')
            pdf.add_page()
            pdf.rect(40, 30, 90, 50)
            pdf.set_font("Arial", size=11)
            pdf.cell(150, 125, name + " " + surname, 0, 0, 'C')
            pdf.image(image, 60, 40, 50)
            my_file = Path('assets/' + name + "_" + surname + ".pdf")
            pdf.output(my_file)
            os.startfile(my_file)

            self.close_windows()

        elif answer == "no":
            self.close_windows()
Exemplo n.º 46
0
    def PrintData(self):
        self.dictionarydata = NewDataBase.LoadData(self.ticket_number.get())
        pdf = FPDF('P','mm','A5')
        pdf.add_page()
        pdf.set_xy(0, 0)
        pdf.set_font('arial', 'B', 10)
        pdf.cell(ln=0, h=5, align='C', w=0, txt="Century Rayon", border=0)
                
        pdf.set_font('arial','',10)
                
                #printing ticket numbr
        pdf.set_xy(20,10)
        pdf.cell(ln=0, h=0, w=0, txt="Tkt No. : ", border=0)
                
        pdf.set_xy(60,10)
        pdf.cell(ln=0, h=0, w=0, txt=self.ticket_number.get(), border=0)
                
                
                # Printing full name in pdf
        pdf.set_xy(20,15)
        pdf.cell(ln=0, h=0, w=0, txt="Name : ", border=0)
                
        pdf.set_xy(60,15)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['full_name'] , border=0)
                
                # printing department in pdf
        pdf.set_xy(20,20)
        pdf.cell(ln=0, h=0, w=0, txt="Department :  ", border=0)
                
        pdf.set_xy(60,20)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['department'] , border=0)
                
                # printing department code
        pdf.set_xy(20,25)
        pdf.cell(ln=0, h=0, w=0, txt="Memo:  ", border=0)
                
        pdf.set_xy(60,25)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['reason_for_memo'] , border=0)
                
        pdf.set_xy(10,30)
        pdf.cell(ln=0, h=0, w=0, txt="Check in Time : ", border=0)
                
        pdf.set_xy(60,30)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['check_in'], border=0)
                
                # printing check in date
        pdf.set_xy(10,35)
        pdf.cell(ln=0, h=0, w=0, txt="Check in Date : ", border=0)
                
        pdf.set_xy(60,35)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['date_in'], border=0)
                
                #printing shift
        pdf.set_xy(20,40)
        pdf.cell(ln=0, h=0, w=0, txt="Shift : ", border=0)
                
        pdf.set_xy(60,40)
        pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['shift'], border=0)

        #pdf.set_font('arial', 'B', 10)
		
        pdf.line(20,55,50,55)
        pdf.set_xy(20,60)
        pdf.cell(ln=0, h=0, w=0, txt="sign of employee", border=0)
        
        pdf.line(60,55,100,55)
        pdf.set_xy(60,60)
        pdf.cell(ln=0, h=0, w=0, txt="Dept Head SIGN", border=0)
        
        pdf.set_xy(20,70)
        pdf.cell(ln=0, h=0, w=0, txt="Timekeeper: ", border=0)
                
        pdf.set_xy(60,70)
        pdf.cell(ln=0, h=0, w=0, txt=self.username.get(), border=0)
                
        try:
            pdf.output('Timekeeper.pdf')
        except Exception:
            tkinter.messagebox.showerror('','Please close the previous pdf file')
        else:
            wb.open('timekeeper.pdf')
def create_pdf(id_telegram, total_grade, grade_limit, recomendation):
    cur_date = datetime.now()

    string = f"Помните, что чем ниже количество набранных баллов" \
             f",тем меньше уровень того или инного растройства.\nВы набрали {total_grade} из {grade_limit} баллов. \n" \
             f"Таким образом, y Вас {recomendation}"

    pdf = FPDF()
    pdf.add_page()
    pdf.add_font('DejaVuSerif', '', 'font/DejaVuSerif.ttf', uni=True)
    pdf.add_font('DejaVuSerif-Bold', '', 'font/DejaVuSerif-Bold.ttf', uni=True)

    pdf.set_font('DejaVuSerif-Bold', '', 16)
    pdf.cell(40, 10, f"{cur_date.strftime('%m/%d/%Y, %H:%M')}",ln=1)

    pdf.set_font("DejaVuSerif", "", 14)
    pdf.multi_cell(180, 8, txt=string)

    pdf.set_font("DejaVuSerif", "", 14)
    pdf.multi_cell(150, 9, f"\nНиже приведены графики, которые помогут "
                           "Вам лучше понять и увидеть результаты текущего и предыдуших тестов")

    pdf.image(f"{SIMPLE_PIE_CHART}_{id_telegram}.png", x=5, y=110, w=180, h=80)

    pdf.set_font("DejaVuSerif", "", 14)
    pdf.set_y(230)
    pdf.multi_cell(170, 9, "Выше изображенный круговой график демонстрирует зависимость полученного балла "
                           "от предельной величины баллов."
                           "Иначе говоря, посмотрев на него Вы поймете: насколько всё хорошо или плохо")

    pdf.add_page()
    pdf.set_font("DejaVuSerif", "", 14)
    pdf.multi_cell(180, 8, txt="Нижеприведенный комплексный график показывает разнообразие тестов, "
                               "которые пользователь проходил за всё время использования программы MeChecker, "
                               "и результатов, которые были получены по каждому из них. "
                               "Он позволит Вам оценить эмоциональное состояние, "
                               "в котором Вы преимущественно находились и находитесь прямо сейчас")

    pdf.image(f"{COMPLEX_PIE_CHART}_{id_telegram}.png", x=5, y=65, w=200, h=100)

    mycursor = mydb.cursor()
    mycursor.execute(f"select categories.id, categories.category from users "
                     "INNER JOIN categories_n_grades ON users.user_cat_grades_id = categories_n_grades.id "
                     "INNER JOIN categories ON categories_n_grades.categories_grades_id = categories.id "
                     f"where users.idTelegram = {id_telegram} "
                     "group by categories.id, categories.category;")
    myresult = mycursor.fetchall()

    categories_object = {}
    for item in myresult:
        categories_object[item[1]] = item[0]

    print(categories_object)

    for property in categories_object:

        obj = get_all_result_by_category(id_telegram, categories_object[property])
        draw_line_graph(id_telegram, obj["results"], obj["dates"], property)

        res_string = "Нижеприведенный график показывает зависимость всех результатов, полученных в ходе прохождения " \
                     f"теста - '{property}', " \
                     "от времени прохождения теста.\nБлагодаря ему легко визуализируется динамика психологического " \
                     "состояния человека. Приглядитесь к нему внимательно, вспомните недавние события, и Вы поймете, " \
                     "что улучшило Ваше психологическое состояние, а что - нет. Придерживайтесь этой тактики, " \
                     "потому что именно она поможет Вам в долгосрочной перспективе!"

        if len(obj["results"]) < 2:
            res_string += "(в данный момент тест пройден один раз, поэтому на графике показана только начальная точка)"

        pdf.add_page()
        pdf.set_font("DejaVuSerif", "", 14)

        pdf.multi_cell(180, 8, txt=res_string)

        pdf.image(f"{property}_{id_telegram}.png", x=5, y=100, w=200, h=150)

    pdf.output(f"results{cur_date.date()}_{id_telegram}.pdf", "F")
    return f"results{cur_date.date()}_{id_telegram}.pdf"
Exemplo n.º 48
0
    def Print(self):
        if(self.ticket_number.get()):
            if(self.dictionarydata['flag']==0):
                DataBase.update(self.ticket_number.get(),self.memo.get(),self.remark.get('1.0','end'),self.date.get(),self.time.get(),self.shift.get(),self.dept_code.get())
                self.dictionarydata = DataBase.load(self.ticket_number.get())
                pdf = FPDF('P','mm','A5')
                pdf.add_page()
                pdf.set_xy(0, 0)
                pdf.set_font('arial', 'B', 10)
                pdf.cell(ln=0, h=5, align='C', w=0, txt="Century Rayon-Time Office", border=0)
                
                pdf.set_font('arial','',10)
                
                #printing ticket numbr
                pdf.set_xy(20,10)
                pdf.cell(ln=0, h=0, w=0, txt="Tkt No. : ", border=0)
                
                pdf.set_xy(60,10)
                pdf.cell(ln=0, h=0, w=0, txt=self.ticket_number.get(), border=0)
                
                
                # Printing full name in pdf
                pdf.set_xy(20,15)
                pdf.cell(ln=0, h=0, w=0, txt="Name : ", border=0)
                
                pdf.set_xy(60,15)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['full_name'] , border=0)
                
                # printing department in pdf
                pdf.set_xy(20,20)
                pdf.cell(ln=0, h=0, w=0, txt="Department :  ", border=0)
                
                pdf.set_xy(60,20)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['department'] , border=0)
                
                # printing department code
                pdf.set_xy(20,25)
                pdf.cell(ln=0, h=0, w=0, txt="Department code:  ", border=0)
                
                pdf.set_xy(60,25)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['department_code'] , border=0)
                
                
                #printing memo in pdf
                pdf.set_xy(20,30)
                pdf.cell(ln=0, h=0, w=0, txt="Memo : ", border=0)
                
                pdf.set_xy(60,30)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['reason_for_memo'] , border=0)
                
                # printing remark in pdf
                pdf.set_xy(20,35)
                pdf.cell(ln=0, h=0, w=0, txt="Remark : ", border=0)
                
                pdf.set_xy(60,35)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['remark'], border=0)
                
                #printing check in time
                pdf.set_xy(10,40)
                pdf.cell(ln=0, h=0, w=0, txt="Check in Time : ", border=0)
                
                pdf.set_xy(60,40)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['check_in'], border=0)
                
                # printing check in date
                pdf.set_xy(10,45)
                pdf.cell(ln=0, h=0, w=0, txt="Check in Date : ", border=0)
                
                pdf.set_xy(60,45)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['date_in'], border=0)
                
                #printing shift
                pdf.set_xy(20,50)
                pdf.cell(ln=0, h=0, w=0, txt="Shift : ", border=0)
                
                pdf.set_xy(60,50)
                pdf.cell(ln=0, h=0, w=0, txt=self.dictionarydata['shift'], border=0)
                
                
                #printing photo
                pdf.set_xy(20,55)
                pdf.cell(ln=0, h=0, w=0, txt="Photo : ", border=0)
                
                try:
                    pdf.image(self.path, 60, 55, 22,22)
                except Exception as e:
                    #print(e)
                    pdf.set_xy(60,55)
                    pdf.cell(ln=0, h=0, w=0, txt="Photo not available", border=0)
                
                pdf.set_xy(20,100)
                pdf.cell(ln=0, h=0, w=0, txt="Timekeeper: ", border=0)
                
                pdf.set_xy(60,100)
                pdf.cell(ln=0, h=0, w=0, txt=self.username.get(), border=0)
                
                pdf.line(20,90,50,90)
                
                pdf.set_xy(20,95)
                pdf.cell(ln=0, h=0, w=0, txt="sign of employee", border=0)
                
                pdf.line(60,90,100,90)
                pdf.set_xy(60,95)
                pdf.cell(ln=0, h=0, w=0, txt="DEPT. HEAD SIGN", border=0)
                
                # sign
                #pdf.set_font('arial', 'B', 10)

                
                try:
                    pdf.output('Timekeeper.pdf')
                except Exception:
                    tkinter.messagebox.showerror('','Please close the previous pdf file')
                else:
                    wb.open('timekeeper.pdf')
                    fp=open("D:/TimeKeeper_stuffs/Personal Database/Logs/"+str(self.td.date())+".txt",'a') 
                    data = ['5199',self.dictionarydata['date_in'],self.dictionarydata['check_in'],self.ticket_number.get(),'I']
                    fp.write('||'.join(data))
                    fp.write("\n")
                    fp.close()
            else:
                tkinter.messagebox.showwarning('','The print has already been generated')
        else:
            tkinter.messagebox.showwarning('','Enter Ticket number')
Exemplo n.º 49
0
    def add_watermark_image_to_pdf(
        self,
        image_path: str,
        output_path: str,
        source_path: str = None,
        coverage: float = 0.2,
    ) -> None:
        """Add image to PDF which can be new or existing PDF.

        If no source path given, assumes a PDF is already opened.

        **Examples**

        **Robot Framework**

        .. code-block:: robotframework

            ***Settings***
            Library    RPA.PDF

            ***Tasks***
            Example Keyword
                Add Watermark Image To PDF
                ...             image_path=approved.png
                ...             source_path=/tmp/sample.pdf
                ...             output_path=output/output.pdf

        **Python**

        .. code-block:: python

            from RPA.PDF import PDF

            pdf = PDF()

            def example_keyword():
                pdf.add_watermark_image_to_pdf(
                    image_path="approved.png"
                    source_path="/tmp/sample.pdf"
                    output_path="output/output.pdf"
                )

        :param image_path: filepath to image file to add into PDF
        :param source: filepath to source, if not given add image to currently
            active PDF
        :param output_path: filepath of target PDF
        :param coverage: how the watermark image should be scaled on page,
         defaults to 0.2
        """
        self.switch_to_pdf(source_path)
        temp_pdf = os.path.join(tempfile.gettempdir(), "temp.pdf")
        writer = PyPDF2.PdfFileWriter()
        pdf = FPDF()
        pdf.add_page()
        reader = self.ctx.active_pdf_document.reader
        mediabox = reader.getPage(0).mediaBox
        im = Image.open(image_path)
        max_width = int(float(mediabox.getWidth()) * coverage)
        max_height = int(float(mediabox.getHeight()) * coverage)
        width, height = self.fit_dimensions_to_box(*im.size, max_width,
                                                   max_height)

        pdf.image(name=image_path, x=40, y=60, w=width, h=height)
        pdf.output(name=temp_pdf)

        img = PyPDF2.PdfFileReader(temp_pdf)
        watermark = img.getPage(0)
        for n in range(reader.getNumPages()):
            page = reader.getPage(n)
            page.mergePage(watermark)
            writer.addPage(page)

        with open(output_path, "wb") as f:
            writer.write(f)
Exemplo n.º 50
0
def write_exam(
    response,
    exam,
    template_questions,
    student_questions,
    name_question,
    sid_question,
    dispatch,
    out=None,
    substitute_in_question_text=False,
):
    pdf = FPDF()
    pdf.add_page()

    pdf.set_font("Courier", size=16)
    pdf.multi_cell(200, 20, txt=exam, align="L")
    pdf.multi_cell(200, 20, txt=response.get(name_question, "NO NAME").encode("latin-1", "replace").decode("latin-1"), align="L")
    pdf.multi_cell(200, 20, txt=response.get(sid_question, "NO SID").encode("latin-1", "replace").decode("latin-1"), align="L")

    pdf.set_font("Courier", size=9)

    if out is None:
        def out(text):
            pdf.multi_cell(
                200, 5, txt=text.encode("latin-1", "replace").decode("latin-1"), align="L"
            )

    student_question_lookup = {q["id"]: q for q in student_questions}

    for question in template_questions:
        pdf.add_page()
        out("\nQUESTION")
        if substitute_in_question_text:
            question_for_text = student_question_lookup.get(question["id"], question)
        else:
            question_for_text = question
        for line in question_for_text["text"].split("\n"):
            out(line)

        out("\nANSWER")

        if question.get("type") in ["multiple_choice", "select_all"]:
            selected_options = response.get(question["id"], [])
            if question.get("type") == "multiple_choice" and not isinstance(
                selected_options, list
            ):
                selected_options = [selected_options]
            available_options = sorted(
                [(i, option["text"]) for i, option in enumerate(question["options"])]
            )
            if question["id"] not in student_question_lookup:
                student_options = sorted(
                    [
                        (option.get("index", i), option["text"])
                        for i, option in enumerate(question["options"])
                    ]
                )
            else:
                student_options = sorted(
                    [
                        (option.get("index", i), option["text"])
                        for i, option in enumerate(
                            student_question_lookup[question["id"]]["options"]
                        )
                    ]
                )

            available_options = [
                (*available_option, option)
                for available_option, (j, option) in zip(
                    available_options, student_options
                )
            ]

            available_options.sort(key=lambda x: x[1])

            for i, template, option in available_options:
                if option in selected_options:
                    template = template
                    out("[X] " + template)
                else:
                    out("[ ] " + template)
        else:
            for line in response.get(question["id"], "").split("\n"):
                out(line)

        out("\nAUTOGRADER")
        if question["id"] in student_question_lookup and question["id"] in response:
            out(grade(student_question_lookup[question["id"]], response, dispatch))
        elif question["id"] not in student_question_lookup:
            out("STUDENT DID NOT RECEIVE QUESTION")
        else:
            out("")

    return pdf
def make_pdf(site, MAP, pdf_name, wc_name, wc_name_mask, name1_2d, name2_2d,
             sim_name, gif_name, img_promo):

    PROLOG = f'''Web Scraping science papers from site:
    {site} on the topic - "Connectome".'''
    EPILOG = "Top Words Cloud"
    EPILOG2 = "t-SNE"
    empty = []

    # Description
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=15, style="B")

    #pdf.set_creator("Bonart")
    pdf.multi_cell(0, 8, txt=PROLOG, align="C")
    pdf.image(
        img_promo,
        x=15,
        y=50,
        w=180,
        link="8.8.8.8",
    )  #
    pdf.add_page()

    # Create pdf-pages with data from dictionary
    for idx, i in enumerate([x for x in MAP.items()]):
        try:
            url = i[0]
            title = encode_decode(i[1][1])
            data = encode_decode(i[1][0][0])
            pdf.ln(10)
            pdf.set_font("Arial", size=12, style="B")
            pdf.multi_cell(0, 8, txt=title, align="L")
            pdf.set_text_color(180, 5, 100)
            pdf.cell(0, 10, txt=url, ln=1, align="L")
            pdf.set_text_color(0, 0, 0)
            pdf.set_font("Arial", size=12)
            pdf.multi_cell(0, 8, txt=data)
        except:
            empty.append(idx)
            continue
    print("Amount of empty data:", len(empty))

    # Epilog
    pdf.add_page()
    pdf.set_font("Arial", size=15, style="B")
    pdf.multi_cell(0, 8, txt=EPILOG, align="C")
    pdf.image(f'{wc_name}.png', x=15, y=30, w=180, link="8.8.8.8")
    pdf.add_page()
    pdf.image(f'{wc_name_mask}.png', x=15, y=10, w=180, link="8.8.8.8")
    pdf.add_page()
    pdf.image(f'{name1_2d}.png', x=15, y=10, w=180, link="8.8.8.8")
    pdf.add_page()
    pdf.image(f'{name2_2d}.png', x=15, y=10, w=180, link="8.8.8.8")
    pdf.add_page()
    pdf.image(f'{sim_name}.png', x=15, y=10, w=180, link="8.8.8.8")
    pdf.add_page()
    pdf.image(gif_name, x=15, y=10, w=180, link="8.8.8.8")
    pdf.output(f"{pdf_name}.pdf")
Exemplo n.º 52
0
def generate_pdf(name, end_date, pr_days):
    #initialise web driver to export fraphs to png
    options = FirefoxOptions()
    web_driver = Firefox(
        executable_path=
        'C:/Users/ABachleda-Baca/AppData/Local/salabs_/WebDriverManager/gecko/v0.27.0/geckodriver-v0.27.0-win64/geckodriver.exe',
        options=options)
    #Define period to be considered using time_period function
    week_times = time_period_extract(days=pr_days, end_date=end_date)

    #Import data from json files in known directory using json_import function and save all recorded alerts#in events array
    path = 'output/Building1/'
    events = import_events_from_json(week_times, path)
    #transform events from json file to list of dictionaries
    total_list = []
    if events:
        total_list = extract_alerts_from_events(events)

    #extract the timestamps for daily energy usage
    if total_list:
        timestamp_daily_energy_gen = []
        energy_daily_modelled_dc = []
        energy_daily_gen_ac = []
    for i in total_list[-1]['daily_energy']:
        i = total_list[-1]['daily_energy'].index(i)
        timestamp_daily_energy_gen.append(
            (total_list[-1]['daily_energy'][i][0])[:10])
        energy_daily_modelled_dc.append(total_list[-1]['daily_energy'][i][1])
        energy_daily_gen_ac.append(total_list[-1]['daily_energy'][i][2])

    #Draw graph Daily energy generation
    #bokeh plot generation mix and DH performance indicator

    #draw a graph
    if not os.path.exists('output/' + name + '/charts/DCvsAC'):
        os.makedirs('output/' + name + '/charts/DCvsAC', mode=0o777)
    output_file('output/' + name + '/charts/DCvsAC/energy_output' +
                end_date[:10] + '.html')
    data = {
        'timestamps': timestamp_daily_energy_gen,
        'energy_DC_modelled': energy_daily_modelled_dc,
        'energy_ac_generated': energy_daily_gen_ac
    }

    source = ColumnDataSource(data=data)
    p = figure(x_range=timestamp_daily_energy_gen,
               plot_width=700,
               plot_height=600,
               title='Daily Energy Output',
               toolbar_location=None,
               tools="")
    p.title.text_font_size = '15pt'
    p.xaxis.axis_label_text_font_size = "15pt"
    p.yaxis.axis_label_text_font_size = "15pt"
    p.yaxis.major_label_text_font_size = '15pt'
    p.xaxis.major_label_text_font_size = '12pt'
    p.yaxis.axis_label = 'Energy output [kWh]'
    a1 = p.vbar(x=dodge('timestamps', 0.0, range=p.x_range),
                top='energy_DC_modelled',
                width=0.25,
                source=source,
                color='#718dbf')
    a2 = p.vbar(x=dodge('timestamps', 0.25, range=p.x_range),
                top='energy_ac_generated',
                width=0.25,
                source=source,
                color='#00008B')
    p.xgrid.grid_line_color = None
    legend = Legend(items=[("Modelled Energy DC ", [a1]),
                           ("Measured Energy AC", [a2])],
                    location=(0, -5))

    p.add_layout(legend, 'below')
    p.y_range.start = 0
    save(p)
    export_png(p,
               filename='output/' + name + '/charts/DCvsAC/energy_output' +
               end_date[:10] + '.png',
               webdriver=web_driver)

    #Extract PR for last 3 month
    system_pr = []
    timestamp_pr = []
    for i in total_list:
        i = total_list.index(i)
        system_pr.append(total_list[i]['system_pr'])
        timestamp_pr.append(total_list[i]['timestamp'][:10])
    #Draw a graph
    if system_pr:
        #create directory for graph
        if not os.path.exists('output/' + name + '/charts/PR'):
            os.makedirs('output/' + name + '/charts/PR', mode=0o777)
        #create directory for report
        if not os.path.exists('output/' + name + '/charts/reports'):
            os.makedirs('output/' + name + '/charts/reports', mode=0o777)
        output_file('output/' + name + '/charts/PR/pr_' + end_date[:10] +
                    '.html')
        #draw graph to compare real energy output and predicted one
        p = figure(plot_height=600,
                   plot_width=1000,
                   title="PR for past 3 months measured in weekly basis",
                   x_range=timestamp_pr,
                   y_range=(min(system_pr) - 0.4, max(system_pr) + 0.4))
        p.title.text_font_size = '15pt'
        p.xaxis.axis_label_text_font_size = "15pt"
        p.yaxis.axis_label_text_font_size = "15pt"
        p.yaxis.major_label_text_font_size = '15pt'
        p.xaxis.major_label_text_font_size = '15pt'
        p.xaxis.major_label_orientation = math.pi / 2
        p.yaxis.axis_label = 'performance in decimals'
        p.line(timestamp_pr,
               system_pr,
               line_width=2,
               color='blue',
               legend_label='PR')
        p.circle(timestamp_pr, system_pr, size=10, color='red', alpha=0.5)
        save(p)
        export_png(p,
                   filename='output/' + name + '/charts/PR/pr_' +
                   end_date[:10] + '.png',
                   webdriver=web_driver)

        #Generation of PDF Report
        pdf = FPDF()
        pdf.add_page()
        pdf.set_xy(0, 0)
        pdf.set_font('arial', 'B', 12)
        pdf.cell(60)
        pdf.cell(75, 10, "Performance of PV System in " + name, 0, 2, 'C')
        pdf.set_font('arial', 'B', 10)
        #extract begining of the week
        #change to string

        start_day = timestamp_pr[-2]
        stop_day = timestamp_pr[-1]
        pdf.cell(
            75, 10, "Report generated on: " +
            datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 0, 2, 'C')
        pdf.cell(75, 10, "Week: From " + start_day + ' to ' + stop_day, 0, 2,
                 'C')
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.cell(60)
        pdf.set_font('arial', '', 10)
        pdf.cell(-60)
        pdf.cell(
            90, 10,
            'Total calculated nominal energy output from PV array(DC Energy): '
            + str(total_list[-1]['total_energy_modelled_dc']) + ' kWh', 0, 2,
            'L')
        pdf.cell(
            90, 10, 'Total energy generated from PV system (AC Energy): ' +
            str(total_list[-1]['total_energy_generated_ac']) + ' kWh', 0, 2,
            'L')
        pdf.cell(90, 10, 'Performance ratio of the PV System , calculated as:',
                 0, 2, 'L')
        pdf.cell(
            90, 10,
            'Total energy generated from PV system/Total calculated nominal energy output from PV array: PR= '
            + str(total_list[-1]['system_pr']), 0, 2, 'L')
        pdf.cell(
            90, 10, 'Total calculated losses of the system  : ' +
            str(round(((1 - total_list[-1]['system_pr']) * 100), 2)) + '%', 0,
            2, 'L')
        pdf.cell(10)
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.image('output/' + name + '/charts/DCvsAC/energy_output' +
                  end_date[:10] + '.png',
                  x=None,
                  y=None,
                  w=150,
                  h=120,
                  type='',
                  link='')
        pdf.cell(ln=1, h=5.0, w=0, border=0)
        pdf.image('output/' + name + '/charts/PR/pr_' + end_date[:10] + '.png',
                  x=None,
                  y=None,
                  w=170,
                  h=100,
                  type='',
                  link='')
        pdf.set_font('arial', 'B', 10)
        pdf_report_location = 'output/' + name + '/charts/reports/Pv_performance' + end_date[:
                                                                                             10] + '.pdf'
        pdf.output(pdf_report_location, 'F')

        return pdf_report_location
Exemplo n.º 53
0
def fetch_images_and_return_response(deck_code: str):
    code = deck_code
    file_name = deck_code

    # html = requests.get("https://www.pokemon-card.com/deck/deck.html?deckID=11F1Fw-VNG8m4-fk1bVF").content
    html = requests.get("https://www.pokemon-card.com/deck/deck.html?deckID=" + code).content

    soup = BeautifulSoup(html, "html.parser")

    card_data_script_text = soup.find_all("script")[-1].contents[0]

    # deck_pke_list の例: [["33525", "3"], ["33525", "3"]]
    deck_pke_list = [elem.split("_")[:2] for elem in soup.find(id="deck_pke")["value"].split("-")]
    deck_gds_list = [elem.split("_")[:2] for elem in soup.find(id="deck_gds")["value"].split("-")] \
        if soup.find(id="deck_gds")["value"] != "" else []
    deck_sup_list = [elem.split("_")[:2] for elem in soup.find(id="deck_sup")["value"].split("-")] \
        if soup.find(id="deck_sup")["value"] != "" else []
    deck_sta_list = [elem.split("_")[:2] for elem in soup.find(id="deck_sta")["value"].split("-")] \
        if soup.find(id="deck_sta")["value"] != "" else []
    deck_ene_list = [elem.split("_")[:2] for elem in soup.find(id="deck_ene")["value"].split("-")] \
        if soup.find(id="deck_ene")["value"] != "" else []
    # deck_ajs_list = [elem.split("_")[:2] for elem in soup.find(id="deck_ajs")["value"].split("-")]\
    #     if soup.find(id="deck_ajs")["value"] != "" else []

    deck_list = deck_pke_list + deck_gds_list + deck_sup_list + deck_sta_list + deck_ene_list  # + deck_ajs_list
    cards_to_print_count = 0

    card_url_list = []

    dl_counter = 0

    for elm in deck_list:
        dl_counter += 1
        pattern = re.compile(r"(/assets/images/card_images/([a-zA-Z]+)/[^\n]*/0+%s_[^\n]+\.jpg)" % elm[0],
                             re.MULTILINE | re.DOTALL)
        match = pattern.search(card_data_script_text)

        if match:
            url = "https://www.pokemon-card.com" + match.group(1)
            elm.append(url)
        #    print(elm)
        else:
            # たまに画像がなくて裏面の画像なことがあるので、その対応
            url = "https://www.pokemon-card.com/assets/images/noimage/poke_ura.jpg"
            elm.append(url)

        try:
            for i in range(int(elm[1])):
                cards_to_print_count += 1
                card_url_list.append(elm[2])
        except ValueError:
            return HttpResponse(
                "デッキコードが正しくないか、ポケモンカード公式のサーバが応答していません。",
                content_type="text/plain; charset=utf-8"
            )

    # キャンバスと出力ファイルの初期化
    pdf = FPDF(orientation='P', unit='mm', format="A4")

    pdf.set_author("PTCG2Win")
    pdf.set_title(deck_code)
    pdf.set_subject("PDF to print")

    card_url_or_image_list = []

    def split_images_and_append_to_list(input_image: Image.Image, x_pieces, y_pieces, output_list):
        imgwidth, imgheight = input_image.size
        height = imgheight // y_pieces
        width = imgwidth // x_pieces
        for j in range(y_pieces):
            for k in range(x_pieces):
                box = (k * width, j * height, (k + 1) * width, (j + 1) * height)
                part = input_image.crop(box)
                output_list.append(part)

    def trim(input_image: Image.Image) -> Image.Image:
        bg = Image.new(input_image.mode, input_image.size, input_image.getpixel((0, 0)))
        diff = ImageChops.difference(input_image, bg)
        diff = ImageChops.add(diff, diff, 2.0, -100)
        bbox = diff.getbbox()
        if bbox:
            return input_image.crop(bbox)

    v_union_filename_pattern: re.Pattern = re.compile(r"[A-Z]VUNION\.jpg$")
    reduced_card_url_list = []
    cards_count = len(card_url_list)
    for i in range(cards_count):
        card_url = card_url_list[i]
        if re.search(v_union_filename_pattern, card_url):
            for j in range(card_url_list.count(card_url) // 4):
                reduced_card_url_list.append(card_url)
            card_url_list = ["" if url == card_url else url for url in card_url_list]
        else:
            reduced_card_url_list.append(card_url)
    filtered_card_url_list = [card_url for card_url in reduced_card_url_list if card_url != ""]

    for card_url in filtered_card_url_list:
        if "/card_images/legend/" in card_url:
            rsp = requests.get(card_url, stream=True)
            rsp.raw.decode_content = True
            img_object = Image.open(rsp.raw)
            img_object = img_object.rotate(90, expand=True)
            card_url_or_image_list.append(img_object)
        elif re.search(v_union_filename_pattern, card_url):
            rsp = requests.get(card_url, stream=True)
            rsp.raw.decode_content = True
            img_object = trim(Image.open(rsp.raw))
            split_images_and_append_to_list(img_object, 2, 2, card_url_or_image_list)
        else:
            card_url_or_image_list.append(card_url)

    # ポケモンカードのサイズは63x88なので、紙を縦置きにした場合、3枚x3枚(189x264)入る。
    for i in range(len(card_url_or_image_list)):
        card_url_or_image = card_url_or_image_list[i]
        # 9枚ごとに改ページ
        if i % 9 == 0:
            pdf.add_page("P")
        #        print("Page", i // 9 + 1)
        # 3枚ごとに改行
        x_pos = (11 + 63 * (i % 3))
        y_pos = (15 + 88 * ((i % 9) // 3))

        pdf.image(
            card_url_or_image,
            x_pos,
            y_pos,
            w=63,
            h=88,
        )

    buffer = BytesIO()

    output = pdf.output()
    buffer.write(output)
    buffer.seek(0)
    # httpレスポンスの作成
    return FileResponse(buffer, filename=f"{deck_code}.pdf", as_attachment=True, content_type='application/pdf')
Exemplo n.º 54
0
class FacturaPdf:

    pdf = FPDF()
    pagina = 0
    yLinea = 0
    saltoPagina = 225
    lineas = []
    jsonDecoded = ""
    textoResiduos = "El responsable de la entrega del residuo o envase usado, para su correcta gestión ambiental es el poseedor final (R.D. 782/98 art.18)"
    textoRegistro = "Inscrita en el Reg.Mercantil de Valencia, Tomo 6.630, Libro 3.934, Folio 205, Sección 8º, Hoja V-71.929, Inscr. 1ª."

    idioma = ""
    textosIdioma = {
        "INGLES": {
            "albaran": "Dlv. Note:",
            "fecha": "Date:",
            "Pedido": "Order Nr.:",
            "bultos": "Total Cases:",
            "pesoBruto": "Gross Weight:",
            "pesoNeto": "Net Weight:",
            "cliente": "CUSTOMER NUMBER",
            "agente": "BROKER",
            "numeroFactura": "INVOICE NUMBER",
            "codigo": "ITEM Nr.",
            "descripcion": "PRODUCT NAME",
            "cantidad": "CASES",
            "precio": "PRICE",
            "importe": "AMOUNT",
            "importeBruto": "GROSS AMOUNT",
            "descuento": "DISCOUNT",
            "descuentoPP": "%ADV PAYMENT",
            "condicionesPago": "PAYMENT TERMS:",
            "totalFactura": "TOTAL INVOICE"
        }
    }

    def __init__(self):

        self.pdf = FPDF()
        self.pdf.set_font("Arial", size=9)

    def __del__(self):
        #del(FPDF)
        print('Destructor called')

    def leerCaracter(self, nombreFichero="factura.json", desde=1, hasta=1):
        with open(nombreFichero) as fileobj:
            i = 1
            for line in fileobj:
                for ch in line:
                    if i >= desde and i <= hasta:
                        print(ch)
                    i += 1

    def leerJSON(self, nombreFichero="E_1270.json"):

        os.chdir(r"C:\ServidorWeb\server\kingCRM\facturas")

        script_dir = os.path.dirname(
            __file__)  #<-- absolute dir the script is in
        rel_path = "facturas/" + nombreFichero
        abs_file_path = os.path.join(script_dir, rel_path)

        f = open(abs_file_path, "r")

        #f = codecs.open(abs_file_path, "r", encoding="cp500")
        content = f.read()

        jsonDecoded = json.loads(content)
        #print(jsonDecoded)

        f.close()
        self.jsonDecoded = jsonDecoded

        lineas = jsonDecoded["lineas"]
        self.lineas = lineas

        if "idioma" in jsonDecoded:
            self.idioma = jsonDecoded["idioma"]

    def anyadirPagina(self):

        self.pagina += 1
        self.pdf.add_page()

        #self.pdf.image("preformatoKr.png", 1, 1)

        self.pdf.image("leon_agua.png", 40, 100, 150, 150)
        self.pdf.image("LOGO_KR.jpg", 10, 1, 50, 50)

        self.pdf.rect(5, 60, 200, 15)
        self.textoImprimir(7, 64, self.idioma, "cliente", "CODIGO CLIENTE")

        self.pdf.line(40, 60, 40, 75)
        self.textoImprimir(42, 64, self.idioma, "agente", "AGENTE")

        self.pdf.line(108, 60, 108, 75)
        self.textoImprimir(110, 64, self.idioma, "fecha", "FECHA")

        self.pdf.line(168, 60, 168, 75)

        self.textoImprimir(175, 64, self.idioma, "numeroFactura", "Nº FACTURA")

        self.pdf.rect(5, 80, 200, 150)

        self.pdf.line(5, 86, 205, 86)
        self.textoImprimir(7, 84, self.idioma, "codigo", "CODIGO")
        self.pdf.line(25, 80, 25, 230)
        self.textoImprimir(42, 84, self.idioma, "descripcion", "DESCRIPCION")
        self.pdf.line(85, 80, 85, 230)
        self.textoImprimir(90, 84, self.idioma, "cantidad", "CANTIDAD")
        self.pdf.line(108, 80, 108, 230)
        self.pdf.text(110, 84, "UxCJ")
        self.pdf.line(118, 80, 118, 230)
        self.pdf.text(120, 84, "T.UDS")
        self.pdf.line(135, 80, 135, 230)
        self.textoImprimir(140, 84, self.idioma, "precio", "PRECIO UNIDAD")
        self.pdf.line(168, 80, 168, 230)
        self.pdf.text(170, 84, "% DTO")
        self.pdf.line(182, 80, 182, 230)

        self.textoImprimir(185, 84, self.idioma, "importe", "IMPORTE")

        self.pdf.rect(5, 235, 200, 30)

        self.yLinea = 239
        self.pdf.set_font("Arial", size=8)
        self.textoImprimir(10, self.yLinea, self.idioma, "importeBruto",
                           "IMPORTE BRUTO")
        self.textoImprimir(40, self.yLinea, self.idioma, "descuento",
                           "DESCUENTO")
        self.textoImprimir(70, self.yLinea, self.idioma, "descuentoPP",
                           "DESCUENTO P.P")

        if self.idioma == "":
            self.pdf.text(110, self.yLinea, "BASE IMPONBLE")
            self.pdf.text(150, self.yLinea, "IVA")
            self.pdf.text(170, self.yLinea, "REC.EQUIVALENCIA")

        self.pdf.set_font("Arial", size=6)
        self.textoImprimir(10, 269, self.idioma, "condicionesPago",
                           "CONDICIONES DE PAGO:")
        self.pdf.rect(5, 270, 140, 20)

        self.pdf.rect(155, 270, 50, 20)
        self.pdf.set_font("Arial", size=10)
        self.textoImprimir(160, 275, self.idioma, "totalFactura",
                           "TOTAL FACTURA")

        self.pdf.set_font("Arial", size=7)
        self.pdf.text(10, 293, self.textoResiduos)
        self.pdf.text(10, 296, self.textoRegistro)

        self.pdf.set_font("Arial", size=10)

    def imprimirCabecera(self):

        self.pdf.set_font("Arial", size=10)

        self.pdf.line(105, 15, 110, 15)
        self.pdf.line(105, 15, 105, 20)

        self.pdf.line(200, 15, 205, 15)
        self.pdf.line(205, 15, 205, 20)

        self.yLinea = 20
        self.pdf.text(110, self.yLinea, self.jsonDecoded["nombre"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["direccion1"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["direccion2"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["direccion3"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["direccion4"])
        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["Nif"])
        if self.jsonDecoded["coa"].strip() == "A":
            self.pdf.text(70, self.yLinea, "** abono **")

        self.yLinea += 6

        self.pdf.line(200, self.yLinea, 205, self.yLinea)
        self.pdf.line(205, self.yLinea - 5, 205, self.yLinea)

        self.pdf.line(105, self.yLinea - 5, 105, self.yLinea)
        self.pdf.line(105, self.yLinea, 110, self.yLinea)

        self.yLinea = 70
        self.pdf.text(10, self.yLinea, self.jsonDecoded["codigoCliente"])
        self.pdf.text(42, self.yLinea, self.jsonDecoded["agente"])
        self.pdf.text(115, self.yLinea, self.jsonDecoded["fecha"])
        self.pdf.text(175, self.yLinea, self.jsonDecoded["factura"])

        print(self.jsonDecoded["codigoCliente"])

    def imprimirPie(self):

        self.yLinea = 246
        self.pdf.set_font("Arial", size=10)
        self.pdf.text(10, self.yLinea, self.jsonDecoded["bruto"])
        self.pdf.text(35, self.yLinea, self.jsonDecoded["descuento"])
        self.pdf.text(50, self.yLinea, self.jsonDecoded["ImporteDtc1"])
        self.pdf.text(70, self.yLinea, self.jsonDecoded["dtoPronto"])
        self.pdf.text(90, self.yLinea, self.jsonDecoded["ImporteDtpp"])

        self.pdf.text(110, self.yLinea, self.jsonDecoded["base1"])
        self.pdf.text(130, self.yLinea, self.jsonDecoded["porcentajeIva1"])
        self.pdf.text(155, self.yLinea, self.jsonDecoded["cuotaIva1"])
        self.pdf.text(170, self.yLinea, self.jsonDecoded["porcentajeRecargo1"])
        self.pdf.text(190, self.yLinea, self.jsonDecoded["cuotaRecargo1"])

        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["base2"])
        self.pdf.text(130, self.yLinea, self.jsonDecoded["porcentajeIva2"])
        self.pdf.text(150, self.yLinea, self.jsonDecoded["cuotaIva2"])
        self.pdf.text(170, self.yLinea, self.jsonDecoded["porcentajeRecargo2"])
        self.pdf.text(190, self.yLinea, self.jsonDecoded["cuotaRecargo2"])

        self.yLinea += 6
        self.pdf.text(110, self.yLinea, self.jsonDecoded["base3"])
        self.pdf.text(130, self.yLinea, self.jsonDecoded["porcentajeIva3"])
        self.pdf.text(150, self.yLinea, self.jsonDecoded["cuotaIva3"])
        self.pdf.text(170, self.yLinea, self.jsonDecoded["porcentajeRecargo3"])
        self.pdf.text(190, self.yLinea, self.jsonDecoded["cuotaRecargo3"])

        self.yLinea = 276

        if "formaPago" in self.jsonDecoded.keys():

            self.pdf.text(40, self.yLinea, self.jsonDecoded["formaPago"])
            self.yLinea += 6

        if "importePlazo1" in self.jsonDecoded.keys():

            if self.jsonDecoded["importePlazo1"].strip() != "":
                self.pdf.text(10, self.yLinea, self.jsonDecoded["fechaPlazo1"])
                self.pdf.text(35, self.yLinea,
                              self.jsonDecoded["importePlazo1"])

            if self.jsonDecoded["importePlazo2"].strip() != "":
                self.pdf.text(65, self.yLinea, self.jsonDecoded["fechaPlazo2"])
                self.pdf.text(85, self.yLinea,
                              self.jsonDecoded["importePlazo2"])

            if self.jsonDecoded["importePlazo3"].strip() != "":
                self.pdf.text(105, self.yLinea,
                              self.jsonDecoded["fechaPlazo3"])
                self.pdf.text(125, self.yLinea,
                              self.jsonDecoded["importePlazo3"])

        if "apagar" in self.jsonDecoded.keys():

            self.pdf.text(175, self.yLinea, self.jsonDecoded["apagar"])

    def textoImprimir(self, x=0, y=0, idioma="", clave="", textoInicial=""):
        texto = textoInicial
        if idioma in self.textosIdioma:
            if clave in self.textosIdioma[idioma]:

                texto = self.textosIdioma[idioma][clave]
        self.pdf.text(x, y, texto)

    def imprimirLineas(self):
        self.yLinea = 90
        self.pdf.set_font("Arial", size=10)

        if self.pagina == 1:
            primeraLineaImpresa = False
            if self.jsonDecoded["albaran"].strip() != "":
                if self.idioma != "":
                    self.pdf.text(32, self.yLinea,
                                  "Dlv. Note:: " + self.jsonDecoded["albaran"])
                else:
                    self.pdf.text(32, self.yLinea,
                                  "Albaran: " + self.jsonDecoded["albaran"])

                primeraLineaImpresa = True
                if self.idioma != "":
                    self.pdf.text(62, self.yLinea,
                                  "Date: " + self.jsonDecoded["fechaAlbaran"])
                else:
                    self.pdf.text(62, self.yLinea,
                                  "Fecha: " + self.jsonDecoded["fechaAlbaran"])

                primeraLineaImpresa = True
            if self.jsonDecoded["pedido"].strip() != "":
                if self.idioma != "":
                    self.pdf.text(102, self.yLinea,
                                  "Order Nr.: " + self.jsonDecoded["pedido"])
                else:
                    self.pdf.text(102, self.yLinea,
                                  "Pedido: " + self.jsonDecoded["pedido"])

                primeraLineaImpresa = True

            if primeraLineaImpresa:
                self.yLinea += 5
        for linea in self.lineas:

            self.pdf.set_font("Arial", size=6)
            self.pdf.text(7, self.yLinea, linea["articulo"])
            self.pdf.set_font("Arial", size=8)
            self.pdf.text(32, self.yLinea, linea["descripcion"])
            self.pdf.text(98, self.yLinea,
                          linea["cantidad"].lstrip(' 0').rjust(7))
            self.pdf.text(110, self.yLinea,
                          linea["factor"].lstrip(' 0').rjust(7))
            self.pdf.text(120, self.yLinea, linea["unidades"])
            self.pdf.text(140, self.yLinea, linea["precio"])
            self.pdf.text(170, self.yLinea, linea["descuento"])
            self.pdf.text(185, self.yLinea, linea["importe"])

            self.yLinea += 5
            self.saltar()

    def imprimirPesos(self):

        self.pdf.set_font("Arial", size=8)

        observaciones = []
        if 'observaciones' in self.jsonDecoded.keys():
            observaciones = self.jsonDecoded["observaciones"]
        for observacion in observaciones:
            if observacion.strip() != "":
                self.yLinea = self.yLinea + 5
                self.saltar()
                self.pdf.text(32, self.yLinea, observacion)

        self.yLinea = self.yLinea + 5
        self.saltar()

        if "bultos" in self.jsonDecoded.keys():
            self.textoImprimir(7, self.yLinea, self.idioma, "bultos",
                               "Bultos: ")
            self.pdf.text(32, self.yLinea, self.jsonDecoded["bultos"])

        if "pesoBruto" in self.jsonDecoded.keys():
            self.textoImprimir(58, self.yLinea, self.idioma, "pesoBruto",
                               "Peso Bruto: ")
            self.pdf.text(80, self.yLinea, self.jsonDecoded["pesoBruto"])

        if "pesoNeto" in self.jsonDecoded.keys():
            self.textoImprimir(120, self.yLinea, self.idioma, "pesoNeto",
                               "Peso Neto: ")
            self.pdf.text(140, self.yLinea, self.jsonDecoded["pesoNeto"])

            print(self.yLinea)

    def saltar(self):
        if self.yLinea > self.saltoPagina:
            self.anyadirPagina()
            self.imprimirCabecera()
            self.yLinea = 90

    def finalizarDocumento(self, documento="factura.pdf"):

        script_dir = os.path.dirname(
            __file__)  #<-- absolute dir the script is in
        rel_path = "facturas\\" + documento
        abs_file_path = os.path.join(script_dir, rel_path)

        print("Fichero a cerrar: " + abs_file_path)
        self.pdf.output(abs_file_path)
Exemplo n.º 55
0
class Kut2FPDF(object):
    """
    Convert kuts to pyFPDF.
    """

    _document: "FPDF"

    _xml: Element
    _xml_data: Element
    _page_orientation: str
    _page_size: List[int]
    _bottom_margin: int
    _left_margin: int
    _right_margin: int
    _top_margin: int
    _page_top: Dict[int, int]
    _data_row: Element
    _parser_tools: "kparsertools.KParserTools"
    _avalible_fonts: List[str]
    _unavalible_fonts: List[str]
    design_mode: bool
    _actual_data_line: Optional[Element]
    _no_print_footer: bool
    _actual_section_size: int
    increase_section_size: int
    last_detail: bool
    actual_data_level: int
    last_data_processed: Element
    prev_level: int
    draws_at_header: Dict[str, str]
    detailn: Dict[str, int]
    name_: str
    _actual_append_page_no: int
    reset_page_count: bool

    def __init__(self) -> None:
        """Constructor."""

        check_dependencies({"fpdf": "fpdf2"})

        self._parser_tools = kparsertools.KParserTools()
        self._avalible_fonts = []
        self._page_top: Dict[int, int] = {}
        self._unavalible_fonts = []
        self.design_mode = config.value("ebcomportamiento/kugar_debug_mode",
                                        False)
        self._actual_data_line = None
        self._no_print_footer = False
        self.increase_section_size = 0
        self.actual_data_level = 0
        self.prev_level = -1
        self.draws_at_header = {}
        self.detailn = {}
        self.name_ = ""
        self._actual_append_page_no = -1
        self.reset_page_count = False
        self.new_page = False

    def parse(self,
              name: str,
              kut: str,
              data: str,
              report: "FPDF" = None,
              flags: List[int] = []) -> Optional[str]:
        """
        Parse string containing ".kut" file into a pdf and return its file path.

        @param name. Filename path for ".kut".
        @param kut. String with ".kut" file contents.
        @param data. String with data to be used in the report.
        @return Path to PDF file.
        """
        try:
            self._xml = self._parser_tools.loadKut(kut).getroot()
        except Exception:
            LOGGER.exception("KUT2FPDF: Problema al procesar %s.kut", name)
            return None
        try:
            self._xml_data = load2xml(data).getroot()
        except Exception:
            LOGGER.exception("KUT2FPDF: Problema al procesar xml_data")
            return None

        application.PROJECT.message_manager().send(
            "progress_dialog_manager", "create",
            ["Pineboo", len(self._xml_data), "kugar"])
        application.PROJECT.message_manager().send(
            "progress_dialog_manager", "setLabelText",
            ["Creando informe ...", "kugar"])

        self.name_ = name
        self.setPageFormat(self._xml)
        # self._page_orientation =
        # self._page_size =
        if report is None:
            from fpdf import FPDF  # type: ignore

            self._actual_append_page_no = 0
            self._document = FPDF(self._page_orientation, "pt",
                                  self._page_size)
            for font in self._document.core_fonts:
                LOGGER.debug("KUT2FPDF :: Adding font %s", font)
                self._avalible_fonts.append(font)
        else:
            self._document = report
        # Seteamos rutas a carpetas con tipos de letra ...

        if not hasattr(self._document, "set_stretching"):
            raise Exception("incorrect pyfpdf versión , you need <= 1.7.3")

        # Cargamos las fuentes disponibles
        next_page_break = (flags[2] == 1) if len(flags) == 3 else True
        page_append = (flags[1] == 1) if len(flags) > 1 else False
        page_display = (flags[0] == 1) if len(flags) > 0 else False

        if page_append:
            self.prev_level = -1
            self.last_detail = False

        page_break = False
        if self.new_page:
            page_break = True
            self.new_page = False

        if self.reset_page_count:
            self.reset_page_no()
            self.reset_page_count = False

        if self.design_mode:
            print("Append", page_append)
            print("Display", page_display)
            print("Page break", next_page_break)

        if next_page_break:
            self.reset_page_count = True

        if page_display:
            self.new_page = True

        self.processDetails(not page_break)

        # FIXME:Alguno valores no se encuentran
        for pages in self._document.pages.keys():
            page_content = self._document.pages[pages]["content"]
            for header in self.draws_at_header.keys():
                page_content = page_content.replace(
                    header, str(self.draws_at_header[header]))

            self._document.pages[pages]["content"] = page_content

        # print(self.draws_at_header.keys())
        self._document.set_title(self.name_)
        self._document.set_author("Pineboo - kut2fpdf plugin")

        return self._document

    def get_file_name(self) -> Optional[str]:
        """Retrieve file name where PDF should be saved."""
        import os

        pdf_name = application.PROJECT.tmpdir
        pdf_name += "/%s_%s.pdf" % (
            self.name_, datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
        if os.path.exists(pdf_name):
            os.remove(pdf_name)
        if self._document is not None:
            self._document.output(pdf_name, "F")
            return pdf_name
        else:
            return None

    def topSection(self) -> int:
        """
        Retrieve top section margin for current page to calculate object positions.

        @return Number with ceiling for current page.
        """
        return self._page_top[int(self._document.page_no())]

    def setTopSection(self, value: int) -> None:
        """
        Update top section for current page.

        Usually updated when processing a section.
        @param value. Number specifying new ceiling.
        """
        self._actual_section_size = value - self.topSection()
        self._page_top[int(self._document.page_no())] = value

    def newPage(self, data_level: int, add_on_header: bool = True) -> None:
        """
        Add a new page to the document.
        """
        self._document.add_page(self._page_orientation)
        self._page_top[int(self._document.page_no())] = self._top_margin
        self._document.set_margins(
            self._left_margin, self._top_margin,
            self._right_margin)  # Lo dejo pero no se nota nada
        self._no_print_footer = False
        if self.design_mode:
            self.draw_margins()

        self._actual_section_size = 0
        self._actual_append_page_no += 1
        if self.design_mode:
            print("Nueva página", self.number_pages())

        # l_ini = data_level
        # l_end = self.prev_level

        # if l_ini == l_end:
        #    l_end = l_end + 1

        # if l_ini <= l_end:
        #    for l in range(l_ini , l_end):
        #        print(l)
        #        self.processSection("AddOnHeader", str(l))
        pg_headers = self._xml.findall("PageHeader")

        for page_header in pg_headers:
            if self.number_pages() == 1 or page_header.get(
                    "PrintFrequency") == "1":
                ph_level = (page_header.get("Level")
                            if page_header.get("Level") is not None else None)
                self.processSection("PageHeader", int(ph_level or "0"))
                break

        if add_on_header and not self.number_pages() == 1:
            for level in range(data_level + 1):
                self.processSection("AddOnHeader", int(level))

        # Por ahora se omite detail header

    def processDetails(self, keep_page: Optional[bool] = None) -> None:
        """
        Process detail secions with their matching detailHeader and detailFooter.
        """
        # Procesamos la cabecera si procede ..

        top_level = 0
        level = 0
        first_page_created = (keep_page if keep_page is not None
                              and self._document.page_no() > 0 else False)

        rows_array = self._xml_data.findall("Row")
        i = 0

        for data in rows_array:
            self._actual_data_line = data
            level_str: Optional[str] = data.get("level")
            if level_str is None:
                level_str = "0"
            level = int(level_str)
            if level > top_level:
                top_level = level

            if not first_page_created:
                self.newPage(level)
                first_page_created = True

            if rows_array[len(rows_array) - 1] is data:
                self.last_detail = True

            if level < self.prev_level:
                for lev in range(level + 1, self.prev_level + 1):
                    self.processData("DetailFooter", self.last_data_processed,
                                     lev)

            if not str(level) in self.detailn.keys():
                self.detailn[str(level)] = 0
            else:
                self.detailn[str(level)] += 1

            if level > self.prev_level:
                self.processData("DetailHeader", data, level)

            self.processData("Detail", data, level)

            self.last_data_processed = data

            self.prev_level = level

            application.PROJECT.message_manager().send(
                "progress_dialog_manager", "setProgress", [i, "kugar"])
            i += 1

        if not self._no_print_footer and hasattr(self, "last_data_processed"):
            for lev in reversed(range(top_level + 1)):
                self.processData("DetailFooter", self.last_data_processed, lev)

        application.PROJECT.message_manager().send("progress_dialog_manager",
                                                   "destroy", ["kugar"])

    def processData(self, section_name: str, data: Element,
                    data_level: int) -> None:
        """
        Check if detailHeader + detail + detailFooter do fit in the remaining page and create a new page if not.

        @param section_name. Section name to check
        @param data. Data to check
        @param data_level. Section level
        """
        self.actual_data_level = data_level
        list_sections = self._xml.findall(section_name)
        # data_size = len(listDF)

        for section in list_sections:
            draw_if = section.get("DrawIf")
            show = True
            if draw_if:
                show = bool(data.get(draw_if))

            if section.get("Level") == str(data_level) and show not in (
                    "", "False", "None"):

                if section_name in ("DetailHeader", "Detail"):
                    height_calculated = (
                        self._parser_tools.getHeight(section) +
                        self.topSection() + self.increase_section_size)

                    if section_name == "DetailHeader":
                        for detail in self._xml.findall("Detail"):
                            if detail.get("Level") == str(data_level):
                                height_calculated += self._parser_tools.getHeight(
                                    detail)

                    for detail_footer in self._xml.findall("DetailFooter"):
                        if detail_footer.get("Level") == str(data_level):
                            height_calculated += self._parser_tools.getHeight(
                                detail_footer)

                    aof_size = 0
                    for add_footer in self._xml.findall("AddOnFooter"):
                        # if add_footer.get("Level") == str(data_level):
                        aof_size += self._parser_tools.getHeight(add_footer)
                        height_calculated += self._parser_tools.getHeight(
                            add_footer)

                    page_footer: Any = self._xml.get("PageFooter")
                    if isinstance(page_footer, Element):
                        if (self._document.page_no() == 1
                                or page_footer.get("PrintFrecuency") == "1"):
                            height_calculated += self._parser_tools.getHeight(
                                page_footer)

                    height_calculated += self._bottom_margin
                    if (height_calculated +
                            aof_size) > self._document.h:  # Si nos pasamos
                        self._no_print_footer = True
                        # Vemos el tope por abajo
                        limit_bottom = self._document.h - aof_size
                        actual_size = self._parser_tools.getHeight(
                            section) + self.topSection()

                        if (actual_size >= limit_bottom - 2
                            ) or self.last_detail:  # +2 se usa de margen extra
                            self.processSection("AddOnFooter", int(data_level))

                            self.newPage(data_level)

                self.processXML(section, data)

                if section.get("NewPage") == "true" and not self.last_detail:
                    self.newPage(data_level, False)

                break  # Se ejecuta una sola instancia

    def processSection(self, name: str, level: int = 0) -> None:
        """
        Process non-detail sections.

        @param name. Section name to process
        """
        sec_list = self._xml.findall(name)
        sec_ = None
        for section in sec_list:
            if section.get("Level") == str(
                    level) or section.get("Level") is None:
                sec_ = section
                break

        if sec_ is not None:
            if (sec_.get("PrintFrequency") == "1"
                    or self._document.page_no() == 1
                    or name in ("AddOnHeader", "AddOnFooter")):
                self.processXML(sec_)

    def processXML(self, xml: Element, data: Optional[Element] = None) -> None:
        """
        Process single XML element.

        @param xml: Element to process
        @param. data: Line affected
        """

        fix_height = True
        if data is None:
            data = self._actual_data_line

        if self.design_mode and data is not None:
            print("Procesando", xml.tag, data.get("level"))

        size_updated = False
        if xml.tag == "DetailFooter":
            if xml.get("PlaceAtBottom") == "true":
                height = self._parser_tools.getHeight(xml)
                self.setTopSection(self._document.h - height -
                                   self.increase_section_size)
                size_updated = True

        if xml.tag == "PageFooter":
            fix_height = False

        if not size_updated:
            self.fix_extra_size(
            )  # Sirve para actualizar la altura con lineas que se han partido porque son muy largas

        for label in xml.iter("Label"):
            self.processText(label, data, fix_height)

        for field in xml.iter("Field"):
            self.processText(field, data, fix_height)

        for special in xml.iter("Special"):
            self.processText(special, data, fix_height, xml.tag)

        for calculated in xml.iter("CalculatedField"):
            self.processText(calculated, data, fix_height, xml.tag)

        # Busco draw_at_header en DetailFooter y los meto también
        if xml.tag == "DetailHeader":
            detail_level = xml.get("Level")
            if detail_level is None:
                raise Exception("Level tag not found")
            for detail_footer in self._xml.iter("DetailFooter"):
                if detail_footer.get("Level") == detail_level:
                    for calculated_filed in detail_footer.iter(
                            "CalculatedField"):
                        if calculated_filed.get("DrawAtHeader") == "true":
                            header_name = "%s_header_%s_%s" % (
                                self.detailn[detail_level],
                                detail_level,
                                calculated_filed.get("Field"),
                            )
                            self.draws_at_header[header_name] = ""
                            self.processText(calculated_filed, data,
                                             fix_height, xml.tag)

        for line in xml.iter("Line"):
            self.processLine(line, fix_height)

        if not size_updated:
            self.setTopSection(self.topSection() +
                               self._parser_tools.getHeight(xml))

    def fix_extra_size(self) -> None:
        """Increase size of the section if needed."""
        if self.increase_section_size > 0:
            self.setTopSection(self.topSection() + self.increase_section_size)
            self.increase_section_size = 0

    def processLine(self, xml: Element, fix_height: bool = True) -> None:
        """
        Process single line.

        @param xml. Sección de xml a procesar.
        @param fix_height. Ajusta la altura a los .kut originales, excepto el pageFooter.
        """

        color = xml.get("Color")
        red = 0 if not color else int(color.split(",")[0])
        green = 0 if not color else int(color.split(",")[1])
        blue = 0 if not color else int(color.split(",")[2])

        style = int(xml.get("Style") or "0")
        width = int(xml.get("Width") or "0")
        pos_x1 = self.calculateLeftStart(xml.get("X1") or "0")
        pos_x1 = self.calculateWidth(pos_x1, 0, False)
        pos_x2 = self.calculateLeftStart(xml.get("X2") or "0")
        pos_x2 = self.calculateWidth(pos_x2, 0, False)

        # Ajustar altura a secciones ya creadas
        pos_y1 = int(xml.get("Y1") or "0") + self.topSection()
        pos_y2 = int(xml.get("Y2") or "0") + self.topSection()
        if fix_height:
            pos_y1 = self._parser_tools.ratio_correction_h(pos_y1)
            pos_y2 = self._parser_tools.ratio_correction_h(pos_y2)

        self._document.set_line_width(
            self._parser_tools.ratio_correction_h(width))
        self._document.set_draw_color(red, green, blue)
        dash_length = 1
        space_length = 1
        if style == 2:
            dash_length = 20
            space_length = 20
        elif style == 3:
            dash_length = 10
            space_length = 10

        self._document.dashed_line(pos_x1, pos_y1, pos_x2, pos_y2, dash_length,
                                   space_length)
        # else:
        #    self._document.line(X1, Y1, X2, Y2)

    def calculateLeftStart(self, position: Union[str, int, float]) -> int:
        """
        Check if left margin is exceeded for current page.

        @param position. Position to check.
        @return Revised position.
        """
        return self._parser_tools.ratio_correction_w(
            int(position)) + self._left_margin

    def calculateWidth(self,
                       width: int,
                       pos_x: int,
                       fix_ratio: bool = True) -> int:
        """
        Check if right margin is exceeded for current page.

        @param x. Position to check.
        @return Revised position.
        """
        limit = self._document.w - self._right_margin
        ret_: int

        if fix_ratio:
            width = self._parser_tools.ratio_correction_w(width)
            pos_x = self._parser_tools.ratio_correction_w(pos_x)
            ret_ = width
            if pos_x + width > limit:
                ret_ = limit - pos_x
        else:
            ret_ = width

        return ret_

    def processText(
        self,
        xml: Element,
        data_row: Optional[Element] = None,
        fix_height: bool = True,
        section_name: Optional[str] = None,
    ) -> None:
        """
        Check tag (calculated, label, special or image).

        @param xml. XML section to process.
        @param fix_height. Revise height from original .kut file except pageFooter.
        """
        is_image = False
        is_barcode = False
        text: str = xml.get("Text") or ""
        # borderColor = xml.get("BorderColor")
        field_name = xml.get("Field") or ""

        # x,y,W,H se calcula y corrigen aquí para luego estar correctos en los diferentes destinos posibles
        width = int(xml.get("Width") or "0")

        height = self._parser_tools.getHeight(xml)

        pos_x = int(xml.get("X") or "0")

        pos_y = (int(xml.get("Y") or "0") + self.topSection()
                 )  # Añade la altura que hay ocupada por otras secciones
        if fix_height:
            pos_y = self._parser_tools.ratio_correction_h(
                pos_y)  # Corrige la posición con respecto al kut original

        data_type = xml.get("DataType")

        if xml.tag == "Field" and data_row is not None:
            text = data_row.get(field_name) or ""

        elif xml.tag == "Special":
            if text == "":
                if xml.get("Type") == "1":
                    text = "PageNo"
            text = self._parser_tools.getSpecial(text,
                                                 self._actual_append_page_no)

        calculation_type = xml.get("CalculationType")

        if calculation_type is not None and xml.tag != "Field":
            if calculation_type == "6":
                function_name = xml.get("FunctionName")
                if function_name and data_row is not None:
                    try:
                        nodo = self._parser_tools.convertToNode(data_row)

                        ret_ = application.PROJECT.call(
                            function_name, [nodo, field_name], None, False)
                        if ret_ is False:
                            return
                        else:
                            text = str(ret_)

                    except Exception:
                        LOGGER.exception(
                            "KUT2FPDF:: Error llamando a function %s",
                            function_name)
                        return
                else:
                    return
            elif calculation_type == "1":
                text = self._parser_tools.calculate_sum(
                    field_name, self.last_data_processed, self._xml_data,
                    self.actual_data_level)

            elif calculation_type in ("5"):
                if data_row is None:
                    data_row = self._xml_data[0]

                text = data_row.get(field_name) or ""

        if data_type is not None:
            text = self._parser_tools.calculated(text, int(data_type),
                                                 xml.get("Precision"),
                                                 data_row)

        if data_type == "5":
            is_image = True

        elif data_type == "6":
            is_barcode = True

        if xml.get("BlankZero") == "1" and text is not None:
            res_ = re.findall(r"\d+", text)
            if res_ == ["0"]:
                return

        if text is not None:
            from pineboolib.core.settings import config

            temporal = config.value("ebcomportamiento/temp_dir")
            if text.startswith(temporal):
                is_image = True

        # negValueColor = xml.get("NegValueColor")
        # Currency = xml.get("Currency")
        #
        # commaSeparator = xml.get("CommaSeparator")
        # dateFormat = xml.get("DateFormat")

        if is_image:
            self.draw_image(pos_x, pos_y, width, height, xml, text)
        elif is_barcode:
            self.draw_barcode(pos_x, pos_y, width, height, xml, text)
        elif data_row is not None:
            level = data_row.get("level") or "0"
            if level and str(level) in self.detailn.keys():
                val = "%s_header_%s_%s" % (self.detailn[str(level)], level,
                                           field_name)

            if xml.get("DrawAtHeader") == "true" and level:
                if section_name == "DetailHeader":
                    val = ""
                    self.drawText(pos_x, pos_y, width, height, xml, val)

                    # print(level, section_name, val, text)

            if section_name == "DetailFooter" and xml.get(
                    "DrawAtHeader") == "true":
                self.draws_at_header[val] = text
                # print("Añadiendo a", val, text, level)

            else:
                self.drawText(pos_x, pos_y, width, height, xml, text)

    def drawText(self, pos_x: int, pos_y: int, width: int, height: int,
                 xml: Element, txt: str) -> None:
        """
        Draw a text field onto the page.

        @param pos_x. Label X Pos.
        @param pos_y. Label Y Pos.
        @param width. Label Width.
        @param height. Label Height.
        @param xml. Related XML Section
        @param txt. Computed text of the label to be created.
        """

        if txt in ("None", None):
            # return
            txt = ""

        if width == 0 and height == 0:
            return

        txt = self._parser_tools.restore_text(txt)

        resizeable = False

        if xml.get("ChangeHeight") == "1":
            resizeable = True

        # height_resized = False
        orig_x = pos_x
        orig_y = pos_y
        orig_w = width
        orig_h = height
        # Corregimos margenes:
        pos_x = self.calculateLeftStart(pos_x)
        width = self.calculateWidth(width, pos_x)

        # bg_color = xml.get("BackgroundColor").split(",")
        fg_color = self.get_color(xml.get("ForegroundColor") or "")
        self._document.set_text_color(fg_color[0], fg_color[1], fg_color[2])

        # self._document.set_draw_color(255, 255, 255)

        # if xml.get("BorderStyle") == "1":
        # FIXME: Hay que ajustar los margenes

        # font_name, font_size, font_style
        font_style = ""
        font_size = int(xml.get("FontSize") or "0")
        font_name_orig = ((xml.get("FontFamily") or "").lower() if
                          xml.get("FontFamily") is not None else "helvetica")
        font_name = font_name_orig

        font_w = int(xml.get("FontWeight") or "50")

        if font_w == 50:  # Normal
            font_w = 100
        elif font_w >= 65:
            font_style += "B"
            font_w = 100

        font_italic = xml.get("FontItalic")
        font_underlined = xml.get(
            "FontUnderlined")  # FIXME: hay que ver si es así

        # background_color = self.get_color(xml.get("BackgroundColor"))
        # if background_color != [255,255,255]: #Los textos que llevan fondo no blanco van en negrita
        #    font_style += "B"

        if font_italic == "1":
            font_style += "I"

        if font_underlined == "1":
            font_style += "U"

        font_name = font_name.replace(" narrow", "")

        font_full_name = "%s%s" % (font_name, font_style)

        if font_full_name not in self._avalible_fonts:
            font_found: Optional[str] = None
            if font_full_name not in self._unavalible_fonts:
                font_found = self._parser_tools.find_font(
                    font_full_name, font_style)
            if font_found:
                if self.design_mode:
                    LOGGER.warning(
                        "KUT2FPDF::Añadiendo el tipo de letra %s %s (%s)",
                        font_name,
                        font_style,
                        font_found,
                    )
                self._document.add_font(font_name, font_style, font_found,
                                        True)
                self._avalible_fonts.append(font_full_name)

            else:
                if font_full_name not in self._unavalible_fonts:
                    if self.design_mode:
                        LOGGER.warning(
                            "KUT2FPDF:: No se encuentra el tipo de letra %s. Sustituido por helvetica%s."
                            % (font_full_name, font_style))
                    self._unavalible_fonts.append(font_full_name)
                font_name = "helvetica"

        if font_name is not font_name_orig and font_name_orig.lower().find(
                "narrow") > -1:
            font_w = 85

        self._document.set_font(font_name, font_style, font_size)
        self._document.set_stretching(font_w)
        # Corregir alineación
        vertical_alignment = xml.get(
            "VAlignment")  # 0 izquierda, 1 centrado,2 derecha
        horizontal_alignment = xml.get("HAlignment")

        # layout_direction = xml.get("layoutDirection")

        start_section_size = self._actual_section_size
        result_section_size = 0
        # Miramos si el texto sobrepasa el ancho

        array_text: List[str] = []
        array_n = []
        text_lines = []
        if txt.find("\n") > -1:
            for line_text in txt.split("\n"):
                array_n.append(line_text)
        if array_n:  # Hay saltos de lineas ...
            for line_ in array_n:
                text_lines.append(line_)
        else:  # No hay saltos de lineas
            text_lines.append(txt)

        for text_line in text_lines:
            if len(text_line) > 1:
                if text_line[0] == " " and text_line[1] != " ":
                    text_line = text_line[1:]
            str_width = self._document.get_string_width(text_line)
            if (
                    str_width > width - 10 and xml.tag != "Label"
                    and resizeable
            ):  # Una linea es mas larga que el ancho del campo(Le quito 10 al ancho maximo para que corte parecido a kugar original)
                # height_resized = True
                array_text = self.split_text(text_line, width - 10)
            else:

                array_text.append(text_line)

        # calculated_h = orig_h * len(array_text)
        self.drawRect(orig_x, orig_y, orig_w, orig_h, xml)

        processed_lines = 0
        extra_size = 0
        for actual_text in array_text:

            processed_lines += 1

            if processed_lines > 1:
                extra_size += font_size + 2

            if horizontal_alignment == "1":  # sobre X
                # Centrado
                pos_x = pos_x + (width / 2) - (
                    self._document.get_string_width(actual_text) / 2)
                # x = x + (width / 2) - (str_width if not height_resized else width / 2)
            elif horizontal_alignment == "2":

                # Derecha
                pos_x = (pos_x + width -
                         self._document.get_string_width(actual_text) - 2
                         )  # -2 de margen
                # x = x + width - str_width if not height_resized else width
            else:
                # Izquierda
                if processed_lines == 1:
                    pos_x = pos_x + 2

            if vertical_alignment == "1":  # sobre Y
                # Centrado
                # y = (y + ((H / 2) / processed_lines)) + (((self._document.font_size_pt / 2) / 2) * processed_lines)
                pos_y = int((orig_y + (orig_h / 2)) +
                            ((self._document.font_size_pt / 2) / 2))

                if len(array_text) > 1:
                    pos_y = pos_y - (font_size // 2)

            elif vertical_alignment == "2":
                # Abajo
                pos_y = orig_y + orig_h - font_size
            else:
                # Arriba
                pos_y = orig_y + font_size

            pos_y = pos_y + extra_size

            if self.design_mode:
                self.write_debug(
                    self.calculateLeftStart(orig_x),
                    pos_y,
                    "Hal:%s, Val:%s, T:%s st:%s" %
                    (horizontal_alignment, vertical_alignment, txt, font_w),
                    6,
                    "green",
                )
                if xml.tag == "CalculatedField":
                    self.write_debug(
                        self.calculateLeftStart(orig_x),
                        pos_y,
                        "CalculatedField:%s, Field:%s" %
                        (xml.get("FunctionName"), xml.get("Field")),
                        3,
                        "blue",
                    )

            self._document.text(pos_x, pos_y, actual_text)
            result_section_size += start_section_size

        result_section_size = result_section_size - start_section_size

        if (self.increase_section_size < extra_size
            ):  # Si algun incremento extra hay superior se respeta
            self.increase_section_size = extra_size

    def split_text(self, texto: str, limit_w: int) -> List[str]:
        """Split text into lines based on visual width."""
        list_ = []
        linea_: Optional[str] = None

        for parte in texto.split(" "):
            if linea_ is None and parte == "":
                continue

            if linea_ is not None:
                if self._document.get_string_width(linea_ + parte) > limit_w:
                    list_.append(linea_)
                    linea_ = ""
            else:
                linea_ = ""

            linea_ += "%s " % parte
        if linea_ is not None:
            list_.append(linea_)
        return list_

    def get_color(self, value: str) -> List[int]:
        """Convert color text into [r,g,b] array."""
        lvalue = value.split(",")
        red: int
        green: int
        blue: int
        if len(lvalue) == 3:
            red = int(lvalue[0])
            green = int(lvalue[1])
            blue = int(lvalue[2])
        else:
            red = int(value[0:2])
            green = int(value[3:5])
            blue = int(value[6:8])

        return [red, green, blue]

    def drawRect(self,
                 pos_x: int,
                 pos_y: int,
                 width: int,
                 height: int,
                 xml: Element = None) -> None:
        """
        Draw a rectangle in current page.

        @param pos_x. left side
        @param pos_y. top side
        @param width. width
        @param height. heigth
        """
        style_ = ""
        border_color = None
        bg_color = None
        line_width = self._document.line_width
        border_width = 0.2
        # Calculamos borde  y restamos del ancho
        orig_x = pos_x
        orig_y = pos_y
        orig_w = width

        pos_x = self.calculateLeftStart(orig_x)
        width = self.calculateWidth(width, pos_x)

        if xml is not None and not self.design_mode:
            if xml.get("BorderStyle") == "1":

                border_color = self.get_color(xml.get("BorderColor") or "")
                self._document.set_draw_color(border_color[0], border_color[1],
                                              border_color[2])
                style_ += "D"

            bg_color = self.get_color(xml.get("BackgroundColor") or "")
            self._document.set_fill_color(bg_color[0], bg_color[1],
                                          bg_color[2])
            style_ = "F" + style_

            border_width = int(
                xml.get("BorderWidth") or "0" if xml.get("BorderWidth"
                                                         ) else 0.2)
        else:
            self.write_cords_debug(pos_x, pos_y, width, height, orig_x, orig_w)
            style_ = "D"
            self._document.set_draw_color(0, 0, 0)

        if style_ != "":
            self._document.set_line_width(border_width)

            self._document.rect(pos_x, pos_y, width, height, style_)
            self._document.set_line_width(line_width)

            self._document.set_xy(orig_x, orig_y)
        # self._document.set_draw_color(255, 255, 255)
        # self._document.set_fill_color(0, 0, 0)

    def write_cords_debug(
        self,
        pos_x: Union[float, int],
        pos_y: Union[float, int],
        width: Union[float, int],
        height: Union[float, int],
        orig_x: Union[float, int],
        orig_w: Union[float, int],
    ) -> None:
        """Debug for Kut coordinated."""
        self.write_debug(
            int(pos_x),
            int(pos_y),
            "X:%s Y:%s W:%s H:%s orig_x:%s, orig_W:%s" % (
                round(pos_x, 2),
                round(pos_y, 2),
                round(width, 2),
                round(height, 2),
                round(orig_x, 2),
                round(orig_w, 2),
            ),
            2,
            "red",
        )

    def write_debug(self,
                    pos_x: int,
                    pos_y: int,
                    text: str,
                    height: int,
                    color: Optional[str] = None) -> None:
        """Write debug data into the report."""
        orig_color = self._document.text_color
        red = 0
        green = 0
        blue = 0
        current_font_family = self._document.font_family
        current_font_size = self._document.font_size_pt
        current_font_style = self._document.font_style
        if color == "red":
            red = 255
        elif color == "green":
            green = 255
        elif color == "blue":
            blue = 255

        self._document.set_text_color(red, green, blue)
        self._document.set_font_size(4)
        self._document.text(pos_x, pos_y + height, text)
        self._document.text_color = orig_color
        # self._document.set_xy(orig_x, orig_y)
        self._document.set_font(current_font_family, current_font_style,
                                current_font_size)

    def draw_image(self, pos_x: int, pos_y: int, width: int, height: int,
                   xml: Element, file_name: str) -> None:
        """
        Draw image onto current page.

        @param pos_x. left position
        @param pos_y. top position
        @param width. width
        @param height. heigth
        @param xml. Related XML section
        @param file_name. filename of temp data to use
        """
        import os

        if not file_name.lower().endswith(".png"):
            file_name_ = self._parser_tools.parseKey(file_name)
            if file_name_ is None:
                return
            file_name = file_name_

        if os.path.exists(file_name):
            pos_x = self.calculateLeftStart(pos_x)
            width = self.calculateWidth(width, pos_x)

            self._document.image(file_name, pos_x, pos_y, width, height, "PNG")

    def draw_barcode(self, pos_x: int, pos_y: int, width: int, height: int,
                     xml: Element, text: str) -> None:
        """
        Draw barcode onto currrent page.
        """
        if text == "None":
            return
        from pineboolib.fllegacy import flcodbar

        file_name = application.PROJECT.tmpdir
        file_name += "/%s.png" % (text)
        codbartype = xml.get("CodBarType")

        if not os.path.exists(file_name):

            bar_code = flcodbar.FLCodBar(text)  # Code128
            if codbartype is not None:
                type: int = bar_code.nameToType(codbartype.lower())
                bar_code.setType(type)

            bar_code.setText(text)

            pix = bar_code.pixmap()
            if not pix.isNull():
                pix.save(file_name, "PNG")

        self.draw_image(pos_x + 10, pos_y, width - 20, height, xml, file_name)

    def setPageFormat(self, xml: Element) -> None:
        """
        Define page parameters.

        @param xml: XML with KUT data
        """
        custom_size = None

        self._bottom_margin = int(xml.get("BottomMargin") or "0")
        self._left_margin = int(xml.get("LeftMargin") or "0")
        self._right_margin = int(xml.get("RightMargin") or "0")
        self._top_margin = int(xml.get("TopMargin") or "0")

        page_size = int(xml.get("PageSize") or "0")
        page_orientation = xml.get("PageOrientation") or "0"

        if page_size in [30, 31]:
            custom_size = [
                int(xml.get("CustomHeightMM") or "0"),
                int(xml.get("CustomWidthMM") or "0"),
            ]

        self._page_orientation = "P" if page_orientation == "0" else "L"
        self._page_size = self._parser_tools.convertPageSize(
            page_size, int(page_orientation), custom_size)  # devuelve un array

    def draw_margins(self) -> None:
        """Draw margins on the report."""
        self.draw_debug_line(0 + self._left_margin, 0, 0 + self._left_margin,
                             self._page_size[1])  # Vertical derecha
        self.draw_debug_line(
            self._page_size[0] - self._right_margin,
            0,
            self._page_size[0] - self._right_margin,
            self._page_size[1],
        )  # Vertical izquierda
        self.draw_debug_line(0, 0 + self._top_margin, self._page_size[0],
                             0 + self._top_margin)  # Horizontal superior
        self.draw_debug_line(
            0,
            self._page_size[1] - self._bottom_margin,
            self._page_size[0],
            self._page_size[1] - self._bottom_margin,
        )  # Horizontal inferior

    def draw_debug_line(
        self,
        pos_x1: int,
        pos_y1: int,
        pos_x2: int,
        pos_y2: int,
        title: Optional[str] = None,
        color: str = "GREY",
    ) -> None:
        """Draw a debug line on the report."""
        dash_length = 2
        space_length = 2

        red = 0
        green = 0
        blue = 0
        if color == "GREY":
            red = 220
            green = 220
            blue = 220
        self._document.set_line_width(1)
        self._document.set_draw_color(red, green, blue)
        self._document.dashed_line(pos_x1, pos_y1, pos_x2, pos_y1, dash_length,
                                   space_length)

    def number_pages(self) -> int:
        """Get number of pages on the report."""
        return self._actual_append_page_no if self._actual_append_page_no > 0 else 0

    def reset_page_no(self) -> None:
        """Reset page number."""
        self._actual_append_page_no = -1
Exemplo n.º 56
0
    pdf.cell(20, 10, f"Software Version :{s_version}", 0, 0, "C")
    pdf.ln(5)


def create_index_link(entry, n):
    pdf.set_font("Arial", "U", 30)
    pdf.set_text_color(51, 102, 153)
    to_page = pdf.add_link()
    pdf.set_link(to_page, page=n)
    pdf.cell(80)
    pdf.cell(20, 10, f"{entry}", 0, 0, "C", link=to_page)
    pdf.ln(20)


pdf = FPDF()
pdf.add_page()
create_title(s_version, d1, pdf)

pdf.add_page()
n = 3
pdf.ln(30)
create_index_link(chap1, n)
create_index_link(chap2, n)
create_index_link(chap3, n)
create_index_link(chap4, n)

pdf.add_page()
pdf.ln(10)
pdf.image("wat.png", w=180, h=150)

pdf.output('tuto1.pdf', 'F')
Exemplo n.º 57
0
def atualizarVenda(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')

    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')
Exemplo n.º 58
0
def pdf():
    if (entry3.get() == '' or entry0.get() == '' or pn_p_e.get() == ''
            or p_a_e.get() == '' or pn_w_e.get() == ''
            or Text1.get('1.0') == '' or Text2.get('1.0') == ''):
        messagebox.showerror('Error', 'Please fill all the details')
        return
    global h, d, path
    c = 0
    try:
        global h, d
        d = open('doctor_details.txt').read()
        h = open('hospital_details.txt').read()
    except FileNotFoundError:
        c = 1
        messagebox.showinfo(
            'Information',
            "You didn't Fill either Doctor Details or Hospital Details or both. Please fill them by clicking on Reset doctor Details and Reset Hospital details"
        )
    if c == 0:
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", 'B', size=18)
        h = h.split('$')
        pdf.cell(200, 10, txt=h[0].upper(), ln=1, align='C')
        pdf.set_font('Arial', size=12)
        l = h[1].split('\n')
        for i in l:
            pdf.cell(200, 5, txt=i, ln=1, align='C')
        pdf.set_font("Arial", size=16)
        d = d.split('$')
        pdf.cell(200,
                 10,
                 txt="Doctor's name:  " + d[0] + '\t\t\t\t\t\t\t\t\t' +
                 "Phone number:  " + d[1],
                 ln=2)
        #pdf.cell(200,10,txt="Phone number:  "+x[1],ln=2)
        pdf.cell(200,
                 10,
                 txt="Pateint's name:  " + entry3.get() +
                 '\t\t\t\t\t\t\t\t\t' + "Gender:  " + entry0.get(),
                 ln=3)
        #pdf.cell(200,10,txt="Gender:  "+entry0.get(),ln=5)
        pdf.cell(200,
                 10,
                 txt="Patient Phone number: " + pn_p_e.get() +
                 '\t\t\t\t\t\t\t\t\t' + "Age: " + p_a_e.get(),
                 ln=1)
        pdf.set_font("Arial", size=16)
        probl = Text1.get('1.0', END).split('\n')
        pdf.cell(200, 10, txt="PROBLEM:", ln=1)
        pdf.set_font("Arial", size=12)
        for i in range(0, len(probl)):
            pdf.cell(200, 5, txt=str(i + 1) + "." + probl[i], ln=1)
        pdf.cell(200, 2, txt='', ln=1)
        pdf.set_font("Arial", size=16)
        pdf.cell(200, 10, txt="MEDICATION:", ln=6)
        pdf.set_font("Arial", size=12)
        tablets = Text2.get('1.0', END).split('\n')
        for i in range(0, len(tablets)):
            pdf.cell(200, 5, txt=str(i + 1) + "." + tablets[i], ln=i + 7)
        if path == '':
            messagebox.showerror('Error', 'Add Signature')
        else:
            pdf.image(path)
            try:
                pdf.output(entry3.get() + ".pdf")
                messagebox.showinfo('Information',
                                    'PDF had been saved successfully')
            except OSError:
                messagebox.showerror(
                    'Error',
                    'PDF not created Due to some error retry by typing Patient full name'
                )
Exemplo n.º 59
0
def save(name, age, sex, system, height, weight, activity_status, program,
         work_start, work_end, preparation, refresh, required_hour,
         sleep_buffer, sleep_cycle, cus, calorie_required, nut, title):
    #------------------------Instance Creation & Addition of First Page-------------------
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", 'B', 20)
    #------------------------Create Cells & Add Data--------------------------------------
    pdf.cell(200,
             10,
             txt="Sleep Schedule and Nutrition Report",
             ln=1,
             align='C')
    pdf.set_font("Arial", size=13)
    pdf.cell(
        200,
        10,
        txt=
        "________________________________________________________________________",
        ln=2,
        align='L')
    pdf.cell(200, 10, txt="Name: " + name, ln=3, align='L')
    pdf.cell(200,
             10,
             txt="Age:" + str(age) +
             "                                             Sex:" + sex +
             "                                      System: " + system,
             ln=4,
             align='L')
    if system == 'Metric':
        pdf.cell(
            200,
            10,
            txt="Weight: " + str(weight) + " kg" +
            "                                                                                  Height: "
            + str(int(height)) + " cm",
            ln=5,
            align='L')
    elif system == 'Imperial':
        pdf.cell(
            200,
            10,
            txt="Weight: " + str(weight) + " lbs." +
            "                                                                          Height: "
            + str(int(height)) + " inches",
            ln=5,
            align='L')
    pdf.cell(200,
             10,
             txt="Activity Status: " + activity_status +
             "                                              Program: " +
             program,
             ln=6,
             align='L')
    pdf.cell(200,
             10,
             txt="Work Start Time                               : " +
             work_start,
             ln=7,
             align='L')
    pdf.cell(200,
             10,
             txt="Work End Time                                : " + work_end,
             ln=8,
             align='L')
    pdf.cell(200,
             10,
             txt="Preparation Time After Waking Up  : " + str(preparation) +
             " hrs.",
             ln=9,
             align='L')
    pdf.cell(200,
             10,
             txt="Refresh Time After Work                 : " + str(refresh) +
             " hrs.",
             ln=9,
             align='L')
    pdf.cell(200,
             10,
             txt="Buffer Time Before Sleep                : " +
             str(sleep_buffer) + " mins.",
             ln=9,
             align='L')
    pdf.cell(
        200,
        10,
        txt=
        "________________________________________________________________________",
        ln=10,
        align='L')
    pdf.set_font("Arial", 'B', 16)
    pdf.cell(200, 10, txt="Sleep Report", ln=11, align='C')
    pdf.set_font("Arial", size=13)
    pdf.cell(200,
             10,
             txt="Daily Required Sleep Hour : " + str(required_hour) + " hrs.",
             ln=12,
             align='L')
    pdf.cell(200,
             10,
             txt="Number of Sleep Cycles (90 min each) : " + str(sleep_cycle),
             ln=13,
             align='L')
    try:
        pdf.cell(200, 10, txt=cus, ln=14, align='L')
    except:
        pdf.cell(200,
                 10,
                 txt="Your Customised Sleeping Slots: ",
                 ln=14,
                 align='L')
        for i in range(len(cus[0])):
            pdf.cell(200,
                     10,
                     txt="Sleep: " + cus[0][i] + "           Wake: " +
                     cus[1][i],
                     ln=15,
                     align='L')
    pdf.cell(
        200,
        10,
        txt=
        "________________________________________________________________________",
        ln=16,
        align='L')
    pdf.cell(200,
             10,
             txt="A Well Spent Day Bring Happy Sleep. Sweet Dreems.",
             ln=17,
             align='L')
    pdf.set_font("Arial", 'B', 20)
    pdf.cell(200, 10, txt="Diet Report", ln=18, align='C')
    pdf.set_font("Arial", size=13)
    pdf.cell(200,
             10,
             txt="Daily Calorie Requirement : " + str(round(calorie_required)),
             ln=19,
             align='L')
    pdf.cell(200,
             10,
             txt="Your Customised Nurtrient Distribution : ",
             ln=20,
             align='L')
    pdf.cell(200,
             10,
             txt="Carbohydrate : " + str(nut[0]) + ' gm',
             ln=21,
             align='L')
    pdf.cell(200,
             10,
             txt="Protein            : " + str(nut[1]) + ' gm',
             ln=22,
             align='L')
    pdf.cell(200,
             10,
             txt="Fat                  : " + str(nut[2]) + ' gm',
             ln=23,
             align='L')
    pdf.cell(
        200,
        10,
        txt=
        "________________________________________________________________________",
        ln=16,
        align='L')

    #------------------------Save .pdf file-----------------------------------------------
    pdf.output(title)
Exemplo n.º 60
0
def mkpdffilenote():
    from fpdf import FPDF
    import os
    import os.path
    try:
        # obtain matter name
        m = request.form.get("mname")
        mname = m.upper()
        # obtain date
        date = now
    except:
        print("failed to set matter name and date")
    try:
        # obtain attendance type
        xax = ""
        for el in attendtype:
            if request.form.get(el) == "on":
                xax += el + ", "
        tp = xax
        type = tp.upper()
    except:
        print("failed to set attend type")
    try:
        # obtain attendance with
        xab = ""
        for el in attendupon:
            if request.form.get(el) == "on":
                xab += el + ", "
        attendon = xab.upper()
        # obtain text of file note
    except:
        print("failed to set attendance with")
    try:
        notes = request.form.get("text")
        # create the pdf using the now set variables
    except:
        print("failed to set notes for pdf")
    try:
        pdf = FPDF()
        pdf.add_page()
        pdf.set_auto_page_break(True, 2)
        pdf.set_font("Arial", size = 20)
        pdf.cell(200,10, txt = "FILE NOTE", ln = 1, align = 'C')
        pdf.set_font("Arial", size = 12)
        pdf.cell(200,10, txt = f"Matter name:    {mname}", ln = 1, align = 'L')
        pdf.cell(200,10, txt = f"Date:             {date}", ln = 1, align = 'l')
        pdf.cell(200,10, txt = f"Attendance Type: {type}", ln = 1, align = 'l')
        pdf.cell(200,10, txt = f"Attendance Upon: {attendon}, ln = 1, align = 'l")
        pdf.cell(200, 10, txt="Author: Harry McDonald", ln=1)
        pdf.cell(200,10, txt = "NOTES:", ln = 1)
        pdf.multi_cell(200,10, txt = notes, align = 'l')
        pdf.ln()
        # save the pdf under the right file name
        for k in range(1,400):
            if not os.path.exists(f"File Note {mname} {date}.pdf"):
                pdf.output(f'File Note {mname} {date}.pdf')
            elif not os.path.exists(f"File Note {mname} {date}({k}).pdf"):
                pdf.output(f"File Note {mname} {date}({k}).pdf")
                break
        # todo use os.mkdir or shutil move to get file notes into folders sorted by matter

        # if you want to save as word documents instead
        # d = docx.Document()
        # d.add_paragraph(f"FILE NOTE\n{mname}\n{date}\n{type}\n{notes}")
        # for k in range(1,400):
        #     if not os.path.exists(f"Test{mname}.docx"):
        #         d.save(f'Test{mname}.docx')
        #     elif not os.path.exists(f"Test{mname}{k}.docx"):
        #         d.save(f'Test{mname}{k}.docx')
        #         break
    except:
        print(f"Failed to save the file note as a PDF")