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')
def createPDF(self, name=None, size='10kb'): from PyPDF2 import PdfFileReader, PdfFileWriter from fpdf import FPDF import os import random name = os.path.basename(name) tmp_name = '/tmp/' + name output_name = self.sharepath + '/' + name if size == '10kb': randlength = random.randint(10000,90000) elif size == '100kb': randlength = random.randint(100000,900000) elif size == '1mb': randlength = random.randint(1000000,9000000) #create file pdf=FPDF() pdf.add_page() pdf.set_font('Arial','B',8) pdf.cell(0,0,os.urandom(randlength)) pdf.output(tmp_name, "F") #encrypt it output = PdfFileWriter() input1 = PdfFileReader(open(tmp_name, "rb")) output.encrypt(user_pwd="ihasapass") output.addPage(input1.getPage(0)) outputStream = file(output_name, "wb") output.write(outputStream) outputStream.close()
def 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 test_InlineMathParser(self): pdf = FPDF() lp.initPDF(pdf) def tester(pdf,s, y): p = lp.InlineMathParser() p.match( s ) self.assertTrue( p.hasMatch() ) par = p.docItem par.resizePDF(pdf,10,y) par.cellPDF(pdf) tester(pdf, 'a+b-1', 10) tester(pdf, r'\frac{ \sin(2\alpha) }{\cos\alpha}', 20) tester(pdf, r'\sum_{i=0}^{N/2} x', 40) tester(pdf, r'\prod_{j=1}^{\Omega} (j+1)', 60) tester(pdf, r'\prod_{j} (j+1)', 80) tester(pdf, r'\prod^{\Omega} (j+1)', 100) tester(pdf, r'x^{y}', 120) tester(pdf, r'1+x_{i}^{j}', 140) tester(pdf, r'\sum_{j}j^{2}',160) #self.assertRaises(Exception, tester(pdf, '\frac{}{}', 170)) tester(pdf, r'x^{\sum_{j}j^{2}}',180) pdf.output('out/latex/test_inline_maths.pdf', 'F')
def test_greek_letters(self): pdf=FPDF() initPDF(pdf) setFontPDF(pdf,'symbol') p = lp.ListParser( lp.CommandParser(lp.ParagraphItemCreator) ) s = r'\alpha\beta\gamma' p.match( s ) self.assertTrue( p.hasMatch() ) res = p[0].docItem.writePDF()+' '+p[1].docItem.writePDF()+' '+p[2].docItem.writePDF() self.assertEquals( res, u'\u03b1 \u03b2 \u03b3') pdf.write(0, res) pdf.add_font('djv','','font/DejaVuSans.ttf',uni=True) pdf.set_font('djv','',12) pdf.write(0, u' \u23a8 \u23a7 \u23a9 \u23aa \u239e \u2320 \u2321 \u23ae') pdf.ln(10) pdf.add_font('smb','','font/Symbola.ttf',uni=True) pdf.set_font('smb','',12) pdf.write(0, u' \u23b7 \u03b1 \u03b2 \u03b3') pdf.ln(10) pdf.add_font('jax','','font/mathjax_amsregular.ttf',uni=True) pdf.set_font('jax','',12) pdf.write(0, u' abc \u23b7 \u03b1 \u03b2 \u03b3') pdf.ln(10) pdf.add_font('jax','','font/MathJax/ttf/mathjax_size1regular.ttf',uni=True) pdf.set_font('jax','',12) pdf.write(0, u' abc \u23b7 \u03b1 \u03b2 \u03b3') pdf.output('out/latex/test_greek_letters.pdf', 'F')
def test_Two_Paragraphs(self): s = long_string pdf = FPDF() lp.initPDF(pdf) p1 = lp.ParagraphParser() p1.match( s ) self.assertTrue( p1.hasMatch() ) par1 = p1.docItem par1.resizePDF(pdf) par1.cellPDF(pdf) par1.showRect(pdf) p2 = lp.ParagraphParser() p2.match( s ) self.assertTrue( p1.hasMatch() ) par2 = p2.docItem par2.resizePDF(pdf, 0, par1.rect.height() + 5) par2.cellPDF(pdf) par2.resizePDF(pdf, 0, 40) par2.cellPDF(pdf) par2.width = -1 par2.resizePDF(pdf, 20, 60) par2.cellPDF(pdf) pdf.output('out/latex/test_Two_Paragraphs.pdf', 'F')
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
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
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 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)
def test_ScaleFont(self): self.do_for_each_DocItem_class(InlineMathBlock()) pdf = FPDF() initPDF(pdf) block = InlineMathBlock() block.appendItem(MathFunction('tan')) block.appendItem(MathVariable('x')) block.appendItem(MathSign('=')) block.appendItem(MathFunction('sin')) block.appendItem(MathVariable('x')) block.appendItem(MathSign('/')) block.appendItem(MathFunction('cos')) block.appendItem(MathVariable('x')) block.resizePDF(pdf, 10, 20) block.cellPDF(pdf) block.scaleFont(0.8) block.resizePDF(pdf, 10, 30) block.cellPDF(pdf) block.scaleFont(2.0) block.resizePDF(pdf, 10, 40) block.cellPDF(pdf) pdf.output('out/document/test_ScaleFactor.pdf', 'F')
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
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')
def test_Word_cellPDF(self): p = lp.WordParser() s = r'alpha\beta' p.match(s) self.assertTrue( p.hasMatch() ) self.assertEquals( p.getMatch(s), 'alpha') pdf=FPDF() initPDF(pdf) p.docItem.resizePDF( pdf ) p.docItem.cellPDF( pdf ) p.docItem.resizePDF( pdf, p.docItem.rect.x1() + 10, p.docItem.rect.y0() ) p.docItem.cellPDF( pdf ) p.docItem.resizePDF( pdf, p.docItem.rect.x1() + 10, p.docItem.rect.y0() ) p.docItem.cellPDF( pdf ) r = p.docItem.rect p = lp.CommandParser(lp.ParagraphItemCreator) p.match(r'\alpha') setFontPDF(pdf,'symbol') #pdf.set_font('DejaVu','',11) p.docItem.resizePDF( pdf, r.x1() + 10, r.y0() ) p.docItem.cellPDF( pdf ) pdf.output('out/latex/test_Word_cellPDF.pdf', 'F')
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')
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))
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()
def makepdf(i,p): #os.chdir(i) pdf= FPDF('P','mm',[368,266]) pdf.add_page() pdf.image(p+"/"+u'01台历.jpg',0,0,184,133) pdf.image(p+"/"+u'03台历.jpg',184,0,184,133) pdf.image(p+"/"+u'05台历.jpg',0,133,184,133) pdf.image(p+"/"+u'07台历.jpg',184,133,184,133) pdf.add_page() pdf.image(p+"/"+u'04台历.jpg',0,0,184,133) pdf.image(p+"/"+u'02台历.jpg',184,0,184,133) pdf.image(p+"/"+u'08台历.jpg',0,133,184,133) pdf.image(p+"/"+u'06台历.jpg',184,133,184,133) pdf.add_page() pdf.image(p+"/"+u'09台历.jpg',0,0,184,133) pdf.image(p+"/"+u'11台历.jpg',184,0,184,133) pdf.image(p+"/"+u'13台历.jpg',0,133,184,133) pdf.image(u'b.jpg',184,133,184,133) pdf.add_page() pdf.image(p+"/"+u'12台历.jpg',0,0,184,133) pdf.image(p+"/"+u'10台历.jpg',184,0,184,133) pdf.image(u'b.jpg',0,133,184,133) pdf.image(p+"/"+u'14台历.jpg',184,133,184,133) pdf.output(i+'.pdf','F') print i + "----->ok"
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')
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')
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')
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))
def test_MathSubSuperscript(self): self.do_for_each_DocItem_class(MathSubSuperscript(MathVariable('x'),MathVariable('2'))) pdf = FPDF() initPDF(pdf) #---------------------------- sss = MathSubSuperscript(MathVariable('x'),MathVariable('n'),MathVariable('2')) sss.resizePDF(pdf, 10, 10) sss.cellPDF(pdf) #---------------------------- sss = MathSubSuperscript(MathVariable('x'),MathVariable('i')) sss.resizePDF(pdf, 10, 20) sss.cellPDF(pdf) #---------------------------- block = InlineMathBlock() block.appendItem(MathVariable('x')) block.appendItem(MathSign('+')) block.appendItem(MathVariable('y')) brackets = MathBrackets() brackets.appendItem(block) sss = MathSubSuperscript(brackets,None,MathVariable('p')) sss.resizePDF(pdf, 10, 40) sss.cellPDF(pdf) pdf.output('out/document/test_MathSubSuperscript.pdf', 'F')
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')
def test_MathBrackets(self): tmp = MathBrackets() tmp.appendItem(MathVariable('x')) self.do_for_each_DocItem_class(tmp) pdf = FPDF() initPDF(pdf) block = InlineMathBlock() block.appendItem(MathVariable('x')) block.appendItem(MathSign('+')) block.appendItem(MathVariable('y')) brackets = MathBrackets() brackets.appendItem(block) brackets.resizePDF(pdf, 10, 10) brackets.cellPDF(pdf) p = MathPower() p.appendItem(brackets) p.appendItem(MathVariable('q')) p.resizePDF(pdf, 10, 20) p.cellPDF(pdf) pdf.output('out/document/test_MathBrackets.pdf', 'F')
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)
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')
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)
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'))
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')
def make_pdf(main_units, backup_units, bonus_units, backup_dict, main_unit_match, bonus_unit_match, bonus_dict, folder_name): pdf = FPDF() for ind, row in main_units.iterrows(): for count in range(row["bigcount"]): backup_ind = backup_dict[ind] pdf.add_page() pdf.set_font('Arial', 'B', 35) pdf.cell(0, 20, 'Team # ' + str(1 + ind) + "({num} team members)".format( num=str(min(2 * row["bigcount"], 8))), ln=2, align='C') #Set the main complex pdf.set_font('Arial', 'B', 20) pdf.cell(0, 10, 'Main Complex (go here first):', ln=2) pdf.set_font('Arial', "", 14) apt_title = main_units.loc[ind, "Apartment Title"] description = main_units.loc[ind, "Description"] address = main_units.loc[ind, "Address"] pdf.cell(0, 7, apt_title + ", " + address, ln=2) pdf.cell(0, 7, description, ln=2) pdf.cell( 0, 12, "Check if you visited _____ Approx. what % of units did you visit ______", ln=2) #Set the backup complex pdf.set_font('Arial', 'B', 20) pdf.cell(0, 10, "Backup Complex (ONLY if you can't access main):", ln=2) pdf.set_font('Arial', "", 14) apt_title = backup_units.loc[backup_ind, "Apartment Title"] description = backup_units.loc[backup_ind, "Description"] address = backup_units.loc[backup_ind, "Address"] pdf.cell(0, 7, apt_title + ", " + address, ln=2) pdf.cell(0, 7, description, ln=2) pdf.cell( 0, 7, "Check if you visited _____ Approx. what % of units did you visit _________", ln=2) #Set the bonus complexes bonus_frame = get_frame(ind, main_units, bonus_units, main_unit_match, bonus_unit_match, bonus_dict) pdf.set_font('Arial', 'B', 20) pdf.cell(0, 10, "Bonus Complexes", ln=2) pdf.set_font('Arial', "", 14) for bonus_ind, bonus_row in bonus_frame.iterrows(): apt_title = bonus_row["Apartment Title"] description = bonus_row["Description"] address = bonus_row["Address"] pdf.cell(0, 7, apt_title.encode('utf8') + ", " + address.encode('utf8'), ln=2) pdf.cell(0, 7, description, ln=2) pdf.cell( 0, 7, "Check if you visited _____ Approx. what % of units did you visit _________", ln=2) pdf.output(folder_name + '/temp_folder/Turf list.pdf', 'F')
def buscarFinanciera(folder=''): print('Entrando a Financiera') archivos = [f for f in listdir(folder) if isfile(join(folder, f))] palabra = [ "CAPACIDAD FINANCIERA", "Capacidad financiera", "Capacidad Financiera", "capacidad financiera", "INDICADORES FINANCIEROS", "Indicadores financieros", "HABILITANTES FINANCIEROS", "Habilitantes financieros", "Habilitantes Financieros" ] pytesseract.pytesseract.tesseract_cmd = r'/usr/local/Cellar/tesseract/4.1.0/bin/tesseract' ocurrencias = [] # Abrimos la imagen for x in archivos: ruta = folder + x try: if x.endswith('.jpg'): im = Image.open(ruta) # Utilizamos el método "image_to_string" # Le pasamos como argumento la imagen abierta con Pillow with open(folder + x.replace('.jpg', '') + ".txt", "r") as text_file: datafile = text_file.readlines() for i, line in enumerate(datafile): for d in palabra: if d in line: #Se utiliza el script buscarTablas para encontrar y extraer las tablas relacionadas encontrados = buscarTablas(ruta) #Los resultados se escanean con la libreria Pytesseract y se comprueba que lo encontrado es correcto for u in encontrados: texteando = pytesseract.image_to_string(u) texteando = unidecode.unidecode(texteando) #Si hay coincidencias se guarda el resultado en una imagen if any( i.isdigit() for i in texteando ) and 'Endeudamiento' in texteando or 'ENDEUDAMIENTO' in texteando or 'endeudamiento' in texteando or '%' in texteando: os.rename( u, folder + r'Financiero-' + str(i) + '.png') ocurrencias.append(folder + 'Financiero-' + str(i) + '.png') i += 1 else: continue except: continue dosocurrencias = [] #En caso de haber repetidos resultados o resultados no relacionados, se eliminan para ahorrar analisis y espacio for a in ocurrencias: for b in ocurrencias: try: if str(a) is not str(b) and os.path.exists( a) and os.path.exists(b): an = cv2.imread(a) bn = cv2.imread(b) an = cv2.resize(an, (500, 300)) bn = cv2.resize(bn, (500, 300)) difference = cv2.subtract(an, bn) result = not np.any(difference) if result is True: ocurrencias.remove(b) dosocurrencias.append(b) if os.stat(a).st_size < 100000: ocurrencias.remove(a) dosocurrencias.append(a) except Exception as e: print(e) continue for i in dosocurrencias: if (i in ocurrencias): dosocurrencias.remove(i) for i in dosocurrencias: if (os.path.exists(i)): os.remove(os.path.abspath(i)) #Como ultima alternativa, en caso de no encontrar cuadros con la informacion, se busca el texto y se extrae el texto relacionado if not ocurrencias: ocurrencias = buscarCoincidencias(palabra, 10, folder) p = 0 results = '' for j in ocurrencias: if 'INDICE DE LIQUIDEZ' in j or 'Indice de liquidez' in j or 'Indice de Liquidez' in j or 'Liquidez' in j: fecha = ocurrencias[p:p + 20] results = fecha pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font('arial', 'B', 13.0) for i in results: pdf.write(5, str(i)) pdf.ln() pdf.output(folder + 'Financieros.pdf', 'F') pages = convert_from_path(folder + 'Financieros.pdf') paginas = [] u = 0 for page in pages: filename = "Financieros" + "-" + str(u) + '.png' page.save(folder + filename.replace('_', ' '), 'PNG') results.append(folder + filename.replace('_', ' ')) u = u + 1 return results p += 1 #Se eliminan errores y se devuelve la ruta con los resultados obtenidos for i in ocurrencias: if os.path.exists(i) == False: ocurrencias.remove(i) return ocurrencias
def generarpdf(datos, result): pdf = FPDF() #header of the pdf file header = 'Reporte Simulación' pdf.add_page() pdf.set_font('Arial', 'B', 16) w = pdf.get_string_width(header) + 6 pdf.set_x((210 - w) / 2) pdf.cell(w, 9, header, 0, 0, 'C') pdf.line(20, 18, 210 - 20, 18) pdf.ln(10) pdf.set_font('Times', '', 12) pdf.multi_cell(0, 5, ' Datos de configuración: ') pdf.multi_cell(0, 5, ' Descripción: ' + datos['identificacion']) pdf.multi_cell(0, 5, ' Horas de atención: ' + str(datos['horas_atencion'])) pdf.multi_cell( 0, 5, ' Cantidad de intervalos: ' + str(datos['cantidad_intervalos'])) pdf.multi_cell(0, 5, ' Total declientes: ' + str(datos['total_clientes'])) pdf.multi_cell(0, 5, ' Distribuciones: ' + str(datos['distribuciones'])) pdf.multi_cell( 0, 5, ' Cantidad de cajas_abiertas: ' + str(datos['cantidad_cajas_abiertas_cada_intervalo'])) pdf.multi_cell(0, 5, ' Minimo de_productos: ' + str(datos['minimo_productos'])) pdf.multi_cell(0, 5, ' Maximo_de productos: ' + str(datos['maximo_productos'])) pdf.multi_cell(0, 5, ' Promedio_seleccion: ' + str(datos['promedio_seleccion'])) pdf.multi_cell(0, 5, ' promedio_marcado: ' + str(datos['promedio_marcado'])) pdf.multi_cell(0, 5, ' Promedio_pago: ' + str(datos['promedio_pago'])) pdf.multi_cell(0, 5, ' -------------------------------------------------') for i in range(10): pdf.ln() pdf.set_font('Arial', '', 12) pdf.set_fill_color(200, 220, 255) pdf.cell(0, 6, 'Resultados intervalo: ' + str(result[i][0]), 0, 1, 'L', 1) pdf.ln(10) pdf.set_font('Times', '', 12) pdf.multi_cell( 0, 5, ' La cantidad de clientes ingresados es: ' + str(result[i][1])) pdf.multi_cell( 0, 5, ' La cantidad de clientes despachados es: ' + str(result[i][2])) pdf.multi_cell( 0, 5, ' El promedio de productos por cliente despachado es: ' + str(result[i][3])) pdf.multi_cell( 0, 5, ' El promedio de clientes en espera en colas de caja es: ' + str(result[i][4])) pdf.multi_cell( 0, 5, ' La longitud maxima de cola de espera en caja fue de: ' + str(result[i][5])) pdf.ln() pdf.set_font('Arial', '', 12) pdf.set_fill_color(200, 220, 255) pdf.cell(0, 6, 'Tiempo total simulado: ' + str(result[1][6]) + ' minutos.', 0, 1, 'L', 1) #pdf.set_y(0) #on top of the page pdf.set_y(-30) #30 CM from the bottom of the page pdf.set_font('Arial', '', 8) pdf.set_text_color(0) pdf.cell(0, 5, 'Page ' + str(pdf.page_no()), 0, 0, 'C') dir = os.getcwd() + "/*.pdf" Numero = len(glob.glob(str(dir))) Numero += 1 pdf.output('resultados' + str(Numero) + '.pdf', 'F')
message['From'] = sender_address message['To'] = receiver_address message['Subject'] = "COVID-19 REPORT" message.attach(MIMEText(mail_content, 'plain')) attach_file_name = pwd+"\\..\\data\\report.pdf" attach_file = open(attach_file_name, 'rb') # Open the file as binary mode payload = MIMEBase('application', 'octate-stream') payload.set_payload((attach_file).read()) encoders.encode_base64(payload) #encode the attachment #add payload header with filename payload.add_header('Content-Disposition', 'attachment', filename='report.pdf') message.attach(payload) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(message) generate_reports(heading11,figure11,line11,heading12,figure12,line12,emptyline,emptyline) generate_reports(heading21,figure21,line21,heading22,figure22,line22,emptyline,emptyline) generate_reports(heading31,figure31,line31,heading32,figure32,line32,line33,line34) pdf.output(pwd+'\\..\\data\\report.pdf', 'F') send_mail()
def pdf_creator(data): '''receive some data and create a pdf report with a summary of information''' width = 210 today = date.today() pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'B', 16) # header display pdf.image('../images/germany_flag1.png') pdf.image('../images/header_pdf.png', 70, 10) #pdf.cell(f'Date: {today}') # descriptive text pdf.set_font('Arial', 'BU', 18) pdf.cell(0.1, 20, 'Data Resume:') pdf.set_font('Arial', 'BU', 12) pdf.cell(0.1, 40, f'Number of Houses:') pdf.set_font('Arial', size=12) pdf.cell(0.1, 55, f'{data.shape[0]} houses') pdf.set_font('Arial', 'BU', 12) pdf.cell(0.1, 70, f'Rent Price:') pdf.set_font('Arial', size=12) pdf.cell(0.1, 85, f'AVG - {data["montly_rent"].mean():.2f} EUR') pdf.cell(0.1, 95, f'MAX - {data["montly_rent"].max():.2f} EUR') pdf.cell(70, 105, f'MIN - {data["montly_rent"].min():.2f} EUR') pdf.set_font('Arial', 'BU', 12) pdf.cell(0.1, 70, 'Size:') pdf.set_font('Arial', size=12) pdf.cell(0.1, 85, f'AVG - {data["size"].mean():.2f}m²') pdf.cell(0.1, 95, f'MAX - {data["size"].max():.2f}m²') pdf.cell(60, 105, f'MIN - {data["size"].min():.2f}m²') pdf.set_font('Arial', 'BU', 12) pdf.cell(0.1, 70, 'Pets:') pdf.set_font('Arial', size=12) pdf.cell(0.1, 85, f'Not Allowed - {len(data[data["pets"] == "Pets not allowed"])} houses') pdf.cell(0.1, 95, f'Negotiable - {len(data[data["pets"] == "Pets negotiable"])} houses') pdf.cell(-132, 105, f'Allowed - {len(data[data["pets"] == "Pets allowed"])} houses') # histograms pdf.set_font('Arial', 'BU', 18) pdf.cell(0.1, 126, 'Data Histograms:') # first histplot hist_plot(data, 'montly_rent', 'MONTLY RENT') pdf.image('../images/montly_rent.png', 4, 126, width/2) # second histplot hist_plot(data, 'size', 'SIZE') pdf.image('../images/size.png', width/2, 126, width/2) # third histplot hist_plot(data, 'm2_value', 'M² VALUE') pdf.image('../images/m2_value.png', 4, 200, width/2) # fourth histplot hist_plot(data, 'pets', 'PETS') pdf.image('../images/pets.png', width/2, 200, width/2) # second page pdf.add_page() # header display pdf.image('../images/germany_flag1.png') pdf.image('../images/header_pdf.png', 70, 10) #==================== # graphs #==================== pdf.set_font('Arial', 'BU', 18) pdf.cell(0.1, 20, 'Data Graphs:') pdf.ln(20) montly_plot(data) pdf.image('../images/montly_rent_barplot.png', x=0, h=70) pdf.ln(5) m2_plot(data) pdf.image('../images/m2_barplot.png', x=0, h=70) pdf.ln(2) pet_plot(data) pdf.image('../images/pet_plot.png', x=25, h=55) pdf.set_author('Felipe Demenech Vasconcelos') pdf.close() pdf.output('../reports/rent_houses_germany.pdf', 'F') return pdf.output(dest='S')
def attack(zipfilename,dictionary,g,dir=''): """ Zipfile password cracker using a dictionary attack,generating pdf report """ pdf = FPDF() pdf.add_page() format = "%a %b %d %H:%M:%S %Y" today = datetime.datetime.today() s = today.strftime(format) e=d = datetime.datetime.strptime(s, format) sha1target= hashes.sha1(zipfilename) sha1wordlist= hashes.sha1(zipfilename) print '----------dictionary attack----------' print 'target : '+zipfilename print 'wordlist : '+dictionary print 'started at :', d.strftime(format) start=datetime.datetime.now().replace(microsecond=0) pdf.set_font('Arial', 'B', 22) pdf.cell(200, 10, 'Attack Report',align='C',ln=5) pdf.set_font('Courier', '', 12) pdf.cell(125, 4, '',0,1,'C') pdf.cell(115, 4, 'target zip file : " '+zipfilename+' "',0,1) pdf.set_font('Courier', '', 10) pdf.cell(125, 4, 'SHA1 : '+sha1target,0,1,'C') pdf.cell(125, 4, '',0,1,'C') pdf.set_font('Courier', '', 12) pdf.cell(115, 4, 'wordlist used : " '+dictionary+' "',0,1) pdf.set_font('Courier', '', 10) pdf.cell(125, 4, 'SHA1 : '+sha1wordlist,0,1,'C') pdf.cell(125, 4, '',0,1,'C') pdf.set_font('Courier', '', 12) pdf.cell(115, 4, 'attack started at : '+str(d.strftime(format)),0,1) password = None zip_file = zipfile.ZipFile(zipfilename) found=0 attempts=0 lis=zip_file.namelist() namedir=lis[0].split('/')[0] os.system('rm -r '+namedir) with open(dictionary, 'r') as f: for line in f.readlines(): password = line.strip('\n') try: attempts+=1 zip_file.extractall(pwd=password) print 'trying : "'+password +'"....accepted' print 'extracting ...' password = '******' % password found=1 break except: print 'trying : "'+password +'"....wrong password' pass today = datetime.datetime.today() s = today.strftime(format) d = datetime.datetime.strptime(s, format) pdf.cell(125, 4, '',0,1,'C') pdf.cell(115, 4, 'attack finished at : '+str(d.strftime(format)),0,1) print 'finished at :', d.strftime(format) end=datetime.datetime.now().replace(microsecond=0) pdf.cell(125, 4, '',0,1,'C') pdf.cell(115, 4, 'attack duration : " '+str((end-start))+' "',0,1) pdf.cell(125, 4, '',0,1,'C') pdf.cell(115, 4, 'number of attempts : '+str(attempts),0,1) pdf.cell(125, 4, '',0,1,'C') print 'number of attempts : ',attempts print 'duration : ',(end-start) if (found): print password print 'target zipfile successfully extracted to : " '+namedir+' "'+' at the current working directory' pdf.cell(115, 4, password,0,1) pdf.cell(125, 4, '',0,1,'C') pdf.cell(115, 4, 'target zipfile successfully extracted to : " '+namedir+' "',0,1) pdf.cell(125, 4, '',0,1,'C') else : print "[-] final result : password not found" pdf.cell(115, 4, "[-] final result : password not found",0,1) pdf.cell(125, 4, '',0,1,'C') if found: pdf.cell(115, 4, 'all files contained in this zip file with data type test : ',0,1) pdf.cell(125, 4, '',0,1,'C') lis=zip_file.namelist() for item in lis : if os.path.isfile(item): pdf.cell(40, 5, 'FILE : '+item, ln=1) pdf.cell(40, 5, 'MIME-TYPE : '+type(item), ln=1) pdf.cell(125, 4, '',0,1,'C') else: pdf.cell(115, 4, "can't perform data test on files ",0,1) pdf.cell(115, 4, "because NO file was extracted (password not found)",0,1) pdf.cell(125, 4, '',0,1,'C') res='' if(g==1): if(dir==''): name='report_'+str(e).replace(' ','_') res = 'report_'+str(e).replace(' ','_')+'.pdf saved at the current directory' else: name=dir+'/'+'report_'+str(e).replace(' ','_') res = 'hashes_'+str(e).replace(' ','_')+'.pdf saved at '+name+'.pdf' pdf.output(name+'.pdf', 'F') print res #attack('eg.zip','wordlist.txt',1) #browse('',1,'tes')
def pdf(): #CREATE PDF BUTTON 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="Pateint's name: " + entry3.get() + '\t\t\t\t\t\t\t\t\t' + "Gender: " + entry0.get(), ln=3) 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' )
def generate_pdf(self): # self.data_add = filedialog.askopenfilename() self.df = pd.read_excel(self.data_add) company = self.company_name_line.get() date = self.date_line.get() for i in range(len(self.df)): name = self.df['NAME'][i] person_orgazization = self.df['COLLEGE'][i] event = self.df['EVENT'][i] pdf = FPDF(orientation='L', unit='mm', format='legal') pdf.add_page() pdf.set_fill_color(0, 0, 0) pdf.set_font("Times", size=35) # print(pdf.x,pdf.y) pdf.image('d.jpg', x=0, y=0, w=350, h=214) # pdf.image('c.png', x=20, y=67, w=50,h = 60) pdf.image('c.png', x=146, y=127, w=60, h=70) # pdf.add_font() pdf.x = 160.0 pdf.y = 30.0 pdf.cell(40, 20, txt=self.certi_title_default_text.get(), align="C", ln=0) pdf.x = 160.0 pdf.y = 60.0 pdf.set_font("Times", size=30) first_line = self.certi_first_line.get() first_line = self.replacetext(first_line, name, person_orgazization, event, company) pdf.cell(40, 10, txt=first_line, align="C", ln=0) pdf.x = 160.0 pdf.y = 75.0 second_line = self.certi_second_line.get() second_line = self.replacetext(second_line, name, person_orgazization, event, company) pdf.set_font("Times", size=40) pdf.cell(40, 10, txt=second_line, align="C", ln=0) pdf.set_font("Times", size=20) pdf.x = 160.0 pdf.y = 90.0 third_line = self.certi_third_line.get() third_line = self.replacetext(third_line, name, person_orgazization, event, company) pdf.cell(40, 10, txt=third_line, align="C", ln=0) pdf.x = 160.0 pdf.y = 102.0 pdf.set_font("Times", size=25) forth_line = self.certi_forth_line.get() forth_line = self.replacetext(forth_line, name, person_orgazization, event, company) pdf.cell(40, 10, txt=forth_line, align="C", ln=0) pdf.x = 160.0 pdf.y = 114.0 pdf.set_font("Times", size=20) fifth_line = self.certi_fifth_line.get() fifth_line = self.replacetext(fifth_line, name, person_orgazization, event, company) pdf.cell(40, 10, txt=fifth_line, align="C", ln=0) pdf.x = 30.0 pdf.y = 170.0 pdf.set_font("Times", size=20) pdf.cell(40, 10, txt="DATE: " + date, align="C", ln=0) pdf.x = 260.0 pdf.y = 170.0 pdf.set_font("Times", size=20) pdf.cell(40, 10, txt="SIGNATURE", align="C", ln=0) pdf.output(str(i) + " " + self.df['NAME'][i] + ".pdf") print("generated certificate for " + self.df['NAME'][i])
pdf = FPDF() # Set Author Name of the PDF pdf.set_author("@NavonilDas") # Set Subject of The PDF pdf.set_subject("python") # Set the Title of the PDF pdf.set_title("Generating PDF with Python") pdf.add_page() # Set Font family Courier with font size 28 pdf.set_font("Courier", "", 18) # Add Text at (0,50) pdf.text(0, 50, "Example to generate PDF in python.") # Set Font Family Courier with italic and font size 28 pdf.set_font("Courier", "i", 28) pdf.text(0, 60, "This is an italic text") # Write text at 0,60 # Draw a Rectangle at (10,100) with Width 60,30 pdf.rect(10, 100, 60, 30, "D") # Set Fill color pdf.set_fill_color(255, 0, 0) # Red = (255,0,0) # Draw a Circle at (10,135) with diameter 50 pdf.ellipse(10, 135, 50, 50, "F") # Save the Output at Local File pdf.output("output.pdf", "F")
add = raw_input("type image location as described in Readme.md : ") add1 = "-1024.jpg?cb=1453809353" pdf = FPDF() # No of pages = 661 pages = raw_input("Type Number of pages : ") pdfname = raw_input("Type name of pdf with .pdf in last like xyz.pdf : ") pages = int(pages) for i in range(pages): i += 1 link = add + str(i) + add1 name = str(i) + ".jpg" try: download_file(link, name) pdf.add_page() pdf.image(name, 0, 0, 210, 297) os.remove(name) except: print "Error at adding Page No. " + str(i) pdf.output(pdfname, "F")
def generate_pdf_report2(user, start_time, end_time): start_date = format_date_from_datetime(start_time) end_date = format_date_from_datetime(end_time) # Letter size paper, use inches as unit of measure pdf = FPDF(format='letter', unit='in') # Add new page. Without this you cannot create the document. pdf.add_page() # Remember to always put one of these at least once. pdf.set_font('Arial', '', 10.0) # Effective page width, or just epw epw = pdf.w - 2 * pdf.l_margin # Set column width to 1/4 of effective page width to distribute content # evenly across table and page col_width = epw / 3 data = [ get_row(edit) for edit in user.edits if start_time <= edit.time <= end_time ] # Document title centered, 'B'old, 14 pt pdf.set_font('Arial', 'B', 16.0) pdf.multi_cell(epw, 0.0, user.name) th = pdf.font_size pdf.set_font('Arial', '', 12.0) pdf.ln(2 * th) pdf.cell(0, 2 * th, "Contributions between {0} and {1}".format(start_date, end_date)) pdf.ln(2 * th) pdf.set_font('Arial', '', 12.0) pdf.cell(0, 2 * th, "Number of characters added: {0}".format(user.num_added)) pdf.ln() pdf.cell(0, 2 * th, "Number of characters deleted: {0}".format(user.num_deleted)) pdf.ln(4 * th) pdf.set_font('Arial', 'B', 14.0) pdf.cell(0, 2 * th, "Format of edits") pdf.ln(2 * th) # Describe format of edit pdf.set_font('Arial', 'I', 12.0) pdf.cell(col_width, 2 * th, "Date and time", border=1) pdf.cell(col_width * 1.5, 2 * th, "File name", border=1) pdf.cell(col_width * 0.5, 2 * th, "Addition/Deletion", border=1) pdf.ln(2 * th) pdf.cell(0, 2 * th, "Content of edit", border=1) pdf.set_font('Arial', 'B', 14.0) pdf.ln(6 * th) pdf.cell(0, 2 * th, "Edit history") pdf.set_font('Arial', '', 12.0) pdf.ln(4 * th) for row in data: if pdf.h - pdf.y < pdf.b_margin + 4 * th: pdf.add_page() pdf.cell(col_width, 2 * th, str(row[0]), border=1) pdf.cell(col_width * 1.5, 2 * th, str(row[1]), border=1) pdf.cell(col_width * 0.5, 2 * th, str(row[2]), border=1) pdf.ln(2 * th) pdf.multi_cell(0, 2 * th, str(row[3]), border=1) pdf.ln(4 * th) try: pdf.output( '{0} {1} to {2}.pdf'.format(user.name, start_date, end_date), 'F') except: # file already exists and is open pass
def gerar_pdf(data): # save FPDF() class into a # variable pdf pdf = FPDF(orientation='L') # pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size=15) # Effective page width, or just epw epw = pdf.w - 2 * pdf.l_margin # Set column width to 1/4 of effective page width to distribute content # evenly across table and page col_width = epw / 10 # Text height is the same as current font size th = 2 * pdf.font_size # Since we do not need to draw lines anymore, there is no need to separate # headers from data matrix. pdf.cell(epw, 0.0, 'Dados relativos ao dia ' + data, align='C') pdf.ln(th) header_completo = ['Estado', 'Total de Casos', 'Total de Obitos', '% por Populacao', 'Casos dia Anterior', 'Obitos dia Anterior', '% de Aumento de casos', '% de Aumento de obitos', 'Novos Casos', 'Novos Obitos'] header = ['ES', 'TC', 'TO', '%PO', 'CDA', 'ODA', '%AC', '%AO', 'NC', 'NO'] # legenda: pdf.cell(epw, 0.0, 'Legenda:', align='L') pdf.ln(th) for i in range(len(header)): pdf.cell(0.3 * epw, th, header[i] + ' -> ' + header_completo[i], border=1, align='L') pdf.ln(th) pdf.ln(3 * th) # header: primeiro = True for titulo in header: pdf.cell(col_width, th, titulo, border=1) primeiro = True pdf.ln(th) # body for estado in sorted(estados): pdf.cell(col_width, th, estado, border=1) pdf.cell(col_width, th, str(casosAcumulado[estado]), border=1) pdf.cell(col_width, th, str(obitosAcumulado[estado]), border=1) pdf.cell(col_width, th, "{:.6f}".format(percPopCasos[estado]), border=1) pdf.cell(col_width, th, str(casoAnterior[estado]), border=1) pdf.cell(col_width, th, str(obitoAnterior[estado]), border=1) pdf.cell(col_width, th, "{:.6f}".format(percPopCasos[estado]), border=1) pdf.cell(col_width, th, "{:.6f}".format(percPopCasos[estado]), border=1) pdf.cell(col_width, th, str(novosCasos[estado]), border=1) pdf.cell(col_width, th, str(novosObitos[estado]), border=1) pdf.ln(th) pdf.ln(th) col_width = epw / 2 # total de casos e obitos: pdf.cell(col_width, th, 'Total Casos', border=1) pdf.cell(col_width, th, str(sum(casosAcumulado.values())), border=1) pdf.ln(th) pdf.cell(col_width, th, 'Total Obitos', border=1) pdf.cell(col_width, th, str(sum(obitosAcumulado.values())), border=1) pdf.ln(th) pdf.output("relatorio-geral-"+data+".pdf")
margin = 10 imagelist=[] pdf_list=[] merger = PdfFileMerger() for i in range(1,88): str=cwd+"{}{}.jpg".format('\\',i) imagelist.append(str) for imagePath in imagelist: cover = Image.open(imagePath) width, height = cover.size pdf = FPDF(unit="pt", format=[width + 2*margin, height + 2*margin]) pdf.add_page() pdf.image(imagePath, margin, margin) destination = os.path.splitext(imagePath)[0] pdf.output(destination + ".pdf", "F") str=destination+ '.pdf' pdf_list.append(str) for f in pdf_list: merger.append(PdfFileReader(f), 'rb') filename=input("Enter the file name : ") merger.write(filename+".pdf") for i in range(1,88): os.system("del {}.jpg".format(i)) os.system("del {}.pdf".format(i))
from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=15) pdf.cell(200, 10, txt="Read me book app", ln=1, align='C') pdf.cell( 200, 10, txt= "A FEW REALTIONS IN EARTH NEVER DIES TAKE FIRST LETTER FROM EACH WORD TO GET THE WORD THAT YOU MEAN TO ME THANKS BEING THE BEST", ln=2, align='C') pdf.output("GFG.pdf")
def oppt1(): cargar = load_workbook(fill) hoja = cargar.active # Solicitud de datos para recopilacion rspre = input(GG +"\n["+ GL+"+" + GG+"]"+ WW +" Pon el codigo de la V8 que requieras."+ GG +"\n["+ GL +"+"+ GG +"]"+ WW +" Incluye un 0 a la respuesta, ejemplo: 01"+ RR +"\n>>> "+ WW) # Definicion de Variables sobre cada fila rspre0 = int(rspre[1:]) rspre1 = rspre0 + 1 rspreA = (f"A{rspre1}") rspreB = (f"B{rspre1}") rspreC = (f"C{rspre1}") rspreD = (f"D{rspre1}") rspreE = (f"E{rspre1}") rspreF = (f"F{rspre1}") rspreG = (f"G{rspre1}") rspreH = (f"H{rspre1}") rspreI = (f"I{rspre1}") rspreJ = (f"J{rspre1}") rspreK = (f"K{rspre1}") rspreL = (f"L{rspre1}") rspreM = (f"M{rspre1}") rspreN = (f"N{rspre1}") rspreO = (f"O{rspre1}") rspreP = (f"P{rspre1}") rspreQ = (f"Q{rspre1}") rspreR = (f"R{rspre1}") rspreS = (f"S{rspre1}") rspreT = (f"T{rspre1}") rspreU = (f"U{rspre1}") rspreV = (f"V{rspre1}") rspreW = (f"W{rspre1}") # Geerción de Variables definiendo valores de cada celda reA = hoja[rspreA].value reB = hoja[rspreB].value reC = hoja[rspreC].value reD = hoja[rspreD].value reE = hoja[rspreE].value reF = hoja[rspreF].value reG = hoja[rspreG].value reH = hoja[rspreH].value reI = hoja[rspreI].value reJ = hoja[rspreJ].value reK = hoja[rspreK].value reL = hoja[rspreL].value reM = hoja[rspreM].value reN = hoja[rspreN].value reO = hoja[rspreO].value reP = hoja[rspreP].value reQ = hoja[rspreQ].value reR = hoja[rspreR].value reS = hoja[rspreS].value reT = hoja[rspreT].value reU = hoja[rspreU].value reV = hoja[rspreV].value reW = hoja[rspreW].value #Impresion de valores con gráfica predeterminada print (YY +"=========================================\n") print ("Información recopilada de", reB) print (B +"\nCódigo:", WW+str(reA), B+"\nNombres:", WW+reB, WW+reC, B+"\nApellidos:", WW+reD, reE, B+"\nGenero:", WW+reF, B+"\nEdad:", WW+str(reG), B+"\nAptitud Temporal:", WW+str(reH), B+"\nDNI:", WW+str(reI), B+"\nDigito de DNI:", WW+str(reJ), B+"\nRUC:", WW+str(reK), B+"\nFecha de Nacimiento:", WW+reL, B+"\nDistrito:", WW+reM, B+"\nDepartamento:", WW+reN, B+"\nEstatura", WW+str(reO), B+"\nUbigeo:", WW+ str(reP), B+"\nFecha de emisión:", WW+reQ, B+"\nEstado Civil:", WW+reR, B+"\nNúmero Telefónico:", WW + reS, B+"\nEstado - Seguro EsSalud:", WW+reT, B+"\nEstado - Seguro SIS:", WW+reU, B+"\nDomicilio:", WW+reV, B+"\nRazón de estar en la DB:", WW+reW) print (YY +"\n=========================================\n"+ WW) # Opciones alternales print ("¿Que es lo que deseas hacer?") print (M + "\n1) Crear archivo PDF") dcss = int(input(CC + "\nElige una opción: "+ WW)) # Seleccion de la primer opcion if dcss == 1: # Creacion de las variables, funciones y hojas pdf = FPDF() pdf.add_page() sutil(YY +"Creando archivo...") lento(GG +"Archivo creado con exito\n") pdf.set_font("Arial",size=12) # Insercion de datos en PDF pdf.cell(200,10,txt="BD-VTA Archivo recopilado",ln=1,align="C") pdf.cell(200,10,txt="Informacion | Fase 1",ln=2,align="r") pdf.cell(200,10,txt="Código de la victima: "+ reA,ln=3,align="r") pdf.cell(200,10,txt="Nombres: "+ reB+" "+reC,ln=4,align="r") pdf.cell(200,10,txt="Apellidos: "+ reD+" "+reE,ln=5,align="r") pdf.cell(200,10,txt="Genero: "+ reF,ln=6,align="r") pdf.cell(200,10,txt="Edad: "+ str(reG),ln=7,align= "r") pdf.cell(200,10,txt="Informacion | Fase 2",ln=8,align="r") pdf.cell(200,10,txt="Aptitud Temporal: "+ reH,ln=9,align="r") pdf.cell(200,10,txt="DNI: "+ str(reI),ln=10,align="r") pdf.cell(200,10,txt="Digito de DNI: "+ str(reJ),ln=11,align="r") pdf.cell(200,10,txt="RUC: "+ str(reK),ln=12,align="r") pdf.cell(200,10,txt="Fecha de Nacimiento: "+ reL,ln=13,align="r") pdf.cell(200,10,txt="Distrito: "+ reM,ln=14,align="r") pdf.cell(200,10,txt="Departamento: "+ reN,ln=15,align="r") pdf.cell(200,10,txt="Informacion | Fase 3",ln=16,align="r") pdf.cell(200,10,txt="Estatura: "+ str(reO),ln=17,align="r") pdf.cell(200,10,txt="Ubigeo: "+ str(reP),ln=18,align="r") pdf.cell(200,10,txt="Fecha de emisión: "+ reQ,ln=19,align="r") pdf.cell(200,10,txt="Estado civil: "+ reR,ln=20,align="r") pdf.cell(200,10,txt="Número telefónico: "+ reS,ln=21,align="r") pdf.cell(200,10,txt="Estado - Seguro EsSalud: "+ reT,ln=22,align="r") pdf.cell(200,10,txt="Estado - Seguro SIS: "+ reU,ln=23,align="r") pdf.cell(200,10,txt="Razón de estar en la DB: "+ reW,ln=24,align="r") # Definicion de titulo arnom = (reB+" "+reC+" "+reD+" "+reE+".pdf") # Salvacion del archivo final pdf.output(arnom) else: print("Termino el subproceso")
def reporter(*args, **kwargs): pdf = FPDF(format=papersize1.upper()) members_dict = dict(inspect.getmembers(entity)) title = '\"' + entity.__name__ + '\"' + " object report\n" set_object_report_title(pdf, title) if name: name_str = "Name:\t{}\n".format(entity.__name__) write_object_report_body(pdf, name_str) if type: type_str = "Type:\t{}\n".format(members_dict['__class__']) write_object_report_body(pdf, type_str) if sign: sign_str = "Sign:\t{}\n".format(inspect.signature(entity)) write_object_report_body(pdf, sign_str) if arg: arg_str = "Args:\tPositional: " + str(args) + "\n" + " " * len( "Args: ") + '\tkey=worded' + str(kwargs) + "\n" write_object_report_body(pdf, arg_str) if docstrings: doc_str = "" if members_dict['__doc__']: doc_strings = members_dict['__doc__'].split("\n") doc_str = "Doc:\t" + doc_strings[0] + '\n' for i in range(1, len(doc_strings)): doc_str += " " * len( "Doc:") + '\t' + doc_strings[i] + '\n' write_object_report_body(pdf, doc_str) if source: source_strings = inspect.getsource(entity).split('\n') source_str = "Source:\t" + source_strings[0] + '\n' for i in range(1, len(source_strings)): source_str += " " * len( "Source:") + '\t' + source_strings[i] + '\n' write_object_report_body(pdf, source_str) if output: captured_out = io.StringIO() with redirect_stdout(captured_out): entity(*args, **kwargs) output_str = "Output:\t" func_out_strings = captured_out.getvalue().split('\n') if len(func_out_strings) != 0: output_str += func_out_strings[0] + '\n' for i in range(1, len(func_out_strings)): output_str += " " * len( "Output:") + '\t' + func_out_strings[i] + '\n' else: output_str += 'None' write_object_report_body(pdf, output_str) pdf.output(entity.__name__ + "_object.pdf", 'F') if multipage1: merger = PdfFileMerger() if os.path.exists(filename1): merger.append(PdfFileReader(filename1)) merger.append(PdfFileReader(entity.__name__ + "_object.pdf")) merger.write(filename1) os.remove(entity.__name__ + "_object.pdf") return entity(*args, **kwargs)
import fpdf from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font('Arial','I',24) pdf.cell(50,50,'this is demo') pdf.output('fpdf.pdf','F')
if int(pag) < 10: with open("{}-{}\\image0{}.jpg".format(name, cap, pag), 'wb') as arq: arq.write(img_data) else: with open("{}-{}\\image{}.jpg".format(name, cap, pag), 'wb') as arq: arq.write(img_data) time.sleep(0.5) pdf = FPDF() files = [x for x in os.listdir(f'./{name}-{cap}')] for image in files: pdf.add_page() pdf.image(f'{name}-{cap}/{image}', 0, 0, 210, 297) pdf.output(f'{name}-{cap}.pdf', "F") time.sleep(0.5) [ os.remove(f'{name}-{cap}/{x}') for x in os.listdir(f'{name}-{cap}') ] os.rmdir(f'{name}-{cap}') if sys.argv[1] == 'one': print('Coloque a url do capitulo') url = input("Url-> ") print('Nome da pasta a ser criada') name = input("Nome-> ") cap = url.split("/")[-1] page = requests.get(url, headers=headers) tree = html.fromstring(page.content)
print("[INFO] Adding {} to file_list".format(filename)) file_list.append(filename) # build pdf file pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) # read contents into buffer output_lines = [] for file in file_list: with open(file, 'r') as in_file: output_lines.append(FILENAME_HEADER.format(file)) for line in in_file.readlines(): output_lines.append(line) # write txt file if enabled if args.text: output_txt = "{}/output.txt".format(args.output) with open(output_txt, 'w') as f: f.writelines(output_lines) print("[INFO] Wrote repo contents to {}".format(output_txt)) # build pdf and write file output_pdf = "{}/output.pdf".format(args.output) pdf.cell(0, 0, FILENAME_HEADER.format(file)) for line in output_lines: pdf.cell(0, 0, line) pdf.output(output_pdf) print("[INFO] Wrote repo contents to {}".format(output_pdf))
pdf = FPDF() pdf.add_page() pdf.set_font('Arial', '', 16) pdf.write(8, "Transparency") pdf.ln() pdf.write(8, " Transparency") pdf.ln() pdf.write(8, " Transparency") pdf.ln() pdf.image(gif1, x=15, y=15) pdf.write(8, "Transparency") pdf.ln() pdf.write(8, " Transparency") pdf.ln() pdf.write(8, " Transparency") pdf.ln() pdf.image(gif2, x=15, y=39) fn = 'issue33.pdf' pdf.output(fn, 'F') os.unlink(gif1) os.unlink(gif2) try: os.startfile(fn) except: os.system("xdg-open \"%s\"" % fn)
def generate_report(final_KDA, final_frag_list, brownies, match_tags, team_players): # with open('myfile.csv', 'wb') as myfile: # wr = csv.writer(myfile) # for row in final_KDA: # wr.writerrow() KDA_data = [] for key in final_KDA: num_round = final_KDA[key]['rounds'] num_kill = final_KDA[key].get('killed', 0) num_death = final_KDA[key].get('dead', 0) num_defuse = final_KDA[key].get('Defused_The_Bomb', 0) num_plant = final_KDA[key].get('Planted_The_Bomb', 0) num_tk = final_KDA[key].get('tk', 0) kill_time = final_KDA[key].get('first_kill_time', 0) rounds_killed = final_KDA[key].get('rounds_killed', 0) death_time = final_KDA[key].get('death_time', 0) killed_or_traded = final_KDA[key].get('rounds_K|T', 0) killed_or_traded_and_dead = final_KDA[key].get('rounds_(K|T)&D', 0) KST = killed_or_traded + (num_round - num_death) - ( killed_or_traded - killed_or_traded_and_dead) row = [ key, num_round, num_kill, num_kill / num_round, num_death, num_death / num_round, num_plant, num_defuse, num_tk, kill_time / rounds_killed, death_time / num_death, 100 * KST / num_round ] KDA_data.append(row) KDA_data = sorted(KDA_data, key=lambda x: x[3], reverse=True) maxes = [max([item[i + 1] for item in KDA_data]) for i in range(11)] mins = [min([item[i + 1] for item in KDA_data]) for i in range(11)] max_cells = 13 cell_width = 20 KDA_cell_width = 18.9 pdf = FPDF(unit='mm', format=(max_cells * cell_width, 297)) pdf.add_page() header = [ 'Name', 'Rounds', 'Kills', 'K/R', 'Death', 'D/R', 'Planted', 'Defused', 'Friendly', 'K time', 'D time', 'KST %' ] pdf.set_font('Arial', 'B', 13) # epw = pdf.w - 2*pdf.l_margin th = pdf.font_size # Match info in the report is created here for match in match_tags: pdf.set_font('Arial', 'B', 16) pdf.set_text_color(r=192, g=57, b=43) pdf.cell(w=cell_width * max_cells, h=2 * th, txt=match, align='C') pdf.ln(2 * th) pdf.ln(2 * th) # Team and player names team_width = 4 for team in team_players: pdf.set_text_color(r=192, g=57, b=43) pdf.set_font('Arial', 'B', 15) pdf.cell(cell_width * team_width, 2 * th, str(team), align='R', border=0, fill=False) pdf.cell(3) pdf.set_font('Arial', '', 14) pdf.set_text_color(r=0, g=0, b=0) player_names = ', '.join(team_players[team]) pdf.cell(cell_width * (max_cells - team_width), 2 * th, str(player_names), align='L', border=0, fill=False) pdf.ln(2 * th) pdf.ln(2 * th) # weapons section starts here (PISTOL PRO, ...) pdf.set_text_color(r=0, g=0, b=0) for item in range(len(weapon_dict)): weapon_details = weapon_dict[item] weapons = weapon_details['weapon'] text2put = weapon_details['name'] imwidth = weapon_details['imwidth'] imname = weapon_details['image'] wfrags = [ item for item in final_frag_list if (item[2] in weapons and item[3] == 0) ] if len(wfrags) == 0: continue ret = np.unique([item[0] for item in wfrags], return_counts=True) wfrags_permatch = [(ret[1][num] / final_KDA[ret[0][num]]['matches']) for num in range(len(ret[0]))] data = sorted(list(zip(ret[0], wfrags_permatch)), key=lambda x: x[1], reverse=True) pdf.set_font('Arial', 'B', 20) pdf.cell(w=cell_width * 2, h=2 * th, txt=text2put) pdf.cell(5) pdf.image(imname, w=imwidth * th) pdf.ln(th) pdf.set_font('Arial', 'B', 16) pdf.cell(w=cell_width * 2, h=2 * th, txt=data[0][0], align='R') pdf.set_text_color(r=76, g=153, b=0) pdf.cell(w=cell_width * 2, h=2 * th, txt='(%.1f Kills)' % data[0][1]) if len(data) > 1: pdf.cell(w=cell_width * 0.5) pdf.set_text_color(r=0, g=0, b=0) pdf.cell(w=cell_width * 2, h=2 * th, txt=data[1][0], align='R') pdf.set_text_color(r=76, g=153, b=0) pdf.cell(w=cell_width * 2, h=2 * th, txt='(%.1f Kills)' % data[1][1]) pdf.set_text_color(r=0, g=0, b=0) pdf.ln(3 * th) # Humiliation section starts here wfrags = [ item for item in final_frag_list if (item[2] == 'knife' and item[3] == 0) ] if len(wfrags) > 0: pdf.set_font('Arial', 'B', 20) pdf.cell(w=cell_width * 2, h=2 * th, txt='Humiliation') pdf.ln(2 * th) for frag in wfrags: pdf.set_font('Arial', 'B', 16) pdf.cell(w=cell_width * 2, h=2 * th, txt=frag[0], align='R') pdf.cell(3) pdf.set_text_color(r=255, g=0, b=0) pdf.cell(w=cell_width * 2, h=2 * th, txt='knifed', align='C') # pdf.image('images/knife.png', w=3*th) pdf.set_text_color(r=0, g=0, b=0) pdf.cell(5) pdf.cell(w=cell_width * 2, h=2 * th, txt=frag[1], align='L') pdf.ln(th) # KDA table starts here pdf.add_page() pdf.set_text_color(r=255, g=255, b=255) # HEADER pdf.set_font('Arial', 'B', 13) for itemno in range(len(header)): # Enter data in colums datum = header[itemno] if itemno == 0: pdf.set_fill_color(r=255, g=153, b=153) pdf.cell(cell_width * 2, 2 * th, str(datum), align='C', border=1, fill=True) pdf.set_fill_color(r=255, g=255, b=255) else: pdf.set_fill_color(r=255, g=153, b=153) pdf.cell(KDA_cell_width, 2 * th, str(datum), align='C', border=1, fill=True) pdf.set_fill_color(r=255, g=255, b=255) pdf.ln(2 * th) # CELLS pdf.set_font('Arial', 'B', 14) pdf.set_text_color(r=0, g=0, b=0) for row in KDA_data: for itemno in range(len(row)): # Enter data in columns datum = row[itemno] if datum == maxes[itemno - 1]: if itemno in [2, 3, 6, 7, 11]: set_color(pdf, bad=0) elif itemno in [5, 8]: set_color(pdf, bad=1) elif itemno in [9, 10]: set_color(pdf, bad=2) elif datum == mins[itemno - 1]: if itemno in [4, 5]: set_color(pdf, bad=0) elif itemno in [11]: set_color(pdf, bad=1) elif itemno in [9, 10]: set_color(pdf, bad=2) if itemno in [3, 5]: datum = '%.2f' % datum elif itemno in [9, 10, 11]: datum = '%.1f' % datum if itemno == 0: pdf.cell(cell_width * 2, 2 * th, str(datum), border=1, fill=True) else: pdf.cell(KDA_cell_width, 2 * th, str(datum), align='C', border=1, fill=True) reset(pdf) pdf.ln(2 * th) # pdf.add_page() pdf.set_text_color(r=0, g=0, b=0) # Pro plays section starts here if len(brownies) > 0: pdf.ln(3 * th) pdf.set_font('Arial', 'B', 20) pdf.cell(w=cell_width * 2, h=2 * th, txt='Pro plays') pdf.ln(2 * th) for brownie in brownies: pdf.set_font('Arial', 'B', 16) pdf.cell(w=cell_width * 2, h=2 * th, txt=brownie[0], align='L') pdf.cell(3) pdf.cell(w=cell_width * 2, h=2 * th, txt=brownie[1], align='C') pdf.cell(3) pdf.set_font('Arial', '', 14) pdf.cell(w=cell_width * 5, h=2 * th, txt=brownie[2], align='C') pdf.cell(3) pdf.cell(w=cell_width * 1, h=2 * th, txt=brownie[3], align='C') pdf.cell(3) pdf.cell(w=cell_width * 1, h=2 * th, txt='Round ' + str(brownie[4]), align='C') pdf.ln(2 * th) pdf.ln(th) pdf.output('Final_report.pdf', 'F')
# 0, # 25, # "Gender identity; most common words ", # border=0, # ln=1, # align="L", # fill=False, # ) pdf.image(my_path + my_image5, x=30, y=30, w=150, h=SIZE) # pdf.cell( # 0, # 210, # "Word frequency ", # border=0, # ln=1, # align="L", # fill=False, # ) pdf.image(my_path + my_image6, x=30, y=160, w=150, h=SIZE) pdf.add_page() pdf.image(my_path + my_image7, x=30, y=30, w=150, h=SIZE) pdf.output(my_path + "fgap_website_data_report.pdf", "F") print("All done")
def main(): df = pd.read_csv('reviews.csv') products = list(df.Item.value_counts().keys()) def cloudmaker(df, product): comment_words = '' stopwords = set(STOPWORDS) for val in df['Review']: val = str(val) # split the value tokens = val.split() # Converts each token into lowercase for i in range(len(tokens)): tokens[i] = tokens[i].lower() comment_words += " ".join(tokens) + " " wordcloud = WordCloud(width=1000, height=1000, max_words=100, stopwords=stopwords, min_font_size=10).generate(comment_words) plt.figure(figsize=(15, 15), facecolor=None) plt.imshow(wordcloud) plt.axis("off") plt.tight_layout(pad=0) plt.title(f'{product}') plt.savefig(f'{product}_cloud' + '.png') def review_pro(df, product): rates = df['Rating'].value_counts() plt.figure(figsize=(10, 10)) plt.bar(rates.index, rates.values, width=0.3) plt.title(f'Rating from users for {product}') plt.ylabel('Number of users', fontsize=12) plt.xlabel('Rating', fontsize=12) for i, rate in enumerate(list(rates.values)): plt.text(rates.index[i] - 0.10, rates.values[i] + 5, str(rate), color='blue') plt.savefig(f"{product}_review.png") pdf = FPDF() pdf.add_page() pdf.set_font("Times", size=25) pdf.cell(200, 10, txt='*' * 40, ln=1, align='C') pdf.cell(200, 10, txt='"Summary Report"', ln=1, align='C') pdf.cell(200, 10, txt='*' * 40, ln=1, align='C') pdf.set_font("Arial", size=15) for product in products: sub_df = df[df['Item'] == product] name = product.split()[:3] name = "_".join(name) mark = '=' * 50 pdf.cell(200, 10, txt=mark, ln=1, align='C') product = f'Product Name: {name}' pdf.cell(200, 10, txt=product, ln=1, align='C') review = f'Number of Reviews: {sub_df.shape[0]}' pdf.cell(200, 10, txt=review, ln=1, align='C') price = sub_df['Price'][:1].values[0] p = f'Price of {name} Rs.: {price}' pdf.cell(200, 10, txt=p, ln=1, align='C') rating = f'Average Rating :' + str(round(np.mean(sub_df['Rating']), 2)) pdf.cell(200, 10, txt=rating, ln=1, align='C') review_pro(sub_df, name) pdf.image(f'{name}_review.png', w=190, h=190, x=0) cloudmaker(sub_df, name) pdf.image(f'{name}_cloud.png', w=190, h=190) mark = '=' * 50 pdf.cell(200, 10, txt=mark, ln=1, align='C') pdf.output("Summary_report.pdf")
def begin_test(): global item_num_indx report_txt = "" #This will hold all the report test and post it to the test report textbox see how it works UUT = item_numbers[item_num_indx][0] report_txt += f"Testing a {UUT} \n" HALLS = item_numbers[item_num_indx][2] report_txt += f"Using {HALLS} Halls per Head\n" HEADS = item_numbers[item_num_indx][3] report_txt += f"With {HEADS} Heads\n" # Obtain test configuration for h in range(HALLS * HEADS): plotlegend.append("hall: "+ str(h)) GPIO.output(ENB, True) # Homing global pin5 while pin5 == 0: GPIO.output(STEP, GPIO.HIGH) sleep(delay) # need pulse for stepper motor controller to move GPIO.output(STEP, GPIO.LOW) pin5 = GPIO.input(5) # rapid move to starting GPIO.output(DIR, CCW) for s in range(500): GPIO.output(STEP, GPIO.HIGH) sleep(delay/10) GPIO.output(STEP, GPIO.LOW) # Read sesnors once to prime, or noise reduction, of the ADS1X15 sensor addressed_read_all_halls() # Noise Check for n in range(noise_readings): readings_table.append(addressed_read_all_halls()) # testing steps for s in range(1100-500): GPIO.output(STEP, GPIO.HIGH) sleep(delay/10) GPIO.output(STEP, GPIO.LOW) step = int(round(s/18,0)) # Write the test readings to the table readings_table.append(addressed_read_all_halls()) df = pd.DataFrame(readings_table) # Calculate noise - 1st derivitive noise_results = df.iloc[:noise_readings, 0:((HALLS * HEADS))].diff(axis=0, periods = 1).abs().max().to_frame() noise_results.columns = ['Noise'] noise_results["Halls"] = plotlegend # Dump noise result to a file? # noise_results.to_csv('noise_results.csv', sep=',') report_txt += str(noise_results) + "\n" result_txtbox.value = report_txt # return the plate back home GPIO.output(DIR, CW) for r in range(1100): GPIO.output(STEP, GPIO.HIGH) sleep(delay/10) GPIO.output(STEP, GPIO.LOW) step = int(60-round(r/18,0)) # Turn on the stepper motor controller GPIO.output(ENB, False) GPIO.cleanup() # Make the Counts chart plt.plot(readings_table) plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.xlabel('Steps') plt.ylabel('Counts') plt.savefig('Counts.png') # plt.show() # if you would like a window pop up # Make Noise Chart #https://www.tutorialspoint.com/how-to-create-a-matplotlib-bar-chart-with-a-threshold-line plt.rcParams["figure.figsize"] = [7.50, 3.50] # plt.rcParams["figure.autolayout"] = True threshold = item_numbers[item_num_indx][14] # 14 is the threshold a_threshold = np.maximum(noise_results["Noise"] - threshold, 0) b_threshold = np.minimum(noise_results["Noise"], threshold) x = range(HALLS * HEADS) fig, ax = plt.subplots() ax.bar(x, b_threshold, 0.35, color="green") ax.bar(x, a_threshold, 0.35, color="red", bottom=b_threshold) plt.axhline(threshold, color='red', ls='dotted') plt.savefig('Noise.png') # Now resize saved figures for the GUI # Create PDF report pdf = FPDF('P', 'mm', 'letter') pdf.add_page() pdf.image('EOLT_report.png', x = 0, y = 0, w = 203, h = 279, type = 'PNG') pdf.image('Noise.png', x = 0, y = 55, w = 97, h = 82, type = 'PNG') pdf.image('Counts.png', x = 100, y = 55, w = 97, h = 82, type = 'PNG') pdf.set_font('helvetica', 'B', 16) pdf.text(23, 40, '121250') pdf.text(23, 51.5, 'January 3, 2022') pdf.text(127, 40, 'B12345') pdf.text(127, 51.5, '01032022r12m3') #set font for results pdf.set_font('helvetica', size=10) # Creating an empty list rows = [] # Iterating through the columns of # dataframe results = noise_results[['Halls', 'Noise']] for column in results.columns: # Storing the rows of a column # into a temporary list li = results[column].tolist() # appending the temporary list rows.append(li) print(f"Rows {rows}") print("plot legend") print(plotlegend) print(f"second column in rows {rows[1]}") row_pos=200 #counter for which row in loop for row in (rows): pdf.text(10, row_pos,str(row)) print(row) row_pos += 5 # pdf.write(5, str(results)) pdf.output('tuto1.pdf', 'F')
def buscarOrganizacional(folder=''): print('Entrando a organizacional') archivos = [f for f in listdir(folder) if isfile(join(folder, f))] palabra = [ "CAPACIDAD DE ORGANIZACION", "capacidad de organizacion", "CAPACIDAD ORGANIZACIONAL", "Capacidad organizacional", "Capacidad Organizacional", 'INDICADORES DE CAPACIDAD ORGANIZACIONAL', "Indicadores de capacidad organizacional", "HABILITANTES ORGANIZACIONALES", "Habilitantes Organizacionales", "Habilitantes organizacionales", "Indices Financieros", "INDICES FINANCIEROS", "RENTABILIDAD DEL ACTIVO", "Rentabilidad del Activo", "Rentabilidad Del Activo" ] pytesseract.pytesseract.tesseract_cmd = r'/usr/local/Cellar/tesseract/4.1.0/bin/tesseract' ocurrencias = [] # Abrimos la imagen try: for x in archivos: ruta = folder + x try: if ruta.endswith('.jpg'): im = Image.open(ruta) # Utilizamos el método "image_to_string" # Le pasamos como argumento la imagen abierta con Pillow try: os.stat(folder + x.replace('.jpg', '') + ".txt") except Exception as e: print(e) texto = pytesseract.image_to_string(im) texto = unidecode.unidecode(texto) datafile = '' with open(folder + x.replace('.jpg', '') + ".txt", "w") as text_file: text_file.write(texto.encode().decode()) try: with open(folder + x.replace('.jpg', '') + ".txt", "r") as text_file: datafile = text_file.readlines() for i, line in enumerate(datafile): for d in palabra: if d in line: #Se utiliza el script buscarTablas para encontrar y extraer las tablas relacionadas encontrados = buscarTablas(ruta) #Los resultados se escanean con la libreria Pytesseract y se comprueba que lo encontrado es correcto for u in encontrados: texteando = pytesseract.image_to_string( u) texteando = unidecode.unidecode( texteando) #Si hay coincidencias se guarda el resultado en una imagen if any( i.isdigit() for i in texteando ) and "RENTABILIDAD " in texteando or "Rentabilidad " in texteando or "Rentabilidad " in texteando or 'Rentabilidad ' in texteando: os.rename( u, folder + r'Organizacional-' + str(i) + '.png') ocurrencias.append( folder + 'Organizacional-' + str(i) + '.png') i += 1 except Exception as e: print(e) except Exception as e: print(e) continue except Exception as e: print(e) pass dosocurrencias = [] #Como ultima alternativa, en caso de no encontrar cuadros con la informacion, se busca el texto y se extrae el texto relacionado if not ocurrencias: ocurrencias = buscarCoincidencias(palabra, 20, folder) p = 0 results = '' for j in ocurrencias: try: if 'RENTABILIDAD' in j or 'Rentabilidad' in j or 'rentabilidad' in j: fecha = ocurrencias[p:p + 10] results = fecha pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font('arial', 'B', 13.0) for i in results: pdf.write(5, str(i)) pdf.ln() pdf.output(folder + 'Organizacionales.pdf', 'F') pages = convert_from_path(folder + 'Organizacionales.pdf') paginas = [] u = 0 for page in pages: filename = "Organizacionales" + "-" + str(u) + '.png' page.save(folder + filename.replace('_', ' '), 'PNG') results.append(folder + filename.replace('_', ' ')) u = u + 1 return results except Exception as e: print(e) print('Aqui esta el error 2') continue p += 1 else: #En caso de haber repetidos resultados o resultados no relacionados, se eliminan para ahorrar analisis y espacio for i in ocurrencias: if os.path.exists(i) == False: ocurrencias.remove(i) for a in ocurrencias: for b in ocurrencias: try: if str(a) is not str(b) and os.path.exists( a) and os.path.exists(b): an = cv2.imread(a) bn = cv2.imread(b) an = cv2.resize(an, (500, 300)) bn = cv2.resize(bn, (500, 300)) difference = cv2.subtract(an, bn) result = not np.any(difference) if result is True: ocurrencias.remove(b) dosocurrencias.append(b) if os.stat(a).st_size < 100000: ocurrencias.remove(a) dosocurrencias.append(a) except Exception as e: print(e) continue for i in dosocurrencias: if (i in ocurrencias): dosocurrencias.remove(i) #Se eliminan errores y se devuelve la ruta con los resultados obtenidos for i in dosocurrencias: if (os.path.exists(i)): os.remove(os.path.abspath(i)) return ocurrencias #convertirPDF('/Users/andalval/Desktop/prueba datalicit/7. FONTIC FTIC-LP-03-2019/PLIEGO DEFINITIVO FTIC-LP-03-2019.pdf')
def buscarUNSPSC(folder=''): print('Entrando a UNSPSC') archivos = [f for f in listdir(folder) if isfile(join(folder, f))] palabra = [ "UNSPSC", "CODIGO UNSPSC", "SEGMENTO", "Segmento", "segmento", "Clasificacion UNSPSC", "CLASIFICACION UNSPSC" ] pytesseract.pytesseract.tesseract_cmd = r'/usr/local/Cellar/tesseract/4.1.0/bin/tesseract' ocurrencias = [] i = 0 # Abrimos la imagen for x in archivos: ruta = folder + x try: if '.jpg' in x: im = Image.open(ruta) # Utilizamos el método "image_to_string" # Le pasamos como argumento la imagen abierta con Pillow with open(folder + x.replace('.jpg', '') + ".txt", "r") as text_file: datafile = text_file.readlines() for i, line in enumerate(datafile): for d in palabra: if d in line: #Se utiliza el script buscarTablas para encontrar y extraer las tablas relacionadas encontrados = buscarTablas(ruta) #Los resultados se escanean con la libreria Pytesseract y se comprueba que lo encontrado es correcto for u in encontrados: texteando = pytesseract.image_to_string(u) texteando = unidecode.unidecode(texteando) #Si hay coincidencias se guarda el resultado en una imagen if any( i.isdigit() for i in texteando ) and "Servicios" in texteando or "Clasificacion" in texteando or 'FAMILIA' in texteando or 'Familia' in texteando: os.rename( u, folder + r'UNSPSC-' + str(i) + '.png') ocurrencias.append(folder + 'UNSPSC-' + str(i) + '.png') i += 1 except Exception as e: continue dosocurrencias = [] #En caso de haber repetidos resultados o resultados no relacionados, se eliminan para ahorrar analisis y espacio for a in ocurrencias: for b in ocurrencias: try: if str(a) is not str(b) and os.path.exists( a) and os.path.exists(b): an = cv2.imread(a) bn = cv2.imread(b) an = cv2.resize(an, (500, 300)) bn = cv2.resize(bn, (500, 300)) difference = cv2.subtract(an, bn) result = not np.any(difference) if result is True: ocurrencias.remove(b) dosocurrencias.append(b) if os.stat(a).st_size < 100000: ocurrencias.remove(a) dosocurrencias.append(a) except Exception as e: print(e) continue for i in dosocurrencias: if i in ocurrencias: dosocurrencias.remove(i) for i in dosocurrencias: if os.path.exists(i): os.remove(os.path.abspath(i)) #Como ultima alternativa, en caso de no encontrar cuadros con la informacion, se busca el texto y se extrae el texto relacionado if not ocurrencias: palabra = [ "UNSPSC", "CODIGO UNSPSC", "SEGMENTO", "Segmento", "segmento", "Clasificacion UNSPSC", "CLASIFICACION UNSPSC", "EXPERIENCIA GENERAL DEL PROPONENTE", "Experiencia general del proponente", "Experiencia del Proponente", "EXPERIENCIA DEL PROPONENTE" ] ocurrencias = buscarCoincidencias(palabra, 20, folder) p = 0 results = '' for j in ocurrencias: if 'UNSPSC' in j or 'Servicio' in j or 'CODIGO' in j or 'CODIGOS' in j: fecha = ocurrencias[p:p + 20] results = fecha pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font('arial', 'B', 13.0) for i in results: pdf.write(5, str(i)) pdf.ln() pdf.output(folder + 'UNSPSC.pdf', 'F') #Se toma cada pagina del PDF y se convierte en imagen con formato .jpg usando la libreria pdf2image pages = convert_from_path(folder + 'UNSPSC.pdf') paginas = [] u = 0 for page in pages: filename = "UNSPSC" + "-" + str(u) + '.png' page.save(folder + filename.replace('_', ' '), 'PNG') results.append(folder + filename.replace('_', ' ')) u = u + 1 return results p += 1 #Se eliminan errores y se devuelve la ruta con los resultados obtenidos for i in ocurrencias: if os.path.exists(i) == False: ocurrencias.remove(i) return ocurrencias
def generatePDF(self, widget_list, filename): # prints all opened signals and their spectrograms (if required) pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font("Arial", "B", 10) # Font settings titlesList = [] # stores the titles of open widgets yCord = 0 # Y-coordinate on the PDF page itr = 0 # To iterate on all the opened widgets to get their title for widget in widget_list: if itr not in self.deletedWinds: if widget.windowTitle().find("Time-FFT") == -1: titlesList.append(widget.windowTitle()) else: # We put an indicator on the spectrogram widgets to mark them if widget.windowTitle()[1] != "#": tempStr = widget.windowTitle()[13:] else: tempStr = widget.windowTitle()[12:] tempStr = tempStr + "x" titlesList.append(tempStr) itr += 1 titlesList.sort() for title in titlesList: windowIndx, _ = self.titleIndex(title) if title[-1] != "x": # The widgets are transformed into images to get inserted into the PDF graphPlot = self.graphDraw(self.signals[windowIndx - 1]) imgName = f"fileName{str(windowIndx)}.png" exporter = pg.exporters.ImageExporter(graphPlot.plotItem) exporter.parameters()["width"] = 250 exporter.parameters()["height"] = 250 exporter.export(imgName) title = title[2:] if title[1] == "#" else title[3:] pdf.cell(0, 10, txt=title, ln=1, align="C") # We change the index of the Y-Coordinate to insert the next image yCord = pdf.get_y() pdf.image( imgName, x=None, y=None, w=95, h=57, type="PNG", link="", ) os.remove(imgName) else: fig, _ = self.spectroDraw(self.signals[windowIndx - 1]) imgName = f".fileName{str(windowIndx + 99)}.png" fig.savefig(imgName) pdf.image( imgName, x=110, y=yCord - 2, w=95, h=60, type="PNG", link="", ) os.remove(imgName) pdf.output(filename)
class summaryClass: def __init__(self): from fpdf import FPDF self.pdf = FPDF() self.pdf.set_auto_page_break(False) self.currentRow = 0 self.claimCount = 1 self.database = db.database_class() def writeClaim(self, claim, diagCodes): self.database.insertAccession(claim.rowList[0]["ACCESSION_NUMBER"]) self.pdf.set_font('Arial', '', 8) self.pdf.set_xy(5, self.currentRow) self.pdf.line(5, self.currentRow, 280, self.currentRow) self.currentRow += 2 self.pdf.set_xy(5, self.currentRow) self.pdf.cell(5, 4, "[" + str(self.claimCount) + "]") self.pdf.set_xy(12, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["ACCESSION_NUMBER"])) self.pdf.set_xy(38, self.currentRow) #self.pdf.cell(5, 4, str(claim.rowList[0]["INSURANCE_PAYER_ID"])) self.pdf.set_xy(70, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["PATIENT_LAST"])) self.pdf.set_xy(88, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["PATIENT_FIRST"])) self.pdf.set_xy(110, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["PATIENT_DOB"])) self.pdf.set_xy(132, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["PATIENT_GENDER"])) self.pdf.set_xy(145, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["REFER_PHY_FIRST"])) self.pdf.set_xy(160, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["REFER_PHY_LAST"])) self.pdf.set_xy(190, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["REFER_PHY_NPI"])) self.pdf.set_xy(220, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["INSURANCE_PLAN_NAME"])) self.currentRow += 5 self.pdf.set_xy(70, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["PATIENT_STREET_ADDR"])) self.pdf.set_xy(220, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["INSURANCE_STREET_ADDR"])) self.currentRow += 5 self.pdf.set_xy(70, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["PATIENT_CITY"])) self.pdf.set_xy(105, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["PATIENT_STATE"])) self.pdf.set_xy(110, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["PATIENT_ZIP"])) self.pdf.set_xy(220, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["INSURANCE_CITY"])) self.pdf.set_xy(250, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["INSURANCE_STATE"])) self.pdf.set_xy(258, self.currentRow) self.pdf.cell(5, 4, str(claim.rowList[0]["INSURANCE_ZIP"])) self.currentRow += 5 self.pdf.line(5, self.currentRow, 280, self.currentRow) self.currentRow += 2 self.pdf.set_xy(15, self.currentRow) self.pdf.cell(5, 4, "Diagnosis Codes:") xPos = 40 for i in range(len(diagCodes)): self.pdf.set_xy(xPos, self.currentRow) self.pdf.cell(5, 4, diagCodes[i]) xPos += 15 self.currentRow += 5 self.pdf.set_xy(15, self.currentRow) self.pdf.cell(5, 4, "CPT Code") self.pdf.set_xy(35, self.currentRow) self.pdf.cell(5, 4, "EMG Code") self.pdf.set_xy(55, self.currentRow) self.pdf.cell(5, 4, "Price") self.currentRow += 5 self.pdf.line(5, self.currentRow, 280, self.currentRow) self.currentRow += 3 for row in claim.rowList: self.pdf.set_xy(15, self.currentRow) self.pdf.cell(5, 4, str(row["CPT"])) self.pdf.set_xy(35, self.currentRow) self.pdf.cell(5, 4, str(row["EMG"])) self.pdf.set_xy(55, self.currentRow) self.pdf.cell(5, 4, str(row["PRICE"])) self.currentRow += 5 if self.pdf.get_y() > 155: self.pdf.add_page("L") self.pdf.set_xy(5, 10) self.currentRow = 5 self.currentRow += 10 self.claimCount += 1 def writeMast(self): self.pdf.add_page("L") self.pdf.set_font('Arial', 'B', 10) self.pdf.set_xy(5, 0) self.pdf.cell(5, 10, 'Claim Summary - ') self.pdf.set_xy(12, self.currentRow + 10) self.pdf.set_font('Arial', '', 8) self.pdf.cell(5, 4, "Accession #") self.pdf.set_xy(38, self.currentRow + 10) self.pdf.cell(5, 4, "Sub ID") self.pdf.set_xy(70, self.currentRow + 10) self.pdf.cell(5, 4, "Pat. Last") self.pdf.set_xy(88, self.currentRow + 10) self.pdf.cell(5, 4, "Pat. First") self.pdf.set_xy(110, self.currentRow + 10) self.pdf.cell(5, 4, "DOB") self.pdf.set_xy(132, self.currentRow + 10) self.pdf.cell(5, 4, "Gender") self.pdf.set_xy(145, self.currentRow + 10) self.pdf.cell(5, 4, "Ref Phy") self.pdf.set_xy(190, self.currentRow + 10) self.pdf.cell(5, 4, "Ref Phy NPI") self.pdf.set_xy(220, self.currentRow + 10) self.pdf.cell(5, 4, "Insurance") self.currentRow = 20 self.pdf.set_font('Arial', '', 10) def writePDF(self): self.pdf.output('claimSummary.pdf', 'F')
def convertirPDF(path=''): pathb = os.path.dirname(path) + '/' + os.path.basename(path) folder = os.path.dirname(pathb) carpeta = folder + '/' + os.path.splitext(os.path.basename(pathb))[0] pages = convert_from_path(pathb.replace('_', ' ')) i = 0 paginas = [] try: if (os.stat(carpeta + '/Finales.jpg')): os.remove(carpeta + '/Finales.jpg') if (os.stat(carpeta + '/Finales.txt')): os.remove(carpeta + '/Finales.txt') if (os.stat(carpeta + '/Finales.pdf')): os.remove(carpeta + '/Finales.pdf') except: pass #Se crea una carpeta con el nombre del archivo PDF try: os.stat(carpeta) except: os.mkdir(carpeta) #Se toma cada pagina del PDF y se convierte en imagen con formato .jpg usando la libreria pdf2image for page in pages: filename = carpeta.replace('_', ' ') + '/' + os.path.splitext( os.path.basename(pathb))[0].replace('_', ' ') + "-" + str(i) + '.jpg' page.save(filename, 'JPEG') paginas.append(filename.replace('_', ' ')) i = i + 1 #Se toma cada imagen generada y se extrae su texto usando reconocimiento optico de caracteres OCR for j in paginas: im = Image.open(j.replace('_', ' ')) try: os.stat(j.replace(".jpg", "") + ".txt") except FileNotFoundError as e: texto = pytesseract.image_to_string(im) texto = unidecode.unidecode(texto) datafile = '' with open(j.replace(".jpg", "").replace('_', ' ') + ".txt", "w") as text_file: text_file.write(texto) continue #Se envia la ruta de los archivos de texto generados para buscar los datos en cada metodo. Al final todos los resultados #se guardan en un PDF relacionado con los datos extraidos. finales = buscarUNSPSC(carpeta + '/') unspsc = list(dict.fromkeys(finales)) pdf = FPDF() try: for a in unspsc: pdf.add_page('L') pdf.image(a, 0, 0, 300, 200) pdf.output(carpeta + '/UNSPSC.pdf') except: pass finales = buscarFinanciera(carpeta + '/') financieros = list(dict.fromkeys(finales)) if not financieros: print('Datos financieros no encontrados') else: try: pdf = FPDF() for a in financieros: pdf.add_page('L') pdf.image(a, 0, 0, 300, 200) pdf.output(carpeta + '/Financieros.pdf') except Exception as e: print(e) try: finales = buscarOrganizacional(carpeta + '/') organizacionales = list(dict.fromkeys(finales)) if not organizacionales: print('Datos organizacionales no encontrados') else: try: pdf = FPDF() for a in organizacionales: pdf.add_page('L') pdf.image(a, 0, 0, 300, 200) pdf.output(carpeta + '/Organizacionales.pdf') except Exception as e: print(e) pass except Exception as e: print(e) print("Datos organizacionales no encontrados") #Una vez encontrados los datos, las tablas extraidas se concatenan en un solo archivo de imagen para ser devuelto try: onlyfiles = [f for f in listdir(carpeta) if isfile(join(carpeta, f))] imagenes = [] for j in onlyfiles: if j.endswith('.png'): imagenes.append(carpeta + '/' + j) imgs = [Image.open(i) for i in imagenes] min_img_width = min(i.width for i in imgs) total_height = 0 for i, img in enumerate(imgs): # If the image is larger than the minimum width, resize it if img.width > min_img_width: imgs[i] = img.resize( (min_img_width, int( img.height / img.width * min_img_width)), Image.ANTIALIAS) total_height += imgs[i].height # I have picked the mode of the first image to be generic. You may have other ideas # Now that we know the total height of all of the resized images, we know the height of our final image img_merge = Image.new(imgs[0].mode, (min_img_width, total_height)) y = 0 for img in imgs: img_merge.paste(img, (0, y)) y += img.height img_merge.save(carpeta + '/Finales.jpg') #Adicionalmente, se guardan los resultados en un PDF para mejor usabilidad merger = PdfFileMerger() try: merger.append(PdfFileReader(carpeta + '/UNSPSC.pdf')) except: pass try: merger.append(PdfFileReader(carpeta + '/Financieros.pdf')) except: pass try: merger.append(PdfFileReader(carpeta + '/Organizacionales.pdf')) except: pass merger.write(carpeta + '/Finales.pdf') merger.close() #Finalmente, se devuelve la ruta del archivo de imagen con los resultados return os.path.abspath(carpeta + '/Finales.jpg') except Exception as e: print(e)
from fpdf import FPDF import fpdf import os from PIL import Image image_list = [str(i + 1) + ".jpg" for i in range(179)] pdf = FPDF('P', "in", (5, 7.5)) for image in image_list: cover = Image.open(image) width, height = cover.size width, height = float(width * 0.264583 / 25.4), float(height * 0.264583 / 25.4) if image == "5.jpg": pdf.add_page('L') pdf.image(image, 0, 0, 7.5, 5) else: pdf.add_page('P') pdf.image(image, 0, 0, 5, 7.5) pdf.output("test1.pdf", "F")