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)
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 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 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 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 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 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 get(self): pdf=FPDF() pdf.add_page() pdf.add_font('DejaVu','','font/DejaVuSansCondensed.ttf',uni=True) pdf.set_font('DejaVu','',16) #pdf.set_font('Arial','B',16) pdf.cell(40,10,u'Hello World! Здравствуй мир') pdf.image('images/LoadFile.png', 0, 50) self.response.headers['Content-Type'] = 'application/pdf' self.response.write(pdf.output('', 'S'))
def gen_pdf_from_image_list(self, image_list): page_size = self.layout.page_size page_type = page_size.page_size_type page_width = page_size.width_mm pdf = FPDF(orientation='P', unit='mm', format=page_type) for image_path in image_list: pdf.add_page() pdf.image(image_path, 0, 0, page_width) self.pdf_path = self.layout.get_pdf_path() pdf.output(name=self.pdf_path) print 'Output PDF: %s' % self.pdf_path
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() for i in range(1,41): # for flow mode, do not pass x or y: pdf.image(os.path.join(common.basepath, '../tutorial/logo_pb.png')) pdf.output(outputname, 'F')
def label(self, serial, f_list, username, old, new): pdf = FPDF(format=(80,24)) pdf.add_page() # put barcode here self.create_barcode(serial) pdf.image('barcode.png', 0, 0, h=24) # barcodes print out with height of 280px. #pdf.add_page() #pdf.set_font('Times','',14) #pdf.cell(30, 22, serial) pdf.output('barcodes/' + serial + '.pdf') self.print_barcode('barcodes/' + serial + '.pdf')
def dotest(outputname, nostamp): # Portrait, millimeter units, A4 page size pdf = FPDF("P", "mm", "A4") if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) # Set font: Times, normal, size 10 pdf.add_page() if not nostamp: # do not show picture in batch url = "http://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Code_3_of_9.svg/262px-Code_3_of_9.svg.png" pdf.image(url, 10, 10) pdf.code39("*wikipedia*", 12.75, 7, 1.49) pdf.output(outputname, 'F')
def make_pdf(_livro): print('convertendo para PDF...') from fpdf import FPDF from PIL import Image import glob list_pages = sorted(glob.glob('*.jpg')) cover = Image.open(str(list_pages[0])) width, height = cover.size pdf = FPDF(unit='pt', format=[width, height]) for page in list_pages: pdf.add_page() pdf.image(str(page), 0, 0) pdf.output('%s.pdf' % _livro, 'F') for page in list_pages: os.remove(page)
def generar_codigos(request): values = {} form = GeneratorForm() if request.method == 'POST': form = GeneratorForm(request.POST) if form.is_valid(): #os.chmod(os.path.join('generated','temp'),755) cantidad = int(form.cleaned_data['cantidad']) provincia = form.cleaned_data['codigo_provincia'] ciudad = form.cleaned_data['codigo_ciudad'] numeroInicial = int(form.cleaned_data['numero_inicial']) total_imagenes = int(cantidad) * 2 paginas = calcular_cantidad_paginas(total_imagenes) archivo = FPDF('P','mm','A4') archivo.add_page() os.remove(os.path.join('/tmp','NIF','generated','codigos.pdf')) os.makedirs(os.path.join('/tmp','NIF','generated','temp')) 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('/tmp','NIF','generated','codigos.pdf'),'F') shutil.rmtree(os.path.join('/tmp','NIF','generated','temp')) #shutil.copy(os.path.join('/tmp','NIF','generated','codigos.pdf'),os.path.join('/var','django','spid','generated','codigos.pdf')) return HttpResponseRedirect(reverse('descargar')) else: values['error'] = 'Error en el formulario vuelva a intentarlo' values['form'] = form else: values['error'] = 'Error en el formulario vuelva a intentarlo' values['form'] = form return render_to_response('./index_nif.html',values,context_instance=RequestContext(request))
def on_bimprimirrepuestos_clicked(self, widgets): listarep = self.interface.get_object("listarep") recorrer = listarep.get_iter_first() pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", "B", size=16) pdf.cell(110, 10, "Listado de repuestos", 0, 0) pdf.cell(25, 10, "Talleres cuspedrinos", 0, 1) pdf.cell(110, 10, "", 0, 0) pdf.cell(25, 10, "Tel. 555555555", 0, 1) pdf.cell(110, 10, " ", 0, 0) now = datetime.datetime.now() fecha = now.strftime("%Y-%m-%d %H:%M") pdf.cell(25, 10, str(fecha), 0, 1) pdf.image('/home/daniel/workspace/taller/img/tallerlogo.jpg', x=70, y=2, w=40, h=50, type='jpg') columnas = ["Cod", "Nombre", "Descripcion", "Stock", "Precio"] cont = 0; for col in columnas: if cont == 0: pdf.cell(12, 10, col, 1, 0, "C") else: if cont == 1: pdf.cell(50, 10, col, 1, 0, "C") else: if cont == 2: pdf.cell(100, 10, col, 1, 0, "C") else: pdf.set_font("Helvetica", "B", size=14) pdf.cell(15, 10, col, 1, 0, "C") cont = cont + 1; pdf.ln() pdf.set_font("Helvetica", size=12) while recorrer != None: cod = str(listarep.get_value(recorrer, 2)) nombre = listarep.get_value(recorrer, 0) descripcion = listarep.get_value(recorrer, 1) stock = str(listarep.get_value(recorrer, 4)) precio = str(listarep.get_value(recorrer, 3)) pdf.cell(12, 10, cod, 1, 0, "R") pdf.cell(50, 10, nombre, 1, 0, "L") pdf.cell(100, 10, descripcion, 1, 0, "L") pdf.cell(15, 10, stock, 1, 0, "R") pdf.cell(15, 10, precio, 1, 0, "R") pdf.ln() recorrer = listarep.iter_next(recorrer) lista = "/home/daniel/workspace/taller/listas/listarepuestos.pdf" pdf.output(lista, "F") os.system('/usr/bin/evince ' + str(lista) + ' &')
def label_with_info(self, serial, f_list, username, old, new): pdf = FPDF(format=(80,65), unit='mm') pdf.add_page() # put barcode here self.create_barcode(serial) pdf.image('barcode.png', x=0, y=0, h=30) # barcodes print out with height of 280px. pdf.set_font('Arial', '', 12) pdf.ln(21) pdf.cell(21, 4, "Added " + time.strftime("%c"),0,2) pdf.cell(80, 4, "Created: " + old,0,2) pdf.cell(80, 4, "Modified: " + new,0,2) #pdf.set_font('Arial', '', 12) #pdf.cell(30, 10, "created: " + old + ", modified: " + new, ln=1) pdf.output('barcodes/label.pdf') self.print_barcode('barcodes/label.pdf')
def group_label(self, group_id, name, location, notes): pdf = FPDF(format=(80,65), unit='mm') pdf.set_margins(5, 5) pdf.add_page() self.create_barcode(group_id) pdf.image('barcode.png', x=0, y=0, h=30) pdf.set_font('Arial', '', 14) pdf.cell(30) pdf.cell(40,0, location, 0, 2) pdf.ln(10) pdf.cell(30) pdf.cell(21, 4, str(group_id) + ": " + name, 0, 1) pdf.ln(10) pdf.set_font('Arial', '', 8) pdf.multi_cell(0, 5, notes, 0, 2) pdf.output('barcodes/group_label.pdf') self.print_barcode('barcodes/group_label.pdf')
def listarImprimir(request): lineas = TOTAL_LINEAS_PDF fecha = datetime.date.today() now = datetime.datetime.now() nombre = "Carta_Boru_"+str(fecha)+'.pdf' pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'BU', 25) pdf.image(RUTA_PROYECTO + "\\" + STATIC_URL + "img\\boru_logo_pdf.png", 13, 13, 52, 23, type='PNG') pdf.cell(0, 30, 'Carta Boru', 0, 1, 'C') pdf.ln(10) lineas = lineas - 4 secciones = SeccionCarta.objects.filter().order_by("categoria") for seccion in secciones: if not seccion.es_vacia_seccion(): if (lineas - 3) <= 0: pdf.add_page() lineas = TOTAL_LINEAS_PDF lineas = lineas - 3 pdf.set_font('Arial', 'UB', 20) pdf.cell(0, 10, str(seccion.nombre).capitalize(), 0, 1, 'L') pdf.ln() productos = seccion.dame_productos() for p in productos: if p.activo ==True: if (lineas - 2) <= 0: pdf.add_page() lineas = TOTAL_LINEAS_PDF - 3 pdf.set_font('Arial', 'UB', 20) pdf.cell(0, 10, str(seccion.nombre).capitalize(), 0, 1, 'L') pdf.ln() lineas= lineas -2 pdf.set_font('Arial', 'B', 16) pdf.cell(75, 10, str(p.nombre).capitalize(), 0, 0) pdf.set_font('Arial', 'B', 16) pdf.cell(90, 10, "........................................................", 0, 0, "L") pdf.set_font('Arial', 'B', 16) pdf.cell(25, 10, '$' + str(p.importe()), 0, 0, "L") pdf.ln() pdf.ln() lineas = lineas -1 return HttpResponse(pdf.output(name=nombre,dest='S'),content_type='application/pdf')
def dotest(outputname, nostamp): plane = genbar() palette = (0,0,0, 255,255,255) + (128,128,128)*254 try: img = Image.frombytes("P", plane.size, plane.tobytes()) except AttributeError: # note: https://github.com/python-pillow/Pillow/issues/63 img = Image.fromstring("P", plane.size, plane.tostring()) img.putpalette(palette) with tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") as f: gif1 = f.name with tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") as f: gif2 = f.name img.save(gif1, "GIF", optimize = 0) img.save(gif2, "GIF", transparency = 1, optimize = 0) pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) 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) pdf.output(outputname, 'F') os.unlink(gif1) os.unlink(gif2)
def on_bimprimirclientes_clicked(self, widgets): listaclientes = self.interface.get_object("lista") recorrer = listaclientes.get_iter_first() pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", "B", size=16) pdf.cell(110, 10, "Listado de clientes", 0, 0) pdf.cell(25, 10, "Talleres cuspedrinos", 0, 1) pdf.cell(110, 10, "", 0, 0) pdf.cell(25, 10, "Tel. 555555555", 0, 1) pdf.cell(110, 10, " ", 0, 0) now = datetime.datetime.now() fecha = now.strftime("%Y-%m-%d %H:%M") pdf.cell(25, 10, str(fecha), 0, 1) pdf.image('/home/daniel/workspace/taller/img/tallerlogo.jpg', x=70, y=2, w=40, h=50, type='jpg') columnas = ["Cod", "Nombre", "NIF", "Telefono"] cont = 0; for col in columnas: if cont == 0: pdf.cell(20, 10, col, 1, 0, "C") else: if cont == 1: pdf.cell(100, 10, col, 1, 0, "C") else: pdf.cell(35, 10, col, 1, 0, "C") cont = cont + 1; pdf.ln() pdf.set_font("Helvetica", size=14) while recorrer != None: cod = str(listaclientes.get_value(recorrer, 0)) nombre = listaclientes.get_value(recorrer, 1) + " " + listaclientes.get_value(recorrer, 2) dni = listaclientes.get_value(recorrer, 3) telefono = listaclientes.get_value(recorrer, 9) pdf.cell(20, 10, cod, 1, 0, "R") pdf.cell(100, 10, nombre, 1, 0, "L") pdf.cell(35, 10, dni, 1, 0, "R") pdf.cell(35, 10, telefono, 1, 0, "R") pdf.ln() recorrer = listaclientes.iter_next(recorrer) lista = "/home/daniel/workspace/taller/listas/listaclientes.pdf" pdf.output(lista, "F") os.system('/usr/bin/evince ' + str(lista) + ' &')
def dotest(outputname, nostamp): plane = genbar() palette = (0,0,0, 255,255,255) + (128,128,128)*254 img = Image.fromstring("P", plane.size, plane.tostring()) img.putpalette(palette) f = tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") gif1 = f.name f.close() f = tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") gif2 = f.name f.close() img.save(gif1, "GIF") img.save(gif2, "GIF", transparency = 1) pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) 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) pdf.output(outputname, 'F') os.unlink(gif1) os.unlink(gif2)
def get_file(self, url): position_link = 0 if url.find('slideshare.net')>position_link: d = Download(url) imgs = d.get_tags('img', 'class', 'slide_image') if imgs != 'error': links = d.get_urls('slideshare', imgs, 'data-full') pdf = FPDF('P', 'pt', 'Letter') index_cache = 0 index_link = 0 print "\nDownload images [",len(links),"]:\n" for pagina_pdf in links: file_path=urlretrieve(pagina_pdf.split('?')[index_link])[index_cache] print " ", pagina_pdf img=Image.open(file_path) pdf.add_page(format = img.size) pdf.image(file_path, x=0, y=0) pdf.output('slideshare.pdf', 'F') print 'se genero en archivo slideshare.pdf' else: print 'link de slideshare no hace referencia a un archivo valido' else: print 'link de slideshare no es valido'
def dotest(outputname, nostamp): pdf = FPDF(orientation = "L", unit = "in") if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() img_path = os.path.join(common.basepath, '../tutorial/logo.png') img = Image.open(img_path) w, h = img.size width = 8 height = width * (h // w) with tempfile.NamedTemporaryFile(delete = False, suffix = ".png") as f: img_new = f.name # convert to RGBA img2 = img.convert(mode = "RGBA") img2.save(img_new) # create pdf pdf.image(img_new, x = 1, y = 1, w = width, h = height) pdf.output(outputname, 'F')
def generate_pdf(card): """ Make a PDF from a card :param card: dict from fetcher.py :return: Binary PDF buffer """ from eclaire.base import SPECIAL_LABELS pdf = FPDF('L', 'mm', (62, 140)) pdf.set_margins(2.8, 2.8, 2.8) pdf.set_auto_page_break(False, margin=0) pdf.add_page() font = pkg_resources.resource_filename('eclaire', 'font/Clairifont.ttf') pdf.add_font('Clairifont', fname=font, uni=True) pdf.set_font('Clairifont', size=48) pdf.multi_cell(0, 18, txt=card.name.upper(), align='L') qrcode = generate_qr_code(card.url) qrcode_file = mktemp(suffix='.png', prefix='trello_qr_') qrcode.save(qrcode_file) pdf.image(qrcode_file, 118, 35, 20, 20) os.unlink(qrcode_file) # May we never speak of this again. pdf.set_fill_color(255, 255, 255) pdf.rect(0, 55, 140, 20, 'F') pdf.set_font('Clairifont', '', 16) pdf.set_y(-4) labels = ', '.join([label.name for label in card.labels if label.name not in SPECIAL_LABELS]) pdf.multi_cell(0, 0, labels, 0, 'R') return pdf.output(dest='S')
def print_file(title, data): (f, fname) = tempfile.mkstemp(text=True) pdf = FPDF('L', unit='mm', format=(112, 100)) pdf.add_page() pdf.set_font('Arial', '', 8) pdf.cell(0, 10, data['newTicketTime'], 0, 1) pdf.ln() pdf.ln() pdf.set_font('Arial', 'B', 128) pdf.cell(0, 10, data['newTicketValue'], 0, 1, 'C') pdf.set_font('Arial', '', 18) pdf.ln() pdf.cell(0, 10, data['description'].encode('cp1252', 'ignore'), 0, 1, 'C') qr = qrcode.QRCode(box_size=3) link = 'http://q.foi.hr/view?id=' + str(data['id']) qr.add_data(link) qr.make(fit=True) img = qr.make_image() (qf, qfname) = tempfile.mkstemp(suffix='.png') img.save(qfname, 'PNG') pdf.image(qfname) pdf.set_font('Arial', '', 10) pdf.text(47, 87, link) pdf.output(fname) job = CUPS.printFile(PRINTER_NAME, fname, title, {}) while job in CUPS.getJobs(which_jobs='not-completed').keys(): time.sleep(2) os.unlink(fname) os.unlink(qfname)
def main(): os.chdir(get_path()) image_ending = '.jpg' pdf = FPDF() h_im = 2338. w_im = 1700. ratio = h_im/w_im w = 215 #w = 210 h = w*ratio file_list = os.listdir(os.getcwd()) file_list = sorted(file_list) out_name = '' for e in file_list: if image_ending in e.lower(): pdf.add_page() if len(out_name)==0: out_name = e #pdf.set_font('Arial', '8', 16) #pdf.cell(40,10,'Hello World!') print e #im = Image.open(e) #pdf.image(im, 0, 0, 100, 100) #pdf.image(e, 0, 0, 100, 100) pdf.image(e,0,0,w,h) #conv(e) out_name = out_name.split('.')[0]+'.pdf' pdf.output(out_name, 'F')
def heterozygosity(het_dataframe, thresh, minThresh, outDir): pdf = FPDF() # create new PDF pdf.add_page() pdf.set_margins(20, 10, 20) pdf.set_font('Arial', 'B', 24) pdf.set_x(20) pdf.multi_cell(0, 30, "Heterozygosity", 0, 1, 'L') pdf.line(20, 32, 190, 32) sample_fails = open(outDir + '/samples_failing_heterozygosity.txt', 'w') fail_het = het_dataframe.loc[((het_dataframe['F'] > thresh) | (het_dataframe['F'] < minThresh))] fail_het[['FID', 'IID']].to_csv(sample_fails.name, sep='\t', index=False, header=False) # format it FID <tab> IID <new line> # sorts inbreeing coeffiecient score to rank for ploting het_dataframe.sort_values(by='F', ascending=True, axis=0, inplace=True) het_dataframe = het_dataframe.reset_index() het_dataframe['rank'] = het_dataframe.index pdf.set_font('Arial', '', 12) pdf.multi_cell(0, 5, 'Heterozygosity is calculated on the merged sample space. Samples with extreme levels of heterozygosity as measured by \ the F inbreeding coefficient, may be indicative of a sample exhibiting poor quality. The current inbreeding coefficient threshold is set \ to ' + str(thresh) + '. Any F value above this threshold is filtered out.', 0, 1, 'J') pdf.multi_cell(0, 5, '\n', 0, 1, 'J') pdf.set_font('Arial', 'B', 16) pdf.set_fill_color(200) pdf.multi_cell(0, 8, 'Total Number Samples Analyed: '+ str(len(het_dataframe.index)), 1, 'L', True) pdf.set_x(30) pdf.multi_cell(0, 8, 'Total Number Samples Failing: '+ str(len(fail_het.index)), 1, 1, 'L') het_dataframe.plot(kind='scatter', x='rank', y='F', title='Ranked Inbreeding Coefficient scores', s=7) plt.tight_layout(pad=2, w_pad=2, h_pad=2) plt.savefig(outDir+'/'+'heterozygosity_plot.png') plt.close() pdf.image(outDir+'/'+'heterozygosity_plot.png', x=10, y=130, w=190, h=150) return sample_fails.name, pdf
def pdf(country, coin): pdf = FPDF('P', 'mm', 'A4') pdf.add_page() pdf.set_font('Arial', 'B', 16) pdf.text(10, 10, "WORLD SUICIDE RATES") pdf.set_font('Arial', 'B', 12) wi = 10 pdf.text(10, 10 + wi, ( f"The average suicide rate in {country} is {getSumSuicidesByCountry(country)} suicides/year with a gbp per capita = {gbpPerCapitaAverage(coin,country)} {coin}" )) pdf.image("../OUTPUT/GBPPerCapita.jpg", 20, 90, w=120, h=200) pdf.text(10, 10 + 2 * wi, ( f'The age range with the highest suicide rate in {country} is the range between {ageMaxSuicides(country)[0]}' )) pdf.text( 10, 10 + 3 * wi, (f' with {ageMaxSuicides(country)[1]} suicides from 1985 to 2016')) pdf.text(10, 10 + 4 * wi, ( f'The age range with the lowest suicide rate in {country} is the range between {ageMinSuicides(country)[0]} with {ageMinSuicides(country)[1]}' )) pdf.text(10, 10 + 5 * wi, (f'suicides from 1985 to 2016')) pdf.text(10, 10 + 6 * wi, ( f'The country in the world with the most number of suicides per 100k is {suicidesCountry100kMax()[0]} ' )) pdf.text(10, 10 + 7 * wi, (f'with a {suicidesCountry100kMax()[1]} suicides')) pdf.text(10, 10 + 8 * wi, ( f'The country in the world with the lowest number of suicides per 100k is ' )) pdf.text(10, 10 + 9 * wi, ( f' {suicidesCountry100kMin()} with a {suicidesCountry100kMin()[1]} suicides' )) pdf.add_page() pdf.image("../OUTPUT/suicideRateByCountry.jpg", 10, 50, h=90) return pdf.output('../OUTPUT/PDF.pdf', "F")
def make_pdf(self): with open(self.fd + "/" + "_desc.json", "r") as js: self.mdic = json.load(js) pdf = FPDF() for k, v in self.mdic.items(): vtit = (v[1][1]) vid = (v[0][1]) vdes = (v[2][1]) print(vtit) pdf.add_page() pdf.image('logo.png', 10, 8, 33, 0, '', 'http://www.redandgreen.co.uk') image_path = (self.fd + "/" + vid + ".jpg") pdf.image(image_path, 10, 30, 190, 0, '', "http://www.youtube.com/watch?v=" + vid) pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True) pdf.set_font('DejaVu', '', 14) pdf.cell(180, 15, txt="http://www.youtube.com/watch?v=" + vid, ln=1, align="L") pdf.cell(30, txt="{}".format(vtit), ln=1, align="L") pdf.ln(165) # comment out if error pdf.multi_cell(w=0, h=4, txt=vdes) # comment out if error for i in tqdm(range(20)): pdf.output(self.pdfname, 'F') time.sleep(0.5) print("All done, please check root folder for output.pdf")
class Pdfiy: def __init__(self, name): self.name = name self.pdf = FPDF() def create_pdf(self): self.pdf.add_page() self.pdf.image("source/export/pages/1.png", 0, 0, w=210, h=297) self.pdf.add_page() self.pdf.image("source/export/pages/2.png", 0, 0, w=210, h=297) self.pdf.add_page() self.pdf.image("source/export/pages/3.png", 0, 0, w=210, h=297) self.pdf.add_page() self.pdf.image("source/export/pages/4.png", 0, 0, w=210, h=297) def save_pdf(self): self.pdf.output('source/export/pdf/' + self.name + '.pdf', 'F')
def img2pdf(self, pth, filename): try: res_pdf_path = pth.replace("files", "converted") im = Image.open(pth) width, height = im.size if height >= width: orientation = 'P' w = 210 h = 297 else: orientation = 'L' w = 297 h = 210 pdf = FPDF() pdf.add_page(orientation=orientation) pdf.image(pth, x=0, y=0, w=w, h=h) pdf.output(res_pdf_path, "F") res = open(res_pdf_path, 'rb') if not filename.endswith('.pdf'): filename = filename + '.pdf' self.pdf_doc.save(filename, DjangoFile(res)) except: raise
def converting_to_pdf(path, pack_of_news): symbol = ':' pdf = FPDF() pdf.add_font('DejaVuSans', '', 'DejaVuSans.ttf', uni=True) pdf.set_font("DejaVuSans") pdf.add_page() if not os.path.exists(path): os.makedirs(path) getting_images(path, pack_of_news) for item in pack_of_news: name_by_date = item.time_of_novelty.replace(symbol, '') directory = checking_path() file_name = path.joinpath(Path(directory + name_by_date + '.jpg')) pdf.set_text_color(0, 0, 0) pdf.write( 10, str(item.number_of_novelty) + ". " + item.title_of_novelty + "\n") try: pdf.image(str(file_name), w=140, h=100) except RuntimeError: pdf.write("NO IMAGE, BUT LINK: " + item.images_links + "\n") pdf.write(5, "ALT TEXT: " + item.alt_text + "\n") pdf.write(10, "PUBLISHED: " + item.time_of_novelty + "\n") pdf.write(7, "SOURCE LINK: " + item.source_link + "\n\n") pdf.set_text_color(0, 0, 255) pdf.write(6, "DESCRIPTION: " + item.description + "\n") pdf.set_text_color(0, 0, 0) pdf.write(7, "\nIMAGES LINKS: " + item.images_links + "\n") pdf.write(6, "MAIN SOURCE LINK: " + item.main_source + "\n") try: pdf.output((path.joinpath(Path('News.pdf')))) # Create pdf in path except PermissionError: print("Something wrong with your path in pdf!") except FileNotFoundError: print("You entered wrong path!")
def build_report(self): pdf = FPDF('L') pdf.add_page() pdf.image(self.graph_local_path, x=158.5, y=40, w=119, h=119) font_family = fonts.get_font_family() font_path = fonts.get_font_path() pdf.add_font(font_family, '', font_path, uni=True) pdf.set_right_margin(148.5) organizer_name = members.user_id_to_user_name(self.slack_client, self.organizer_id) title = 'Game set up by {}'.format(organizer_name) pdf.set_font(font_family, '', 14) pdf.write(8, title) pdf.write(8, '\n\n') pdf.set_font(font_family, '', 24) pdf.write(11, self.question) pdf.write(11, '\n\n') pdf.set_font(font_family, '', 14) msg = [ 'Truth: {}'.format(self.truth), self.build_signed_guesses_msg('pdf'), self.build_conclusion_msg('pdf') ] msg = '\n\n'.join(msg) pdf.write(8, msg) pdf.output(self.report_local_path, 'F')
def write_to_fpdf(input_folder, output_file_path, image_file): """ Convert to the TIF to PDF :param input_folder: Working folder :param output_file_path: Where we write to :param image_file: The active image file being processed :return: Nothing """ pdf = FPDF() pdf.set_auto_page_break(0) image_file_path = input_folder + os.path.sep + image_file cover = Image.open(image_file_path) width, height = cover.size # convert pixel in mm with 1px=0.264583 mm width, height = float(width * 0.264583), float(height * 0.264583) # given we are working with A4 format size pdf_size = {'P': {'w': 210, 'h': 297}, 'L': {'w': 297, 'h': 210}} # get page orientation from image size orientation = 'P' if width < height else 'L' # make sure image size is not greater than the pdf format size width = width if width < pdf_size[orientation]['w'] else pdf_size[ orientation]['w'] height = height if height < pdf_size[orientation]['h'] else pdf_size[ orientation]['h'] pdf.add_page(orientation=orientation) pdf.image(image_file_path, 0, 0, width, height) pdf.output(output_file_path, "F")
def imprimir_etiquetas_cajas(pallobj, articuloobj, usuario): ETIQUETA_DIR = '%s/label_files_cajas' % PROJECT_ROOT ahora = datetime.datetime.now() pdf=FPDF('L','cm',(10, 12.5)) pdf.add_page() pdf.set_font('Arial',style='',size=6) pdf.set_y(1) pdf.set_x(0.6) pdf.cell(1, 0, 'ARTICULO: %s - %s' % (articuloobj.articulocod, articuloobj.articulo_descripcion), align='L') pdf.set_y(1.5) pdf.set_x(0.6) pdf.cell(1, 0, 'LOTE: %s UNIDADES: %s' % (pallobj.articulo_lote, pallobj.articulo_unidades_x_pall), align='L') pdf.set_y(1.8) pdf.set_x(0.6) #linea pdf.line(0.5, 2, 11.5, 2) #seccion producto barra_articulo = Code128Encoder('%s|%s' % (articuloobj.codigo_barra_caja, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d')), options={'height':60, 'label_border': 1, 'bottom_border': 5}) barra_articulo.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), bar_width=1) pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), x=0.8, y=2.1) pdf.line(0.5, 4.5, 11.5, 4.5) pdf.set_y(4.7) pdf.set_x(0.5) pdf.cell(1, 0, 'BODEGA: %s HORA: %s FECHA: %s IMPRESO POR: %s' % (pallobj.bodega, ahora.strftime('%H:%M:%S'), ahora.strftime('%d/%m/%Y'), usuario), align='L') pdf.output('%s/%s_%s.pdf' % (ETIQUETA_DIR, articuloobj.articulocod, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d'))) pdf.close() cups_server = CupsServer(settings.CUPS_ADMIN[0], settings.CUPS_ADMIN[1] ) cups_server.modo_admin() for a in range(4): cups_server.imprimir_trabajo('Zebra_TLP2844', "%s/%s_%s.jpg" % (ETIQUETA_DIR, articuloobj.articulocod, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d')), {})
def data_to_heat_map(self, shifted, names, filename = "all_hours_amg_above20percent_all_" "annotated_and_significant_with_01_and_15_fold.pdf"): """ Creates a heat map of the samples for each gene within the 'shifted' list and outputs it to the pdf file with the name 'filename'. The labels for the samples are taken rom the 'names' list. :param shifted: list of 'Gene' objects. :param names: list with the names of the samples. :return: """ pdf = FPDF() counter = 1 total = len(shifted) pdf.add_page() pdf.set_text_color(255, 255, 255) pdf.set_font('Arial', '', 12) shifted.sort(key=lambda x: x.getMaxShift()) shifted = shifted[::-1] for gene in shifted: gene.calculate_lengths() ax = sns.heatmap(np.transpose(gene.getSamples()), vmin=0.0, vmax=1.0, annot=True, fmt=".3g", linewidths=.5, yticklabels=names, xticklabels=gene.getLengths(), cmap='coolwarm') plt.axes(ax) pdf.write(0, gene.getName() + "\n") plt.title(gene.getName() + "\n max_shift = " + str('{0:.3f}'.format(gene.getMaxShift())) + " , max_read = " + str(gene.getMaxRead()) + " , mean_read = " + str('{0:.3f}'.format(gene.getMeanRead())) + "\n transcript = " + str(gene.getNumTranscript()) + " , " + gene.getWhatDiffers() + " , p_value = " + str('{0:.5f}'.format(gene.getPValue())) ) plt.yticks(rotation=0) plt.savefig("data\\heat_maps\\" + gene.getName() + ".png", dpi=65) pdf.image("data\\heat_maps\\" + gene.getName() + ".png") plt.close() print("Writing to PDF " + str(counter) + " out of " + str(total)) counter += 1 pdf.output(filename, "F")
def createpdf(path_image, savepath, results): # Generate FPDF object and add page pdf = FPDF("P", "mm", "A4") # (orientation, unit, format) pdf.add_page() # Vision logo pdf.image("images/logo.png", x=160, y=20, w=39, h=26) # Title pdf.set_font("Arial", "B", 28) # (letter type, style, size) pdf.set_text_color(4, 23, 34) #pdf.set_draw_color(220,220,220) # give color to borders pdf.set_fill_color(255, 255, 255) # backgrund cell color pdf.set_xy(25, 40) pdf.cell(0, 20, "OCT Diagnostic", 0, 2, "C", True) # Image pdf.image(path_image, x=120, y=80, w=59, h=59) # Text pdf.set_font("Arial", "", 12) pdf.set_text_color(10, 10, 10) pdf.cell(25, 20, "", 0, 2, "L") pdf.cell(0, 15, f"Choroidal Neovascularization : {round(results[0]*100, 2)} %", 0, 2, "L") pdf.cell(0, 15, f"Diabetic Macular Edema : {round(results[1]*100, 2)} %", 0, 2, "L") pdf.cell(0, 15, f"Drusen : {round(results[2]*100, 2)} %", 0, 2, "L") pdf.cell(0, 15, f"Normal : {round(results[3]*100, 2)} %", 0, 2, "L") # Save File pdf.output(f"{savepath}.pdf", "F")
def create_analytics_report(day, stock, filename, WIDTH=210, HEIGHT=297): pdf = FPDF() # A4 (210 by 297 mm) ''' First Page ''' pdf.add_page() pdf.image("./resources/THdata.png", 0, 0, WIDTH) create_title(day, stock, pdf) pdf.image("./tmp/fig_closeprice.png", 5, 50, WIDTH - 10) pdf.image("./tmp/fig_vaderscores.png", 5, 180, WIDTH - 10) ''' Second Page ''' pdf.add_page() pdf.image("./tmp/fig_countofnewsperday.png", 5, 40, WIDTH - 10) pdf.output(filename, 'F') print('Report generation successful!')
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 14) for i in range(0, 270, 5): pdf.text(i % 40 + 20, i + 20, "Image masking " * 4) mask = pdf.image(os.path.join(common.basepath, "masking.png"), is_mask = True) pdf.image(os.path.join(common.basepath, "lena.gif"), 40.0, 20.0, w = 120, mask_image = mask) pdf.image(os.path.join(common.basepath, "img_gray.jpg"), 20.0, 200.0, w = 50, mask_image = mask) pdf.image(os.path.join(common.basepath, "img_rgb.jpg"), 80.0, 200.0, w = 50, mask_image = mask) pdf.image(os.path.join(common.basepath, "img_cmyk.jpg"), 140.0, 200.0, w = 50, mask_image = mask) pdf.output(outputname, 'F')
def generatePdf(keywords): mbPaths = getMagicSchoolBusPaths() txts = buildPageTxt(keywords) pdf = FPDF() pageNumb = 0 for keyword in keywords: pdf.add_page() pdf.set_line_width(1) color = randBackColorGen() # create color pdf.set_fill_color(*color) pdf.rect(-5, -5, 1000, 2000, "DF") inverseColor = getColorInverse(*color) pdf.set_text_color(*inverseColor) pdf.set_font("Arial", size=20) pdf.cell(200, 10, txt=keyword.title(), ln=1, align="C") dir = './downloads/' + keyword + adjunctKeyword offsetY = 0 try: im = Image.open(mbPaths[pageNumb]) width, height = im.size imgHeight = 40 pdf.image(mbPaths[pageNumb], x=random.randint(100, 150), y=60, w=imgHeight) offsetY = 70 + height * (imgHeight / width) except: offsetY = 70 offsetX = 20 for file in os.listdir(dir): path = os.path.join(dir, file) if file.endswith(".jpg"): try: im = Image.open(path) width, height = im.size pdf.image(path, x=offsetX, y=offsetY, w=100) offsetY += 20 + height * (100 / width) except: print("error with jpg file shtuff") elif file.endswith(".png"): # todo put back in on refresh im = Image.open(path) rgb_im = im.convert('RGB') width, height = im.size rgb_im.save(path + '.jpg') pdf.image(path + '.jpg', x=offsetX, y=offsetY, w=100) offsetY += 20 + height * (100 / width) offsetX += 20 pdf.set_font("Arial", size=12) for txtSnip in txts[pageNumb]: pdf.cell(200, 13, txt=txtSnip, ln=1, align="L") pdf.ln(1) pageNumb += 1 pdf.output("simple_demo.pdf")
def pokepdf(pokemon): # FPDF Object pdf = FPDF("L", "mm", "A5") # Add page pdf.add_page() # Paint the background pdf.set_fill_color(*color.get(pokemon["type"][0], (255, ))) pdf.rect(0, 0, 210, 297, "F") # Set font pdf.set_font(*fonts["title"]) pdf.set_xy(20, 10) # Add Pokeball ball = {False: "pokeball", True: "masterball"}[pokemon["legendary"]] pdf.image(f"images/balls/{ball}.png", pdf.get_x(), pdf.get_y() + 25, w=20) # Add Pokemon Name pdf.cell(w=0, txt=f"{pokemon['id']} - {pokemon['name']}".title(), align="C", ln=1) # Add Pokemon Sprite pdf.image(pokemon["sprite_url"], 80, pdf.get_y() + 10, w=50) # Set new font font = fonts["flavor"] pdf.set_font(*font) pdf.set_xy(10, 70) # Cut text if larger than page flavor = chunks(pokemon["flavor"], font) # Add flavor text for i in flavor: pdf.cell(w=0, h=5, txt=i, align="C", ln=2) # Add type symbols for i, typ in enumerate(pokemon["type"]): if len(pokemon["type"]) == 1: pos = [90] else: pos = [50, 120] pdf.image(f"images/types/{typ}.png", pos[i], pdf.get_y() + 15, w=40) # Export pdf path = f"output/{pokemon['id']}_{pokemon['name']}.pdf" pdf.output(path) print(f"pdf saved to {path}")
def print_PDF(): pdf = FPDF('L', 'mm', 'A4') pdf.add_page() pdf.set_font('Arial', 'B', 40) pdf.cell(15, 10, 'Report') pdf.set_font('Arial', 'B', 30) pdf.cell(1, 45, 'Loudness') pdf.image('../output/grafica_1.png', 30, 40, h=150) pdf.add_page() pdf.set_font('Arial', 'B', 30) pdf.cell(40, 10, 'Tempo') pdf.image('../output/grafica_2.png', 35, 20, h=150) pdf.add_page() pdf.set_font('Arial', 'B', 30) pdf.cell(40, 10, 'Energy') pdf.image('../output/grafica_3.png', 35, 20, h=150) pdf.add_page() pdf.set_font('Arial', 'B', 30) pdf.cell(40, 10, 'Danceability') pdf.image('../output/grafica_4.png', 35, 20, h=150) return pdf.output('../output/report.pdf', 'F')
def add_image(image_path): pdf = FPDF() pdf.add_page() pdf.image(image_path, x=10, y=50, w=200) pdf.set_font("Arial", size=20) pdf.ln(5) # move 85 down pdf.cell(200, 10, txt="Report of the last 4 days", ln=1) pdf.ln(15) # move 85 down pdf.cell(200, 10, txt="Temperature of the last 4 days", ln=1) pdf.set_font("Arial", size=20) pdf.ln(345) # move 85 down pdf.cell(200, 10, txt="Humidity of the last 4 days", ln=1) pdf.image('/home/cloudera/f02.png', x=10, y=50, w=200) pdf.set_font("Arial", size=20) pdf.ln(675) # move 85 down pdf.cell(200, 10, txt="Soil Moisture of the last 4 days", ln=1) pdf.image('/home/cloudera/f03.png', x=10, y=50, w=200) pdf.set_font("Arial", size=20) pdf.ln(1005) # move 85 down pdf.cell(200, 10, txt="Atmospheric Pressure of the last 4 days", ln=1) pdf.image('/home/cloudera/f04.png', x=10, y=50, w=200) pdf.output("/home/cloudera/add_image.pdf")
def export_pdf(): images = [['movies_years.png', 38.07, 260.82], ['years.png', 228.575, 171.42], ['movies_age.png', 150, 98], ['age.png', 600, 300]] print('Now, we will export a report with the tables and graphs above') print('Exporting...') pdf = FPDF(unit="pt") pdf.set_xy(100, 100) pdf.add_page("p") pdf.set_font("Helvetica", "B", 12) pdf.cell(120, 30, "Report based on Years", ln=1) pdf.set_font("Helvetica", "", 9) pdf.cell( 120, 30, "The next table summarizes the movies recorded every year from 2001-2020:", ln=1) pdf.image(f'output/{images[0][0]}', w=images[0][1], h=images[0][2]) pdf.cell(120, 30, "Expressed as a bar plot in the following figure:", ln=1) pdf.image(f'output/{images[1][0]}', w=images[1][1], h=images[1][2]) pdf.add_page("l") pdf.set_font("Helvetica", "B", 12) pdf.cell(120, 30, "Report based on recommended Ages", ln=1) pdf.set_font("Helvetica", "", 9) pdf.cell( 120, 30, "The next table summarizes the amount of movies per recommended age in each platform:", ln=1) pdf.image(f'output/{images[2][0]}', w=images[2][1], h=images[2][2]) pdf.cell(120, 30, "Expressed as a pie plot in the following figure:", ln=1) pdf.image(f'output/{images[3][0]}', w=images[3][1], h=images[3][2]) print('Your report was succesfully exported') return pdf.output("output/report.pdf")
def main(): pdf = FPDF('P', 'mm', 'A4') pdf.add_page() x, y = grilla(4) pdf.image("RAW/10000001.png", x, y, ancho, largo) x, y = grilla(5) pdf.image("RAW/10000001.png", x, y, ancho, largo) x, y = grilla(6) pdf.image("RAW/10000001.png", x, y, ancho, largo) fila = 1 columna = 2 pdf.output("yourfile.pdf", "F")
def main(): #read all files from a given directory path = "./figures" imagelist = os.listdir(path) #print(imagelist) #Creating first pdf page image image1 = Image.open(path + '\\' + imagelist[0]) image2 = Image.open(path + '\\' + imagelist[1]) get_concat_v(image1, image2).save('./pdf/concat1.png') #Creating second pdf page image image3 = Image.open(path + '\\' + imagelist[2]) image4 = Image.open(path + '\\' + imagelist[3]) image6 = Image.open(path + '\\' + imagelist[5]) imageaux = get_concat_v(image3, image4) get_concat_v(imageaux, image6).save('./pdf/concat2.png') imagelist2 = [ 'concat1.png', 'concat2.png', './figures/z_network_graph.png' ] #Creating pdf pdf = FPDF() pdf.set_author('March') #First page pdf.add_page() pdf.set_font('Arial', 'B', 14) pdf.cell(90, 9, 'Cumulative Returns & Drawdowns', 1, 0, 'C') pdf.ln(10) pdf.image('pdf\\' + imagelist2[0], w=195, h=230) #Second page pdf.add_page() pdf.set_author('March') pdf.set_font('Arial', 'B', 12) pdf.cell(50, 8, 'Portfolio Analysis', 1, 0, 'C') pdf.ln(10) pdf.image('pdf\\' + imagelist2[1], w=195, h=250) #Third page pdf.add_page() pdf.set_author('March') pdf.set_font('Arial', 'B', 12) pdf.cell(50, 8, 'Hierarchical Network', 1, 0, 'C') pdf.ln(10) pdf.image(imagelist2[2], w=195, h=250) #Saving pdf pdf.output("./pdf/portfolio_analysis.pdf", "F")
def create_sales_analytics_report(day=TEST_DATE, filename="report.pdf"): pdf = FPDF() #A4 (210x297 mm) ''' First Page ''' pdf.add_page() pdf.image("./resources/pdf-header.png", 0, 0, WIDTH) create_title(day, pdf) # Generate plots # map_plot_world_sales() # bar_plot_monthly_sales() # bar_plot_country_sales() # bar_plot_product_sales() # bar_plot_orders_vs_price() # Add figures to pdf pdf.image('./resources/world_sales.png', 12, 95, WIDTH - 20) pdf.image('./resources/monthly_sales_plot.png', 5, 200, WIDTH / 2 - 10) pdf.image('./resources/orders_vs_price.png', WIDTH / 2, 200, WIDTH / 2 - 10) ''' Second Page ''' ''' Third Page ''' pdf.output(filename, 'F')
def make_pdf(number, ctype): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) main_img = os.path.join(BASE_DIR, 'content', 'cover.png') pdf = FPDF() pdf.add_page('P') pdf.set_font("Arial", size=15) pdf.cell(10, 10, txt=number, ln=1, align="C") if ctype == 1: pdf.rotate(-90.1) imwrite(main_img, warpImage(imread(main_img), cover_type=0)) pdf.image(main_img, 100, -165, 78, 85) pdf.image(os.path.join(BASE_DIR, 'content', 'template', 'big.png'), 9, -172, 258, 110.3) pdf.output(os.path.join(BASE_DIR, 'content', 'big.pdf')) os.remove(main_img) elif ctype == 0: pdf.rotate(-89.75) imwrite(main_img, warpImage(imread(main_img), cover_type=1)) pdf.image(main_img, 103, -71, 74, 60) pdf.image(os.path.join(BASE_DIR, 'content', 'template', 'small.png'), 17.5, -74, 240, 84) pdf.output(os.path.join(BASE_DIR, 'content', 'small.pdf')) os.remove(main_img)
def test(): actuals = sorted(glob.glob("pdf/actual*")) result = sorted(glob.glob("pdf/result*")) inputs = sorted(glob.glob("pdf/input*")) pdf = FPDF() x = 0 y = 0 for i in range(len(actuals)): pdf.add_page() #print(inputs[i]) print(actuals[i]) #print(result[i]) pdf.image(inputs[i]) pdf.image(actuals[i]) pdf.image(result[i]) pdf.output("result.pdf", "F")
def gen_pdf(): health_pdf = FPDF( ) # А4 с портретной ориентацией. Единица измерения: mm(миллиметр) deceased_pdf = FPDF() health_pdf.add_page() deceased_pdf.add_page() health_pdf.add_font('Segoe Print', '', 'fonts/segoepr.ttf', uni=True) # Segoe Print deceased_pdf.add_font('Segoe Print', '', 'fonts/segoepr.ttf', uni=True) health_pdf.add_font('Corbel', '', 'fonts/corbel.ttf', uni=True) deceased_pdf.add_font('Corbel', '', 'fonts/corbel.ttf', uni=True) health, deceased = put_names() health_pdf.set_font('Segoe Print') deceased_pdf.set_font('Segoe Print') health_pdf.set_font_size(30) deceased_pdf.set_font_size(30) health_pdf.set_text_color(76, 78, 75) deceased_pdf.set_text_color(76, 78, 75) health_pdf.image(name='images/крест.png', x=50, y=4, type='PNG') health_pdf.image(name='images/крест.png', x=143, y=4, type='PNG') deceased_pdf.image(name='images/крест.png', x=36, y=4, type='PNG') deceased_pdf.image(name='images/крест.png', x=157, y=4, type='PNG') health_pdf.cell(185, 5, txt='О ЗДРАВИИ', align='C', ln=1) deceased_pdf.cell(185, 5, txt='ОБ УПОКОЕНИИ', align='C', ln=1) health_pdf.set_xy(10, 20) deceased_pdf.set_xy(10, 20) health_pdf.set_font('Corbel') deceased_pdf.set_font('Corbel') health_pdf.set_font_size(18) deceased_pdf.set_font_size(18) health_pdf.set_text_color(0, 0, 0) deceased_pdf.set_text_color(0, 0, 0) health_pdf.write(h=8, txt=names(health)) deceased_pdf.write(h=8, txt=names(deceased)) health_pdf.output('output/health_notes.pdf') deceased_pdf.output('output/deceased_notes.pdf')
def convert2PDF(image): img = Image.open(image) pdf = FPDF() # compression is not yet supported in py3k version pdf.compress = False pdf.add_page('L') pdf.image('images/imagens-de-amor-textos-romanticos-8.jpg', x=0, y=0, w=298, h=0) pdf.add_page('P') pdf.image('images/ex02.jpg', x=0, y=0, w=210, h=0) pdf.add_page() pdf.image(image, 0, 0) pdf.output('py3k.pdf', 'F')
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 14) pdf.ln(10) if nostamp: data = "TEST-TEST-TEST" else: data = sys.version pdf.write(5, 'hello world %s' % data) pdf.image("../tutorial/logo.png", 50, 50) pdf.image("flower2.jpg", 100, 50) pdf.image("lena.gif", 50, 75) pdf.output(outputname, 'F')
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 14) pdf.text(10, 57, 'DeviceGray') pdf.image("img_gray.jpg", 55, 5) pdf.text(10, 157, 'DeviceRGB') pdf.image("img_rgb.jpg", 55, 105) pdf.text(10, 257, 'DeviceCMYK') pdf.image("img_cmyk.jpg", 55, 205) pdf.output(outputname, 'F')
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 14) pdf.text(10, 57, 'DeviceGray') pdf.image(os.path.join(common.basepath, "img_gray.jpg"), 55, 5) pdf.text(10, 157, 'DeviceRGB') pdf.image(os.path.join(common.basepath, "img_rgb.jpg"), 55, 105) pdf.text(10, 257, 'DeviceCMYK') pdf.image(os.path.join(common.basepath, "img_cmyk.jpg"), 55, 205) pdf.output(outputname, 'F')
def creaPDF(): pdf = FPDF('L','mm','A4') pdf.add_page() pdf.set_font('Arial', 'B', 16) pdf.cell(190, 10, f"{titulo}",1,1,'C') pdf.set_font('Courier', '',10) pdf.cell(190, 10, 'Últimos diez años de evolución de las temperaturas.','',1,'C') pdf.ln(6) pdf.text(10,30,'En el primer gráfico podemos observar la evolución mundial de las temperaturas en los últimos diez años.') pdf.ln(50) pdf.image('output/avgtemperatureEarth.png',x=70, y=50, w=100) pdf.set_font('Courier', '',13) pdf.cell(90,50,'¿Y si queremos ver la evolución de las temperaturas en una sola ciudad, la década pasada?','',1) pdf.set_font('Courier', '',10) pdf.image('output/avgtempplot.png',x=70, y=130, w=100) pdf.cell(150,90,'Por otro lado, el siguiente gráfico pinta la evolución de las precipitaciones en Madrid :','',1) pdf.image('output/RainChange.png',x=70, y=100, w=100) pdf.output("file.pdf") pdf.output("src/report.pdf", "F")
def __init__(self, home, customer): directory = os.listdir('./output/a5-horizontal') files = filter(lambda f: "gift-card-" in f, directory) files = sorted(files, key=lambda f: f) number_of_a5_horizontal = len(files) count = 0 gift_card_number = 1 while number_of_a5_horizontal > 0: pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.add_page() pdf.image('./output/a5-horizontal/{}'.format(files[count]), x=0, y=0, w=210, h=148) pdf.image('./output/a5-horizontal/{}'.format(files[count + 1]), x=0, y=148, w=210, h=148) pdf.output( "{}/{}-gift-cards/a5-horizontal/{}-a5-horizontal-{}.pdf". format(home, customer, customer, gift_card_number)) count += 2 number_of_a5_horizontal -= 2 gift_card_number += 1 if number_of_a5_horizontal < 2: break if number_of_a5_horizontal == 1: pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.add_page() pdf.image('./output/a5-horizontal/{}'.format(files[count]), x=0, y=0, w=210, h=148) pdf.output( "{}/{}-gift-cards/a5-horizontal/{}-a5-horizontal-{}.pdf". format(home, customer, customer, gift_card_number)) number_of_a5_horizontal -= 1 else: MergePDFS(home=home, customer=customer, format='a5-horizontal')
def receipt_gen(share, key, ticket): ipsum = """ Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. """ qr_gen(share, key, ticket) #Setup page receipt = FPDF('P', 'mm', (100, 350)) receipt.add_page() dynamic_widith = receipt.w - 2 * receipt.l_margin #Header receipt.set_font('Arial', '', 26) receipt.cell(0, 11, 'Poll Receipt', ln=2, align='C') #Print date time receipt.set_font('Arial', '', 10) receipt.cell(0, 5, time.strftime("%d/%m/%Y"), align='C', ln=2) receipt.cell(0, 10, time.strftime("%H:%M:%S"), align='C', ln=2, border='B') #spacer receipt.cell(0, 5, ln=2) #Body receipt.set_font('Arial', '', 22) #Personal Share receipt.cell(0, 10, 'Share', align='C', ln=1) receipt.image('share.png', w=50, x=25) #Private key receipt.cell(0, 10, 'Private Key', align='C', ln=1) receipt.image('key.png', w=50, x=25) #Personal Share receipt.cell(0, 10, 'Ticket', align='C', ln=1) receipt.image('ticket.png', w=50, x=25) #Spacer receipt.cell(0, 5, ln=1, border='B') receipt.cell(0, 10, ln=1) #Instructions receipt.set_font('Arial', '', 12) receipt.multi_cell(dynamic_widith, 4, ipsum, align='L') #Save pdf receipt.output('Poll Receipt.pdf')
def add_image_All(image_path, output_path, Ind_Img, tot_Imag, name): pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) pdf.ln(85) # move 85 down pdf.cell(200, 10, name, ln=1) pdf.image(image_path, x=10, y=12, w=200) pdf.add_page() pdf.ln(85) # move 85 down pdf.cell(200, 10, 'Individiual', ln=1) pdf.image(Ind_Img, x=10, y=12, w=200) pdf.add_page() pdf.ln(85) # move 85 down pdf.cell(200, 10, 'Total', ln=1) pdf.image(tot_Imag, x=10, y=12, w=200) pdf.output(output_path)
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 14) pdf.ln(10) if nostamp: data = "TEST-TEST-TEST" else: data = sys.version pdf.write(5, 'hello world %s' % data) path = os.path.join(common.basepath, os.pardir, "tutorial", "logo.png") pdf.image(path, 50, 50) pdf.image(os.path.join(common.basepath, "flower2.jpg"), 100, 50) pdf.image(os.path.join(common.basepath, "lena.gif"), 50, 75) pdf.output(outputname, 'F')