from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4, ZZ, landscape from reportlab.lib.units import mm from reportlab.graphics.barcode import code39 import xlrd from barcode import generate plik = xlrd.open_workbook("numery.xls") strona = plik.sheet_by_index(0) total_rows = strona.nrows c = canvas.Canvas("barcode.pdf", pagesize=landscape(ZZ)) licznik = total_rows // 16 i = 0 for d in range(licznik - 1): c.setFont("Helvetica", 25) code = strona.cell(i, 0).value barcode = code39.Standard39(code, checksum=0, barWidth=0.35 * mm, barHeight=30 * mm) barcode.drawOn(c, 4 * mm, 41 * mm) c.drawString(14 * mm, 30 * mm, code) i += 1 code = strona.cell(i, 0).value barcode = code39.Standard39(code, checksum=0, barWidth=0.35 * mm, barHeight=30 * mm) c.drawString(79 * mm, 35 * mm, code)
def Download(request): pdfmetrics.registerFont( TTFont('song', os.getcwd() + '/project/sua/views/student/STSONG.ttf')) user = request.user student = user.student # Filename = 'str(student.name)' sua_data = SuaSerializer( # 序列化当前学生的所有公益时记录 student.suas.filter(is_valid=True), many=True, context={'request': request}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=公益时' buffer = BytesIO() zuo = 50 kuan = 210 you = 545 p = canvas.Canvas(buffer) p.filename = student.name p.setFont("song", 22) #字号 p.drawString( zuo - 5, 780, "公益时记录", ) #标题 p.drawImage('project/sua/static/sua/images/logo-icon.png', 460, 705, width=90, height=90) #学院标志 p.setFont("song", 15) #字号 p.drawString(zuo - 5, 750, '学号:' + str(user)) #学号 p.drawString(zuo + 150, 750, '名字:' + str(student.name)) #名字 p.drawString(zuo - 5, 720, '总公益时数:' + str(student.suahours) + 'h') #总公益时 location = 640 p.drawString(zuo, 680, "活动名称") p.drawString(zuo + kuan, 680, "活动团体") p.drawString(zuo + kuan * 2, 680, "公益时数") for sua in sua_data.data: p.drawString(zuo, location, str(sua['activity']['title'])) #活动主题 p.drawString(zuo + kuan, location, str(sua['activity']['group'])) #活动团体 p.drawString(zuo + kuan * 2, location, str(sua['suahours']) + 'h') #公益时数 location -= 50 p.line(zuo - 5, location + 15, you, location + 15) #第N横 p.line(zuo - 5, 700, you, 700) #第一横 p.line(zuo - 5, 655, you, 655) #第二横 p.line(zuo - 5, 700, zuo - 5, location + 15) #第一丨 p.line(you, 700, you, location + 15) #第四丨 p.line(zuo + kuan - 5, 700, zuo + kuan - 5, location + 15) #第二丨 p.line(zuo + 2 * kuan - 5, 700, zuo + 2 * kuan - 5, location + 15) #第三丨 p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def cria_pdf(self, loja): from reportlab.pdfgen import canvas from reportlab.lib.units import cm from reportlab.lib.pagesizes import A4 from datetime import datetime, timedelta import time width, height = A4 c = canvas.Canvas("db/dados.pdf", pagesize=A4) data = datetime.now().date() c.setFont('Helvetica-Bold', 10) c.drawRightString(width - 1.5 * cm, height - 8.2 * cm, str(data)) c.drawRightString(width - 4 * cm, height - 8.2 * cm, str(data + timedelta(days=5))) c.drawRightString(width - 6.5 * cm, height - 8.2 * cm, str(loja.usr.cliente)) linha = height - 9.3 * cm ls = 0.525 * cm c.setFont('Helvetica', 8) for li in range(loja.carrinho.__len__()): aux = loja.carrinho[li] c.drawCentredString(1.5 * cm, linha - (li * ls), str(aux.codigo)) c.drawString(2.4 * cm, linha - (li * ls), str(aux.artigo)) c.drawRightString(width - 4.85 * cm, linha - (li * ls), str(aux.quantidade)) c.drawRightString(width - 3.32 * cm, linha - (li * ls), loja.moeda(aux.custo)) c.drawRightString(width - 2.82 * cm, linha - (li * ls), str('23')) c.drawRightString(width - 1.07 * cm, linha - (li * ls), loja.moeda(aux.total())) c.drawString(7 * cm, 3.15 * cm, "(c) Copyright 2019 Gonçalo Figueiredo") texto = c.beginText(10.8 * cm, height - 2.5 * cm) texto.setFont('Helvetica-Bold', 14) texto.textLine("Encomenda") texto.textLine(' ') texto.setFont('Helvetica', 10) texto.textLine("Exmo.(s) Sr.(s)") texto.textLine(' ') texto.setFont('Helvetica-Bold', 10) texto.textLine(loja.usr.nome) texto.setFont('Helvetica', 10) for line in loja.usr.morada.splitlines(False): texto.textLine(line.rstrip()) texto.setFont('Helvetica-Bold', 10) texto.textLine(' ') texto.textLine('NIF: ' + loja.usr.nif) c.drawText(texto) total = loja.total() mercadorias = total / 1.23 iva = total - mercadorias c.setFont('Helvetica', 10) s = 0.53 b = 5.5 c.drawRightString(width - 1.0 * cm, (4 * s + b) * cm, loja.moeda(mercadorias)) c.drawRightString(width - 1.0 * cm, (3 * s + b) * cm, loja.moeda(0)) c.drawRightString(width - 1.0 * cm, (2 * s + b) * cm, loja.moeda(0)) c.drawRightString(width - 1.0 * cm, (1 * s + b) * cm, loja.moeda(iva)) c.drawRightString(width - 1.0 * cm, (0 * s + b) * cm, loja.moeda(0)) total_items = 0 for linha in range(loja.carrinho.__len__()): total_items += loja.carrinho[linha].quantidade c.drawString(3.7 * cm, 8.67 * cm, str(total_items)) c.setFont('Helvetica', 8) c.drawString(2.7 * cm, 6.65 * cm, loja.moeda(mercadorias)) c.drawString(5.45 * cm, 6.65 * cm, loja.moeda(iva)) c.setFont('Helvetica-Bold', 18) c.drawRightString(width - 1.0 * cm, 4.5 * cm, loja.moeda(total)) # ----------------- QR CODE ---------------- t = str(int(time.time() * 100000)) code = t[10:12] + ' ' + t[12:15] + '/' + t[0:10] file = 'F' + t[10:15] + '_' + t[0:10] + '.pdf' c.setFont('Helvetica-Bold', 15) c.drawRightString(width - 1 * cm, height - 1.5 * cm, str(code)) import qrcode qr = qrcode.QRCode() qr.add_data(code) img = qr.make_image(fill_color="#005", back_color="#ffe") c.drawInlineImage(img, width - 4 * cm, height - 4.6 * cm, width=3 * cm, height=3 * cm) # ------------------------------------------ c.showPage() c.save() self.merge_pdf(file) self.envia_pdf(file, loja.usr.email) return file
from reportlab.lib.units import mm from reportlab.pdfgen import canvas def coord(x, y, unit=1): x, y = x * unit, y * unit return x, y c = canvas.Canvas("hello2.pdf", bottomup=0) c.drawString(*coord(15, 20, mm), text="Welcome to Reportlab!") c.showPage() c.save()
def place_pic(fn_in, fn_pic, fn_out, x0, y0, scale=1.0, mask=None, pages=[], follow_rotate=False): pdf = PdfFileReader(file(fn_in, "rb")) output = PdfFileWriter() outputStream = file(fn_out, "wb") width, height = pic_pdf_size = get_pdf_pagesize(fn_in) pdf_dim = get_pdf_dimensions(fn_in) pic_width, pic_height = get_pic_size(fn_pic) pagecount = pdf_dim['numPages'] d_watermark = {} for i in range(pagecount): p = pdf.getPage(i) if i in pages: rotate = int(pdf_dim['d_pageno2rotate'][i]) % 360 w, h = pdf_dim['d_pageno2size'][i] max_wh = max(w, h) translation_scale = 1.0 key = "%.3f|%.3f|%d" % (float(w), float(h), int(rotate)) if key in d_watermark: watermark = d_watermark[key][0] else: s_out = StringIO.StringIO() c = canvas.Canvas(s_out, pagesize=(w, h)) x1 = x0 * translation_scale y1 = y0 * translation_scale - 0.51 if rotate and not follow_rotate: if rotate == 90: c.translate(w, 0) elif rotate == 180: c.translate(w, h) elif rotate == 270: c.translate(0, h) c.rotate(rotate) c.drawImage(fn_pic, x1, y1, width=int(pic_width * scale + 0.5), height=int(pic_height * scale + 0.5), preserveAspectRatio=True, mask=mask) c.save() watermark = PdfFileReader(s_out) d_watermark[key] = (watermark, s_out) p.mergePage(watermark.getPage(0)) output.addPage(p) output.write(outputStream) outputStream.close() for k in d_watermark: try: d_watermark[k][1].close() except: pass pdf.stream.close() return
def pdf3(correo, i_dia, i_mes, i_anno, f_dia, f_mes, f_anno): output = io.BytesIO() p = canvas.Canvas("/usr/src/app/project/extractos.pdf") data = request.get_json() fecha_inicial = str(i_anno) + "-" if (len(str(i_mes)) == 1): fecha_inicial += "0" fecha_inicial += str(i_mes) + "-" if (len(str(i_dia)) == 1): fecha_inicial += "0" fecha_inicial += str(i_dia) + "T00:00:00.000Z" fecha_final = str(f_anno) + "-" if (len(str(f_mes)) == 1): fecha_final += "0" fecha_final += str(f_mes) + "-" if (len(str(f_dia)) == 1): fecha_final += "0" fecha_final += str(f_dia) + "T99:99:99.999Z" envios_recibidos = data[u'total_receive'] envios_realizados = data[u'total_send'] cargas_tarjeta = data[u'total_load'] p.setFont('Helvetica-Bold', 10) #Nombres de columna de DINERO RECIBIDO p.setFont('Helvetica-Bold', 12) p.drawString(15, 755, "DINERO RECIBIDO:") p.setFont('Helvetica-Bold', 10) p.drawString(20, 740, "N. Transacción") p.drawString(110, 740, "Remitente") p.drawString(210, 740, "Monto") p.drawString(300, 740, "Estado") p.drawString(370, 740, "Fecha") p.drawString(470, 740, "Hora") aux = 695 - 15 * (envios_recibidos) #Nombres de columna de DINERO ENVIADO p.setFont('Helvetica-Bold', 12) p.drawString(15, aux + 15, "DINERO ENVIADO:") p.setFont('Helvetica-Bold', 10) p.drawString(20, aux, "N. Transacción") p.drawString(110, aux, "Destinatario") p.drawString(210, aux, "Monto") p.drawString(300, aux, "Estado") p.drawString(370, aux, "Fecha") p.drawString(470, aux, "Hora") total_recibidos_pdf = 0 total_enviados_pdf = 0 total_cargas_pdf = 0 p.setFont('Helvetica', 9) fila = 15 for i in range(0, len(data[u'list_receive'])): if (str(data[u'list_receive'][i][u'updated_at']) < fecha_final and str(data[u'list_receive'][i][u'updated_at']) > fecha_inicial): total_recibidos_pdf += 1 tam_id = len(str(data[u'list_receive'][i][u'id'])) p.drawString(24, 740 - fila, ('0' * (10 - tam_id)) + str(data[u'list_receive'][i][u'id'])) tam_id2 = len(str(data[u'list_receive'][i][u'useridgiving'])) p.drawString(114, 740 - fila, ('0' * (10 - tam_id2)) + str(data[u'list_receive'][i][u'useridgiving'])) p.drawString(214, 740 - fila, '$' + str(data[u'list_receive'][i][u'amount'])) p.drawString(304, 740 - fila, str(data[u'list_receive'][i][u'state'])) s_aux = str(data[u'list_receive'][i][u'updated_at']) hora = "" fecha = "" b_aux = 1 for c in s_aux: if (c == 'T'): b_aux = 0 elif (c == 'Z'): b_aux = 0 elif (b_aux == 1): fecha += c else: hora += c p.drawString(374, 740 - fila, fecha) p.drawString(474, 740 - fila, hora) fila += 15 fila = 15 for i in range(0, len(data[u'list_send'])): if (str(data[u'list_send'][i][u'updated_at']) < fecha_final and str(data[u'list_send'][i][u'updated_at']) > fecha_inicial): total_enviados_pdf += 1 tam_id = len(str(data[u'list_send'][i][u'id'])) p.drawString(24, aux - fila, ('0' * (10 - tam_id)) + str(data[u'list_send'][i][u'id'])) tam_id2 = len(str(data[u'list_send'][i][u'useridreceiving'])) p.drawString(114, aux - fila, ('0' * (10 - tam_id2)) + str(data[u'list_send'][i][u'useridreceiving'])) p.drawString(214, aux - fila, '$' + str(data[u'list_send'][i][u'amount'])) p.drawString(304, aux - fila, str(data[u'list_send'][i][u'state'])) s_aux = str(data[u'list_send'][i][u'updated_at']) hora = "" fecha = "" b_aux = 1 for c in s_aux: if (c == 'T'): b_aux = 0 elif (c == 'Z'): b_aux = 0 elif (b_aux == 1): fecha += c else: hora += c p.drawString(374, aux - fila, fecha) p.drawString(474, aux - fila, hora) fila += 15 aux = aux - fila - 30 p.setFont('Helvetica-Bold', 12) p.drawString(15, aux + 15, "DINERO CARGADO DESDE LA TARJETA:") p.setFont('Helvetica-Bold', 10) #Nombres de columna de cargas desde tarjeta p.drawString(20, aux, "N. Transacción") p.drawString(210, aux, "Monto") p.drawString(300, aux, "Estado") p.drawString(370, aux, "Fecha") p.drawString(470, aux, "Hora") p.setFont('Helvetica', 9) fila = 15 for i in range(0, len(data[u'list_load'])): if (str(data[u'list_load'][i][u'updated_at']) < fecha_final and str(data[u'list_load'][i][u'updated_at']) > fecha_inicial): total_cargas_pdf += 1 tam_id = len(str(data[u'list_load'][i][u'id'])) p.drawString(24, aux - fila, ('0' * (10 - tam_id)) + str(data[u'list_load'][i][u'id'])) p.drawString(214, aux - fila, '$' + str(data[u'list_load'][i][u'amount'])) p.drawString(304, aux - fila, str(data[u'list_load'][i][u'state'])) s_aux = str(data[u'list_load'][i][u'updated_at']) hora = "" fecha = "" b_aux = 1 for c in s_aux: if (c == 'T'): b_aux = 0 elif (c == 'Z'): b_aux = 0 elif (b_aux == 1): fecha += c else: hora += c p.drawString(374, aux - fila, fecha) p.drawString(474, aux - fila, hora) fila += 15 p.drawString(20, 810, "Cargas desde tarjeta....... " + str(total_cargas_pdf)) p.drawString(20, 795, "Envios recibidos........... " + str(total_recibidos_pdf)) p.drawString(20, 780, "Envios realizados.......... " + str(total_enviados_pdf)) p.save() msg = Message("Extractos " + fecha_inicial[0:10] + "---" + fecha_final[0:10], sender="*****@*****.**", recipients=[correo]) msg.body = "Transacciones realizadas entre la fecha: " + fecha_inicial[ 0:10] + " y la fecha " + fecha_final[ 0:10] + ".\n" + "Gracias por usar UWalllet." with app.open_resource("extractos.pdf") as fp: msg.attach("extractos.pdf", "application/pdf", fp.read()) mail.send(msg) pdf_out = output.getvalue() output.close() return "Sent"
# stock data from uncleengineer import thaistock # datetime from datetime import datetime pdfmetrics.registerFont(TTFont('F1', 'angsana.ttc')) def Text(c, x, y, text, font='F1', size=30, color=colors.black): c.setFillColor(color) c.setFont(font, size) c.drawString(x, y, text) dtf = datetime.now().strftime('%Y-%m-%d %H-%M-%S') c = canvas.Canvas('stock - {}.pdf'.format(dtf), pagesize=A4) c.setFont('F1', 30) c.setFillColor(colors.black) c.drawCentredString(105 * mm, 280 * mm, 'ราคาหุ้น (+)') c.drawCentredString(105 * mm, 180 * mm, 'ราคาหุ้น (-)') c.drawCentredString(105 * mm, 80 * mm, 'ราคาหุ้น (0)') # ใส่ข้อความแบบ list textlines = [] #ราคาบวก textlines2 = [] #ราคาลบ textlines3 = [] #ไม่เปลี่ยนแปลง mystock = ['SCB', 'TMB', 'KBANK', 'KTB', 'CPALL', 'CPN', 'GULF', 'PTT', 'BBL'] for st in mystock:
import os, sys from reportlab.pdfgen import canvas from reportlab.lib.units import cm as CM from reportlab.lib.units import inch as INCHES print "CM = ", CM print "IN = ", INCHES c = canvas.Canvas("B.pdf") c.drawString(2*CM ,4*CM,"LID") c.drawString(4*CM ,4*CM,"Kamran") c.drawString(4*CM ,2*CM,"Husain") c.showPage() c.save()
# NJCTL SMARTpdfAddPageNumbers # [email protected] from pyPdf import PdfFileWriter, PdfFileReader import StringIO from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter import sys if __name__ == "__main__": existing_pdf = PdfFileReader(file(sys.argv[1], "rb")) output = PdfFileWriter() numPages = existing_pdf.getNumPages() for i in range(numPages): packet = StringIO.StringIO() can = canvas.Canvas(packet, pagesize=letter) can.drawRightString(750, 30, "%d / %d" % (i + 1, numPages)) can.save() packet.seek(0) new_pdf = PdfFileReader(packet) page = existing_pdf.getPage(i) page.mergePage(new_pdf.getPage(0)) output.addPage(page) outputStream = file(sys.argv[1].replace(".pdf", ".numbered.pdf"), "wb") output.write(outputStream) outputStream.close()
def execute(self, context): pdf_images = [] props = context.scene.mv width, height = landscape(legal) images = self.sort_images(context.window_manager.mv.image_views) for img in images: image = bpy.data.images[img.image_name] image.save_render( os.path.join(bpy.app.tempdir, image.name + ".jpg")) pdf_images.append( os.path.join(bpy.app.tempdir, image.name + ".jpg")) if bpy.data.filepath == "": file_path = bpy.app.tempdir room_name = "Unsaved" else: project_path = os.path.dirname(bpy.data.filepath) room_name, ext = os.path.splitext( os.path.basename(bpy.data.filepath)) file_path = os.path.join(project_path, room_name) if not os.path.exists(file_path): os.makedirs(file_path) file_name = '2D Views.pdf' c = canvas.Canvas(os.path.join(file_path, file_name), pagesize=landscape(legal)) logo = os.path.join(os.path.dirname(__file__), "logo.jpg") for img in pdf_images: #PICTURE c.drawImage(img, 20, 80, width=width - 40, height=height - 100, mask='auto', preserveAspectRatio=True) #LOGO c.drawImage(logo, 25, 20, width=200, height=60, mask='auto', preserveAspectRatio=True) #PICTURE BOX c.rect(20, 80, width - 40, height - 100) #LOGO BOX c.rect(20, 20, 220, 60) #COMMENT BOX c.setFont("Times-Roman", 9) c.drawString(width - 20 - 250 + 5, 67, "COMMENTS:") c.rect(width - 20 - 248, 20, 248, 60) #CLIENT c.drawString(245, 67, "CLIENT: " + props.client_name) c.rect(240, 60, 250, 20) #PHONE c.drawString(245, 47, "PHONE: " + props.client_phone) c.rect(240, 40, 250, 20) #EMAIL c.drawString(245, 27, "EMAIL: " + props.client_email) c.rect(240, 20, 250, 20) #JOBNAME c.drawString(495, 67, "JOB NAME: " + props.job_name) c.rect(490, 60, 250, 20) #JOBNAME c.drawString(495, 47, "ROOM: " + room_name) c.rect(490, 40, 250, 20) #DRAWN BY c.drawString(495, 27, "DRAWN BY: " + props.designer_name) c.rect(490, 20, 250, 20) c.showPage() c.save() #FIX FILE PATH To remove all double backslashes fixed_file_path = os.path.normpath(file_path) if os.path.exists(os.path.join(fixed_file_path, file_name)): os.system('start "Title" /D "' + fixed_file_path + '" "' + file_name + '"') else: print('Cannot Find ' + os.path.join(fixed_file_path, file_name)) return {'FINISHED'}
def generate_certificate_pdf(display_name, certificate_template_id, date, validation_uuid): cert_template = CertificateTemplate.objects.get(pk=certificate_template_id) buffer = io.BytesIO() with Image.open(cert_template.image_file.path) as img: w, h = img.size # Create the PDF object if w > h: cert = canvas.Canvas(buffer, pagesize=landscape(A4)) else: cert = canvas.Canvas(buffer, pagesize=portrait(A4)) cert.setTitle(cert_template.course.get_title()) # add background cert.drawImage(cert_template.image_file.path, 0, 0) # add name if cert_template.include_name: cert.setFont('Helvetica-Bold', 24) cert.drawCentredString(cert_template.name_x, cert_template.name_y, display_name) # add course if cert_template.include_course_title: cert.setFont('Helvetica-Bold', 24) cert.drawCentredString(cert_template.course_title_x, cert_template.course_title_y, cert_template.course.get_title()) # add date if cert_template.include_date: cert.setFont('Helvetica-Bold', 16) cert.drawCentredString(cert_template.date_x, cert_template.date_y, date) host = SettingProperties.get_string(constants.OPPIA_HOSTNAME, '') url_path = reverse('oppia:certificate_validate', args=[validation_uuid]) validation_link = host + url_path # add url if cert_template.validation == CertificateTemplate.VALIDATION_OPTION_URL: cert.setFont('Helvetica', 10) cert.drawCentredString(cert_template.validation_x, cert_template.validation_y, "Verify certificate: " + validation_link) # add QR Code if cert_template.validation == \ CertificateTemplate.VALIDATION_OPTION_QRCODE: qr_img = qrcode.make(validation_link) maxsize = (60, 60) qr_img.thumbnail(maxsize, Image.ANTIALIAS) bytes_in = io.BytesIO() qr_img.save(bytes_in, format='png') bytes_in.seek(0) qr = ImageReader(bytes_in) cert.drawImage(qr, cert_template.validation_x, cert_template.validation_y) cert.setFont('Helvetica', 10) cert.drawCentredString(cert_template.validation_x + 28, cert_template.validation_y - 5, (u"Verify Certificate")) cert.showPage() cert.save() return buffer
def generate_col_letter(request, hrmgmt_id=None): """ Generate COL Letter for candidate. """ hr, first_name, last_name, offered_ctc, joining_date, ref_id \ = "", "", "", "", "", "" try: hr = HRManagement.objects.get(id=int(hrmgmt_id)) except HRManagement.DoesNotExist: hr = hr if hr: client = hr.resume.requirement.client.name first_name = hr.resume.created_by.first_name.upper()[0] last_name = hr.resume.created_by.last_name.upper()[0] tc = ResumeManagement.objects.filter( created_by=hr.resume.created_by).count() nme = "{}{}".format(first_name, last_name) offered_ctc = hr.offered_ctc joining_date = hr.joining_date.strftime("%d/%m/%Y") s = "{}".format(client) ref_id = "Brisa/{}/{}/{}/{}".format( "".join([i[0] for i in s.split()]), datetime.datetime.now().strftime("%b%Y"), nme, tc) response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="{}_{}_offer"'.format( first_name, last_name) p = canvas.Canvas(response) path = os.getcwd() image_path = os.path.abspath(path + "/static/images/logo.png") p.drawImage(image_path, 10, 770, width=155, height=60, mask=None) ptext = """<font name=Times-Bold color=black size=14>Brisa Technologies Pvt.Ltd.</font>""" createParagraph(p, ptext, 420, 815) ptext = """<font name=Times color=black size=12>No.90, 27th Main,</font>""" createParagraph(p, ptext, 420, 803) ptext = """<font name=Times color=black size=12>HSR Layout,Sector-1,</font>""" createParagraph(p, ptext, 420, 791) ptext = """<font name=Times color=black size=12>Bangalore-560 102</font>""" createParagraph(p, ptext, 420, 779) ptext = """<font name=Times color=black size=12>Phone:+91-80-42134897</font>""" createParagraph(p, ptext, 420, 767) ptext = """<font name=Times color=black size=12>website:www.brisa-tech.com</font>""" createParagraph(p, ptext, 420, 755) p.line(10, 740, 580, 740) ref_id = ref_id ptext = """<font name=Times-Bold color=black size=12>Ref: {}</font>""".format( ref_id) createParagraph(p, ptext, 50, 710) name = "{} {},".format(first_name, last_name) ptext = """<font name=Times-Bold color=black size=12>Dear {}</font>""".format( name) createParagraph(p, ptext, 50, 670) gen_date = datetime.datetime.now().strftime("%d/%m/%Y") ptext = """<font name=Times-Bold color=black size=12>{}</font>""".format( str(gen_date)) createParagraph(p, ptext, 480, 710) p.drawString( 50, 630, "As per our discussion with you, please find below the terms and conditions of your conditional" ) p.drawString(50, 605, "offer from Brisa Technologies Pvt. Ltd., Bangalore.") salary = offered_ctc ptext = """<bullet>&bull</bullet><font name=times-roman color=black size=14>Annual CTC would be INR {} /- per annum.</font> """.format( salary) createBulletListParagraph(p, ptext, 100, 570) ptext = """<bullet>&bull</bullet><font name=times-roman size=14>Your Tentative Joining Date with Brisa Technologies would be {}.</font> """.format( joining_date) createBulletListParagraph(p, ptext, 100, 545) ptext = """<font name=Times-Bold color=black size=14>If your profile is shortlisted by our client, you will have to attend Face to</font>""" createParagraph(p, ptext, 50, 490) ptext = """<font name=Times-Bold color=black size=14>Face Interview during weekdays without fail.</font>""" createParagraph(p, ptext, 50, 465) p.drawString( 50, 435, "We will extend a final offer of employment, subject to you clearing a series of internal and " ) p.drawString( 50, 420, "client interviews and your final selection. Please note that this is a conditional offer and does not " ) p.drawString( 50, 405, "constitute a contract of employment, with validity of 7 working days starting from date of issue." ) stringLine = """Kindly send us an acknowledgment and confirm based on which we can process your CV """ ptext = """<u><font name=Times-Bold color=black size=14>{}</font></u>""".format( stringLine) createParagraph(p, ptext, 50, 380) ptext = """<u><font name=Times-Bold color=black size=14>further to our client.</font></u>""" createParagraph(p, ptext, 50, 365) p.drawString( 50, 310, "For any clarification please feel free to call us at 080-42134897. ") ptext = """<font name=Times-Bold color=black size=14>Thanks! </font>""" createParagraph(p, ptext, 50, 240) ptext = """<font name=Times-Bold color=black size=14>HR Manager</font>""" createParagraph(p, ptext, 50, 220) ptext = """<font name=Times-Bold color=black size=14> Brisa Technologies Pvt. Ltd., Bangalore.</font>""" createParagraph(p, ptext, 50, 200) p.save() return response
def open_lenguge(request): xml_string = '' xml_en_binario = '' xml_con_addenda = '' c = '' try: xml_upload = request.FILES.get('file_xml') add_Purchase_Order = request.POST.get('Purchase_Order') add_FileNumber_GL = request.POST.get('FileNumber_GL') add_Branch_Centre = request.POST.get('Branch_Centre') add_TransportRef = request.POST.get('TransportRef') print(add_Purchase_Order) print(add_FileNumber_GL) print(add_Branch_Centre) print(add_TransportRef) if xml_upload: xml_string = xml_upload.read() xml_en_binario = etree.fromstring(xml_string) addenda = etree.Element( etree.QName('{http://www.sat.gob.mx/cfd/3}Addenda')) knreception = etree.Element( etree.QName('{http://www.w3.org/2001/XMLSchema}KNRECEPCION'), nsmap={'kn': 'http://www.w3.org/2001/XMLSchema'}) kntipo = etree.Element( etree.QName('{http://www.w3.org/2001/XMLSchema}Tipo')) facturaskn = etree.Element( etree.QName('{http://www.w3.org/2001/XMLSchema}FacturasKN')) purchase_order = etree.Element( etree.QName( '{http://www.w3.org/2001/XMLSchema}Purchase_Order')) purchase_order.text = add_Purchase_Order branch_centre = etree.Element( etree.QName('{http://www.w3.org/2001/XMLSchema}Branch_Centre')) branch_centre.text = add_Branch_Centre transportes_ref = etree.Element( etree.QName('{http://www.w3.org/2001/XMLSchema}TransportRef')) transportes_ref.text = add_TransportRef file_number_gl = etree.Element( etree.QName('{http://www.w3.org/2001/XMLSchema}FileNumber_GL')) file_number_gl.text = add_FileNumber_GL nodo_bit = etree.tostring(knreception) addenda.append(knreception) knreception.append(kntipo) kntipo.append(facturaskn) facturaskn.append(purchase_order) facturaskn.append(file_number_gl) facturaskn.append(branch_centre) facturaskn.append(transportes_ref) add_integrada = etree.tostring(addenda) ###Agregamos la adenda en el xml se agregará en el último nodo el cual es complemento. #set_trace() xml_en_binario.append(addenda) xml_con_addenda = etree.tostring(xml_en_binario, encoding='UTF-8', xml_declaration=True).decode() print(type(xml_con_addenda)) data = xml_con_addenda response = HttpResponse( data, content_type= 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) #request.build_absolute_uri(reverse('Descargar_xml', args=(xml_con_addenda))) ##----Extraer los valores del XML print("-----Datos Comprobante-----") #Datos comprobante folio = xml_en_binario.get('Folio') print('folio', folio) serie = xml_en_binario.get('Serie') print('folio', serie) no_certificado = xml_en_binario.get('NoCertificado') print('no_certificado', no_certificado) fecha_emision = xml_en_binario.get('Fecha') print('fecha emision', fecha_emision) sello = xml_en_binario.get('Sello') print('sello', sello) tipo_comprobante = xml_en_binario.get('TipoComprobante') print('tipo comprobante', tipo_comprobante) print("-----Datos SAT-----") #Datos del sat uid = xml_en_binario[4][0].get('UUID') print('UUID', uid) fecha_timbrado = xml_en_binario[4][0].get('FechaTimbrado') print('Fecha timbrado', fecha_timbrado) sello_sat = xml_en_binario[4][0].get('SelloSat') print('Sello SAT', sello_sat) csd_sat = xml_en_binario[4][0].get('NoCertificadoSAT') print('csd sat', csd_sat) print("-----Datos Pago-----") #Datos de pago metodo_pago = xml_en_binario.get('MetodoPago') print('metodo pago', metodo_pago) forma_pago = xml_en_binario.get('FormaPago') print('forma pago', forma_pago) moneda = xml_en_binario.get('Moneda') print('moneda', moneda) tipo_cambio = xml_en_binario.get('TipoCambio') print('moneda', tipo_cambio) subtotal = xml_en_binario.get('SubTotal') print('sub total', subtotal) total = xml_en_binario.get('Total') print('total', total) print("-----Emisor-----") #Datos del emisor razon_social_emisor = xml_en_binario[0].get('Nombre') print('Razon social Emisor', razon_social_emisor) regimen_fiscal_emisor = xml_en_binario[0].get('RegimenFiscal') print('regimen fiscal Emisor', regimen_fiscal_emisor) rfc_emisor = xml_en_binario[0].get('Rfc') print('Razon social Emisor', rfc_emisor) print("-----Receptor-----") #Datos del receptor razon_social_receptor = xml_en_binario[1].get('Nombre') print('Razon social receptor', razon_social_receptor) regimen_fiscal_receptor = xml_en_binario[1].get('UsoCFDI') print('regimen fiscal receptor', regimen_fiscal_receptor) rfc_receptor = xml_en_binario[1].get('Rfc') print('Razon social receptor', rfc_receptor) print("-----Addenda-----") #Datos de la addenda Open League purchase_order = xml_en_binario[5][0][0][0][0].text print('orden de compra', purchase_order) no_expedientegl = xml_en_binario[5][0][0][0][1].text print('no. expediente GL', no_expedientegl) centro_sucursal = xml_en_binario[5][0][0][0][2].text print('centro sucursal', centro_sucursal) ref_transporte = xml_en_binario[5][0][0][0][3].text print('ref transporte', ref_transporte) #list_xml = list(xml_en_binario) #print(list_xml) opcion = request.POST.get('opcion') if opcion == 'descargar': response = HttpResponse(content_type='applicaction/pdf') response[ 'Content-Disposition'] = 'attachment; filename=XML con Addenda.pdf' buffer = BytesIO() c = canvas.Canvas(buffer, pagesize=A4) c.setLineWidth(.3) c.setFont('Helvetica', 22) c.drawString(30, 750, folio) c.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response except Exception as e: print('ecepcion en la vista open leguage => {}'.format(str(e))) return render(request, 'addenda_open_lenguage.html', {'xml_ade': xml_con_addenda})
def CanvasPDF(request): response = HttpResponse(content_type='application/pdf') fecha = '' fecha = request.POST['fecha'] buscarf = ('%s-%s-%s') %(fecha[6:10],fecha[0:2],fecha[3:5]) print buscarf pdf_name = "clientes.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() c = canvas.Canvas(buff, pagesize=letter) #Cabecera c.setLineWidth(.3) c.setFont('Helvetica-Bold', 18) c.drawString(60,650,'Reporte de Casos Atendidos en la Oficina de Atención al') c.drawString(150,630,'Ciudadano de la Zona Educativa Barinas') c.setFont('Helvetica-Bold',14) c.drawString(420,700,"Fecha: %s" %time.strftime('%d/%m/%Y')) c.line(417,697,539,697) #Logos logohead = 'media/logos/logo-mppe.jpg' logofooter = 'media/logos/cintillo_footer.png' c.drawImage(logohead, 30, 720, width=110, height=50) c.drawImage(logofooter, 20, 40, width=580, height=50) #Pie de pagina c.setLineWidth(1) c.setFont('Helvetica-Bold', 14) c.line(250,150,400,150) c.drawString(260,120,'Lcda. Yennis Perez') c.drawString(230,105,'Coordinadora de OAC Barinas') #Cabecera de la tabla styles = getSampleStyleSheet() styleBH = styles["Normal"] styleBH.alignment = TA_CENTER styleBH.fontSize = 10 styleBH.fontName = 'Helvetica-Bold' numero = Paragraph('''N° caso''',styleBH) nombre = Paragraph('''Nombres y Apellidos''',styleBH) cedula = Paragraph('''Cedula''', styleBH) departamento = Paragraph('''Departamento''', styleBH) creado = Paragraph('''Fecha de Atencion''', styleBH) usuario = Paragraph('''Atendido por''', styleBH) data= [] data.append([numero, cedula,nombre,departamento,creado,usuario]) #Tabla styleN = styles["BodyText"] styleN.alignment = TA_CENTER styleN.fontSize = 7 high = 580 centrar = 0 izquierda = 0 conteo = Caso.objects.all().count() casos = Caso.objects.filter(activo=True).filter(creado=buscarf).order_by('creado').order_by('departamento').order_by('cedula') for caso in casos: nombre = caso.nombres apellido = ' ' + caso.apellidos fullname = nombre + apellido allcasos = [caso.nrocaso, caso.cedula, fullname.upper(), caso.departamento, caso.creado.strftime("%d-%m-%Y"), caso.usuario] data.append(allcasos) high = high - 18 centrar = centrar + 1 izquierda = izquierda + 1 #Tama#o de tabla width, height = A4 table = Table(data, colWidths=[2.3 * cm, 3 * cm, 5 * cm, 3 * cm, 3 * cm, 3 * cm ]) table.setStyle(TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('LINEABOVE', (0, 0), (5, 1), 1, colors.black), ('LINEBEFORE', (0, 0), (6, 0), 1, colors.black), ('BACKGROUND', (0, 0), (6, 0), colors.lightgrey), ('ALIGN',(0, 0),(5, centrar),'CENTER'), ('ALIGN',(2, 0),(2, izquierda),'LEFT'), ])) #PDF size table.wrapOn(c, width, height) table.drawOn(c, 30, high) c.showPage() c.save() pdf = buff.getvalue() buff.close() response.write(pdf) return response
def makeDocument(filename, pageCallBack=None): #the extra arg is a hack added later, so other #tests can get hold of the canvas just before it is #saved global titlelist, closeit titlelist = [] closeit = 0 c = canvas.Canvas(filename) c.setPageCompression(0) c.setPageCallBack(pageCallBack) framePageForm(c) # define the frame form c.showOutline() framePage(c, 'PDFgen graphics API test script') makesubsection(c, "PDFgen", 10 * inch) #quickie encoding test: when canvas encoding not set, #the following should do (tm), (r) and (c) msg_uni = u'copyright\u00A9 trademark\u2122 registered\u00AE scissors\u2702: ReportLab in unicode!' msg_utf8 = msg_uni.replace('unicode', 'utf8').encode('utf8') c.drawString(100, 100, msg_uni) c.drawString(100, 80, msg_utf8) t = c.beginText(inch, 10 * inch) t.setFont('Times-Roman', 10) drawCrossHairs(c, t.getX(), t.getY()) t.textLines(""" The ReportLab library permits you to create PDF documents directly from your Python code. The "pdfgen" subpackage is the lowest level exposed to the user and lets you directly position test and graphics on the page, with access to almost the full range of PDF features. The API is intended to closely mirror the PDF / Postscript imaging model. There is an almost one to one correspondence between commands and PDF operators. However, where PDF provides several ways to do a job, we have generally only picked one. The test script attempts to use all of the methods exposed by the Canvas class, defined in reportlab/pdfgen/canvas.py First, let's look at text output. There are some basic commands to draw strings: - canvas.setFont(fontname, fontsize [, leading]) - canvas.drawString(x, y, text) - canvas.drawRightString(x, y, text) - canvas.drawCentredString(x, y, text) The coordinates are in points starting at the bottom left corner of the page. When setting a font, the leading (i.e. inter-line spacing) defaults to 1.2 * fontsize if the fontsize is not provided. For more sophisticated operations, you can create a Text Object, defined in reportlab/pdfgen/testobject.py. Text objects produce tighter PDF, run faster and have many methods for precise control of spacing and position. Basic usage goes as follows: - tx = canvas.beginText(x, y) - tx.textOut('Hello') # this moves the cursor to the right - tx.textLine('Hello again') # prints a line and moves down - y = tx.getY() # getX, getY and getCursor track position - canvas.drawText(tx) # all gets drawn at the end The green crosshairs below test whether the text cursor is working properly. They should appear at the bottom left of each relevant substring. """) t.setFillColorRGB(1, 0, 0) t.setTextOrigin(inch, 4 * inch) drawCrossHairs(c, t.getX(), t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(), t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(), t.getY()) t.textOut('textOut moves across:') drawCrossHairs(c, t.getX(), t.getY()) t.textLine('') drawCrossHairs(c, t.getX(), t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(), t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(), t.getY()) t.textLine('textLine moves down') drawCrossHairs(c, t.getX(), t.getY()) t.setTextOrigin(4 * inch, 3.25 * inch) drawCrossHairs(c, t.getX(), t.getY()) t.textLines( 'This is a multi-line\nstring with embedded newlines\ndrawn with textLines().\n' ) drawCrossHairs(c, t.getX(), t.getY()) t.textLines(['This is a list of strings', 'drawn with textLines().']) c.drawText(t) t = c.beginText(2 * inch, 2 * inch) t.setFont('Times-Roman', 10) drawCrossHairs(c, t.getX(), t.getY()) t.textOut('Small text.') drawCrossHairs(c, t.getX(), t.getY()) t.setFont('Courier', 14) t.textOut('Bigger fixed width text.') drawCrossHairs(c, t.getX(), t.getY()) t.setFont('Times-Roman', 10) t.textOut('Small text again.') drawCrossHairs(c, t.getX(), t.getY()) c.drawText(t) #try out the decimal tabs high on the right. c.setStrokeColor(colors.silver) c.line(7 * inch, 6 * inch, 7 * inch, 4.5 * inch) c.setFillColor(colors.black) c.setFont('Times-Roman', 10) c.drawString(6 * inch, 6.2 * inch, "Testing decimal alignment") c.drawString(6 * inch, 6.05 * inch, "- aim for silver line") c.line(7 * inch, 6 * inch, 7 * inch, 4.5 * inch) c.drawAlignedString(7 * inch, 5.8 * inch, "1,234,567.89") c.drawAlignedString(7 * inch, 5.6 * inch, "3,456.789") c.drawAlignedString(7 * inch, 5.4 * inch, "123") c.setFillColor(colors.red) c.drawAlignedString(7 * inch, 5.2 * inch, "(7,192,302.30)") #mark the cursor where it stopped c.showPage() ############################################################## # # page 2 - line styles # ############################################################### #page 2 - lines and styles framePage(c, 'Line Drawing Styles') # three line ends, lines drawn the hard way #firt make some vertical end markers c.setDash(4, 4) c.setLineWidth(0) c.line(inch, 9.2 * inch, inch, 7.8 * inch) c.line(3 * inch, 9.2 * inch, 3 * inch, 7.8 * inch) c.setDash() #clears it c.setLineWidth(5) c.setLineCap(0) p = c.beginPath() p.moveTo(inch, 9 * inch) p.lineTo(3 * inch, 9 * inch) c.drawPath(p) c.drawString(4 * inch, 9 * inch, 'the default - butt caps project half a width') makesubsection(c, "caps and joins", 8.5 * inch) c.setLineCap(1) p = c.beginPath() p.moveTo(inch, 8.5 * inch) p.lineTo(3 * inch, 8.5 * inch) c.drawPath(p) c.drawString(4 * inch, 8.5 * inch, 'round caps') c.setLineCap(2) p = c.beginPath() p.moveTo(inch, 8 * inch) p.lineTo(3 * inch, 8 * inch) c.drawPath(p) c.drawString(4 * inch, 8 * inch, 'square caps') c.setLineCap(0) # three line joins c.setLineJoin(0) p = c.beginPath() p.moveTo(inch, 7 * inch) p.lineTo(2 * inch, 7 * inch) p.lineTo(inch, 6.7 * inch) c.drawPath(p) c.drawString(4 * inch, 6.8 * inch, 'Default - mitered join') c.setLineJoin(1) p = c.beginPath() p.moveTo(inch, 6.5 * inch) p.lineTo(2 * inch, 6.5 * inch) p.lineTo(inch, 6.2 * inch) c.drawPath(p) c.drawString(4 * inch, 6.3 * inch, 'round join') c.setLineJoin(2) p = c.beginPath() p.moveTo(inch, 6 * inch) p.lineTo(2 * inch, 6 * inch) p.lineTo(inch, 5.7 * inch) c.drawPath(p) c.drawString(4 * inch, 5.8 * inch, 'bevel join') c.setDash(6, 6) p = c.beginPath() p.moveTo(inch, 5 * inch) p.lineTo(3 * inch, 5 * inch) c.drawPath(p) c.drawString(4 * inch, 5 * inch, 'dash 6 points on, 6 off- setDash(6,6) setLineCap(0)') makesubsection(c, "dash patterns", 5 * inch) c.setLineCap(1) p = c.beginPath() p.moveTo(inch, 4.5 * inch) p.lineTo(3 * inch, 4.5 * inch) c.drawPath(p) c.drawString(4 * inch, 4.5 * inch, 'dash 6 points on, 6 off- setDash(6,6) setLineCap(1)') c.setLineCap(0) c.setDash([1, 2, 3, 4, 5, 6], 0) p = c.beginPath() p.moveTo(inch, 4.0 * inch) p.lineTo(3 * inch, 4.0 * inch) c.drawPath(p) c.drawString(4 * inch, 4 * inch, 'dash growing - setDash([1,2,3,4,5,6],0) setLineCap(0)') c.setLineCap(1) c.setLineJoin(1) c.setDash(32, 12) p = c.beginPath() p.moveTo(inch, 3.0 * inch) p.lineTo(2.5 * inch, 3.0 * inch) p.lineTo(inch, 2 * inch) c.drawPath(p) c.drawString(4 * inch, 3 * inch, 'dash pattern, join and cap style interacting - ') c.drawString(4 * inch, 3 * inch - 12, 'round join & miter results in sausages') c.textAnnotation('Annotation', Rect=(4 * inch, 3 * inch - 72, inch, inch - 12)) c.showPage() ############################################################## # # higher level shapes # ############################################################### framePage(c, 'Shape Drawing Routines') t = c.beginText(inch, 10 * inch) t.textLines(""" Rather than making your own paths, you have access to a range of shape routines. These are built in pdfgen out of lines and bezier curves, but use the most compact set of operators possible. We can add any new ones that are of general use at no cost to performance.""") t.textLine() #line demo makesubsection(c, "lines", 9 * inch) c.line(inch, 9 * inch, 3 * inch, 9 * inch) t.setTextOrigin(4 * inch, 9 * inch) t.textLine('canvas.line(x1, y1, x2, y2)') #bezier demo - show control points makesubsection(c, "bezier curves", 8.5 * inch) (x1, y1, x2, y2, x3, y3, x4, y4) = (inch, 7.8 * inch, 1.2 * inch, 8.8 * inch, 3 * inch, 8.8 * inch, 3.5 * inch, 8.05 * inch) c.bezier(x1, y1, x2, y2, x3, y3, x4, y4) c.setDash(3, 3) c.line(x1, y1, x2, y2) c.line(x3, y3, x4, y4) c.setDash() t.setTextOrigin(4 * inch, 8.3 * inch) t.textLine('canvas.bezier(x1, y1, x2, y2, x3, y3, x4, y4)') #rectangle makesubsection(c, "rectangles", 8 * inch) c.rect(inch, 7 * inch, 2 * inch, 0.75 * inch) t.setTextOrigin(4 * inch, 7.375 * inch) t.textLine('canvas.rect(x, y, width, height) - x,y is lower left') c.roundRect(inch, 6.25 * inch, 2 * inch, 0.6 * inch, 0.1 * inch) t.setTextOrigin(4 * inch, 6.55 * inch) t.textLine('canvas.roundRect(x,y,width,height,radius)') makesubsection(c, "arcs", 8 * inch) c.arc(inch, 5 * inch, 3 * inch, 6 * inch, 0, 90) t.setTextOrigin(4 * inch, 5.5 * inch) t.textLine('canvas.arc(x1, y1, x2, y2, startDeg, extentDeg)') t.textLine('Note that this is an elliptical arc, not just circular!') #wedge makesubsection(c, "wedges", 5 * inch) c.wedge(inch, 4.5 * inch, 3 * inch, 3.5 * inch, 0, 315) t.setTextOrigin(4 * inch, 4 * inch) t.textLine('canvas.wedge(x1, y1, x2, y2, startDeg, extentDeg)') t.textLine('Note that this is an elliptical arc, not just circular!') #wedge the other way c.wedge(inch, 3.75 * inch, 3 * inch, 2.75 * inch, 0, -45) t.setTextOrigin(4 * inch, 3 * inch) t.textLine('Use a negative extent to go clockwise') #circle makesubsection(c, "circles", 3.5 * inch) c.circle(1.5 * inch, 2 * inch, 0.5 * inch) c.circle(3 * inch, 2 * inch, 0.5 * inch) t.setTextOrigin(4 * inch, 2 * inch) t.textLine('canvas.circle(x, y, radius)') c.drawText(t) c.showPage() ############################################################## # # Page 4 - fonts # ############################################################### framePage(c, "Font Control") c.drawString(inch, 10 * inch, 'Listing available fonts...') y = 9.5 * inch for fontname in c.getAvailableFonts(): c.setFont(fontname, 24) c.drawString(inch, y, 'This should be %s' % fontname) y = y - 28 makesubsection(c, "fonts and colors", 4 * inch) c.setFont('Times-Roman', 12) t = c.beginText(inch, 4 * inch) t.textLines("""Now we'll look at the color functions and how they interact with the text. In theory, a word is just a shape; so setFillColorRGB() determines most of what you see. If you specify other text rendering modes, an outline color could be defined by setStrokeColorRGB() too""") c.drawText(t) t = c.beginText(inch, 2.75 * inch) t.setFont('Times-Bold', 36) t.setFillColor(colors.green) #green t.textLine('Green fill, no stroke') #t.setStrokeColorRGB(1,0,0) #ou can do this in a text object, or the canvas. t.setStrokeColor( colors.red) #ou can do this in a text object, or the canvas. t.setTextRenderMode(2) # fill and stroke t.textLine('Green fill, red stroke - yuk!') t.setTextRenderMode(0) # back to default - fill only t.setFillColorRGB(0, 0, 0) #back to default t.setStrokeColorRGB(0, 0, 0) #ditto c.drawText(t) c.showPage() ######################################################################### # # Page 5 - coord transforms # ######################################################################### framePage(c, "Coordinate Transforms") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines( """This shows coordinate transformations. We draw a set of axes, moving down the page and transforming space before each one. You can use saveState() and restoreState() to unroll transformations. Note that functions which track the text cursor give the cursor position in the current coordinate system; so if you set up a 6 inch high frame 2 inches down the page to draw text in, and move the origin to its top left, you should stop writing text after six inches and not eight.""") c.drawText(t) drawAxes(c, "0. at origin") c.addLiteral('%about to translate space') c.translate(2 * inch, 7 * inch) drawAxes(c, '1. translate near top of page') c.saveState() c.translate(1 * inch, -2 * inch) drawAxes(c, '2. down 2 inches, across 1') c.restoreState() c.saveState() c.translate(0, -3 * inch) c.scale(2, -1) drawAxes(c, '3. down 3 from top, scale (2, -1)') c.restoreState() c.saveState() c.translate(0, -5 * inch) c.rotate(-30) drawAxes(c, "4. down 5, rotate 30' anticlockwise") c.restoreState() c.saveState() c.translate(3 * inch, -5 * inch) c.skew(0, 30) drawAxes(c, "5. down 5, 3 across, skew beta 30") c.restoreState() c.showPage() ######################################################################### # # Page 6 - clipping # ######################################################################### framePage(c, "Clipping") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines( """This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text.""") c.drawText(t) c.saveState() #c.setFillColorRGB(0,0,1) p = c.beginPath() #make a chesboard effect, 1 cm squares for i in range(14): x0 = (3 + i) * cm for j in range(7): y0 = (16 + j) * cm p.rect(x0, y0, 0.85 * cm, 0.85 * cm) c.addLiteral('%Begin clip path') c.clipPath(p) c.addLiteral('%End clip path') t = c.beginText(3 * cm, 22.5 * cm) t.textLines( """This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text. This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text. This shows clipping at work. We draw a chequerboard of rectangles into a path object, and clip it. This then forms a mask which limits the region of the page on which one can draw. This paragraph was drawn after setting the clipping path, and so you should only see part of the text.""") c.drawText(t) c.restoreState() t = c.beginText(inch, 5 * inch) t.textLines( """You can also use text as an outline for clipping with the text render mode. The API is not particularly clean on this and one has to follow the right sequence; this can be optimized shortly.""") c.drawText(t) #first the outline c.saveState() t = c.beginText(inch, 3.0 * inch) t.setFont('Helvetica-BoldOblique', 108) t.setTextRenderMode(5) #stroke and add to path t.textLine('Python!') t.setTextRenderMode(0) c.drawText(t) #this will make a clipping mask #now some small stuff which wil be drawn into the current clip mask t = c.beginText(inch, 4 * inch) t.setFont('Times-Roman', 6) t.textLines((('spam ' * 40) + '\n') * 15) c.drawText(t) #now reset canvas to get rid of the clipping mask c.restoreState() c.showPage() ######################################################################### # # Page 7 - images # ######################################################################### framePage(c, "Images") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) if not haveImages: c.drawString( inch, 11 * inch, "Python or Java Imaging Library not found! Below you see rectangles instead of images." ) t.textLines( """PDFgen uses the Python Imaging Library (or, under Jython, java.awt.image and javax.imageio) to process a very wide variety of image formats. This page shows image capabilities. If I've done things right, the bitmap should have its bottom left corner aligned with the crosshairs. There are two methods for drawing images. The recommended use is to call drawImage. This produces the smallest PDFs and the fastest generation times as each image's binary data is only embedded once in the file. Also you can use advanced features like transparency masks. You can also use drawInlineImage, which puts images in the page stream directly. This is slightly faster for Acrobat to render or for very small images, but wastes space if you use images more than once.""") c.drawText(t) if haveImages: from reportlab.lib.testutils import testsFolder gif = os.path.join(testsFolder, 'pythonpowered.gif') c.drawInlineImage(gif, 2 * inch, 7 * inch) else: c.rect(2 * inch, 7 * inch, 110, 44) c.line(1.5 * inch, 7 * inch, 4 * inch, 7 * inch) c.line(2 * inch, 6.5 * inch, 2 * inch, 8 * inch) c.drawString(4.5 * inch, 7.25 * inch, 'inline image drawn at natural size') if haveImages: c.drawInlineImage(gif, 2 * inch, 5 * inch, inch, inch) else: c.rect(2 * inch, 5 * inch, inch, inch) c.line(1.5 * inch, 5 * inch, 4 * inch, 5 * inch) c.line(2 * inch, 4.5 * inch, 2 * inch, 6 * inch) c.drawString(4.5 * inch, 5.25 * inch, 'inline image distorted to fit box') c.drawString( 1.5 * inch, 4 * inch, 'Image XObjects can be defined once in the file and drawn many times.') c.drawString(1.5 * inch, 3.75 * inch, 'This results in faster generation and much smaller files.') for i in range(5): if haveImages: (w, h) = c.drawImage(gif, (1.5 + i) * inch, 3 * inch) else: (w, h) = (144, 10) c.rect((1.5 + i) * inch, 3 * inch, 110, 44) myMask = [254, 255, 222, 223, 0, 1] c.drawString( 1.5 * inch, 2.5 * inch, "The optional 'mask' parameter lets you define transparent colors. We used a color picker" ) c.drawString( 1.5 * inch, 2.3 * inch, "to determine that the yellow in the image above is RGB=(225,223,0). We then define a mask" ) c.drawString( 1.5 * inch, 2.1 * inch, "spanning these RGB values: %s. The background vanishes!!" % myMask) c.drawString(2.5 * inch, 1.2 * inch, 'This would normally be obscured') if haveImages: c.drawImage(gif, 1 * inch, 1.2 * inch, w, h, mask=myMask) c.drawImage(gif, 3 * inch, 1.2 * inch, w, h, mask='auto') else: c.rect(1 * inch, 1.2 * inch, w, h) c.rect(3 * inch, 1.2 * inch, w, h) c.showPage() c.drawString( 1 * inch, 10.25 * inch, "For rgba type images we can use the alpha channel if we set mask='auto'." ) c.drawString(1 * inch, 10.25 * inch - 14.4, "The first image is solid red with variable alpha.") c.drawString(1 * inch, 10.25 * inch - 2 * 14.4, "The second image is white alpha=0% to purple=100%") for i in xrange(8): c.drawString(1 * inch, 8 * inch + i * 14.4, "mask=None Line %d" % i) c.drawString(3 * inch, 8 * inch + i * 14.4, "mask='auto' Line %d" % i) c.drawString(1 * inch, 6 * inch + i * 14.4, "mask=None Line %d" % i) c.drawString(3 * inch, 6 * inch + i * 14.4, "mask='auto' Line %d" % i) w = 100 h = 75 c.rect(1 * inch, 8 + 14.4 * inch, w, h) c.rect(3 * inch, 8 + 14.4 * inch, w, h) c.rect(1 * inch, 6 + 14.4 * inch, w, h) c.rect(3 * inch, 6 + 14.4 * inch, w, h) if haveImages: from reportlab.lib.testutils import testsFolder png = os.path.join(testsFolder, 'solid_red_alpha.png') c.drawImage(png, 1 * inch, 8 * inch + 14.4, w, h, mask=None) c.drawImage(png, 3 * inch, 8 * inch + 14.4, w, h, mask='auto') png = os.path.join(testsFolder, 'alpha_test.png') c.drawImage(png, 1 * inch, 6 * inch + 14.4, w, h, mask=None) c.drawImage(png, 3 * inch, 6 * inch + 14.4, w, h, mask='auto') c.showPage() if haveImages: import shutil c.drawString(1 * inch, 10.25 * inch, 'This jpeg is actually a gif') jpg = outputfile('_i_am_actually_a_gif.jpg') shutil.copyfile(gif, jpg) c.drawImage(jpg, 1 * inch, 9.25 * inch, w, h, mask='auto') tjpg = os.path.join(os.path.dirname(os.path.dirname(gif)), 'docs', 'images', 'lj8100.jpg') if os.path.isfile(tjpg): c.drawString(4 * inch, 10.25 * inch, 'This gif is actually a jpeg') tgif = outputfile(os.path.basename('_i_am_actually_a_jpeg.gif')) shutil.copyfile(tjpg, tgif) c.drawImage(tgif, 4 * inch, 9.25 * inch, w, h, mask='auto') c.drawString(inch, 9.0 * inch, 'Image positioning tests with preserveAspectRatio') #preserveAspectRatio test c.drawString( inch, 8.8 * inch, 'Both of these should appear within the boxes, vertically centered' ) x, y, w, h = inch, 6.75 * inch, 2 * inch, 2 * inch c.rect(x, y, w, h) (w2, h2) = c.drawImage( gif, #anchor southwest, drawImage x, y, width=w, height=h, preserveAspectRatio=True, anchor='c') #now test drawInlineImage across the page x = 5 * inch c.rect(x, y, w, h) (w2, h2) = c.drawInlineImage( gif, #anchor southwest, drawInlineImage x, y, width=w, height=h, preserveAspectRatio=True, anchor='c') c.drawString( inch, 5.75 * inch, 'anchored by respective corners - use both a wide and a tall one as tests' ) x = 0.25 * inch for anchor in ['nw', 'n', 'ne', 'w', 'c', 'e', 'sw', 's', 'se']: x += 0.75 * inch c.rect(x, 5 * inch, 0.6 * inch, 0.6 * inch) c.drawImage(gif, x, 5 * inch, width=0.6 * inch, height=0.6 * inch, preserveAspectRatio=True, anchor=anchor) c.drawString(x, 4.9 * inch, anchor) x = 0.25 * inch tall_red = os.path.join(testsFolder, 'tall_red.png') for anchor in ['nw', 'n', 'ne', 'w', 'c', 'e', 'sw', 's', 'se']: x += 0.75 * inch c.rect(x, 4 * inch, 0.6 * inch, 0.6 * inch) c.drawImage(tall_red, x, 4 * inch, width=0.6 * inch, height=0.6 * inch, preserveAspectRatio=True, anchor=anchor) c.drawString(x, 3.9 * inch, anchor) c.showPage() ######################################################################### # # Page 8 - Forms and simple links # ######################################################################### framePage(c, "Forms and Links") c.setFont('Times-Roman', 12) t = c.beginText(inch, 10 * inch) t.textLines("""Forms are sequences of text or graphics operations which are stored only once in a PDF file and used as many times as desired. The blue logo bar to the left is an example of a form in this document. See the function framePageForm in this demo script for an example of how to use canvas.beginForm(name, ...) ... canvas.endForm(). Documents can also contain cross references where (for example) a rectangle on a page may be bound to a position on another page. If the user clicks on the rectangle the PDF viewer moves to the bound position on the other page. There are many other types of annotations and links supported by PDF. For example, there is a bookmark to each page in this document and below is a browsable index that jumps to those pages. In addition we show two URL hyperlinks; for these, you specify a rectangle but must draw the contents or any surrounding rectangle yourself. """) c.drawText(t) nentries = len(titlelist) xmargin = 3 * inch xmax = 7 * inch ystart = 6.54 * inch ydelta = 0.4 * inch for i in range(nentries): yposition = ystart - i * ydelta title = titlelist[i] c.drawString(xmargin, yposition, title) c.linkAbsolute(title, title, (xmargin - ydelta / 4, yposition - ydelta / 4, xmax, yposition + ydelta / 2)) # test URLs r1 = (inch, 3 * inch, 5 * inch, 3.25 * inch) # this is x1,y1,x2,y2 c.linkURL('http://www.reportlab.com/', r1, thickness=1, color=colors.green) c.drawString(inch + 3, 3 * inch + 6, 'Hyperlink to www.reportlab.com, with green border') r1 = (inch, 2.5 * inch, 5 * inch, 2.75 * inch) # this is x1,y1,x2,y2 c.linkURL('mailto:[email protected]', r1) #, border=0) c.drawString(inch + 3, 2.5 * inch + 6, 'mailto: hyperlink, without border') r1 = (inch, 2 * inch, 5 * inch, 2.25 * inch) # this is x1,y1,x2,y2 c.linkURL('http://www.reportlab.com/', r1, thickness=2, dashArray=[2, 4], color=colors.magenta) c.drawString(inch + 3, 2 * inch + 6, 'Hyperlink with custom border style') xpdf = fileName2Utf8(outputfile('test_hello.pdf').replace('\\', '/')) link = 'Hard link to %s, with red border' % xpdf r1 = (inch, 1.5 * inch, inch + 2 * 3 + c.stringWidth(link, c._fontname, c._fontsize), 1.75 * inch) # this is x1,y1,x2,y2 c.linkURL(xpdf, r1, thickness=1, color=colors.red, kind='GoToR') c.drawString(inch + 3, 1.5 * inch + 6, link) c.showPage() ############# colour gradients title = 'Gradients code contributed by Peter Johnson <*****@*****.**>' c.drawString(1 * inch, 10.8 * inch, title) c.addOutlineEntry(title + " section", title, level=0, closed=True) c.bookmarkHorizontalAbsolute(title, 10.8 * inch) from reportlab.lib.colors import red, green, blue c.saveState() p = c.beginPath() p.moveTo(1 * inch, 2 * inch) p.lineTo(1.5 * inch, 2.5 * inch) p.curveTo(2 * inch, 3 * inch, 3.0 * inch, 3 * inch, 4 * inch, 2.9 * inch) p.lineTo(5.5 * inch, 2.1 * inch) p.close() c.clipPath(p) # Draw a linear gradient from (0, 2*inch) to (5*inch, 3*inch), from orange to white. # The gradient will extend past the endpoints (so you probably want a clip path in place) c.linearGradient(1 * inch, 2 * inch, 6 * inch, 3 * inch, (red, blue)) c.restoreState() # Draw a radial gradient with a radius of 3 inches. # The color starts orange and stays orange until 20% of the radius, # then fades to white at 80%, and ends up green at 3 inches from the center. # Since extend is false, the gradient stops drawing at the edge of the circle. c.radialGradient(4 * inch, 6 * inch, 3 * inch, (red, green, blue), (0.2, 0.8, 1.0), extend=False) c.showPage() ### now do stuff for the outline #for x in outlinenametree: print x #stop #c.setOutlineNames0(*outlinenametree) return c
def __init__(self, pdf_file): """""" self.canvas = canvas.Canvas(pdf_file, pagesize=letter) self.styles = getSampleStyleSheet() self.width, self.height = letter
############################# # Generate Personalized Form ############################# from reportlab.pdfgen import canvas # parameters width, height = letter top_margin = 1 * inch left_margin = 0.8 * inch # 1.2*inch right_margin = 0.68 * inch bottom_margin = 0.45 * inch # Instantiate the Document c = canvas.Canvas("Enrichment_forms.pdf", pagesize=letter) c.setAuthor("Alvaro Feito Boirac") def add_header(student, c): c.drawImage('bhs_CMYK.tif', width - 2.5 * inch, height - 0.99 * inch, 178 / 1.8, 60 / 1.8) c.setFont("Helvetica", 28) c.drawString(width / 2 - 4 * cm, height - 2 * inch, "Enrichment Activity - " + student[1]) c.setFont("Helvetica", 26) c.drawString(width / 2 - 3 * cm, height - 2.4 * inch, "Sign-up Sheet") def add_identity(student, c): qr = qrcode.QRCode(
liste = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"] ## Saisie des paramètres ################################## fichierQuestions = sys.argv[1] nouveauFichier = sys.argv[2] if sys.argv[3] == "false": anonymat = False else: anonymat = True numSujet = sys.argv[4] ########################################################### canvas = canvas.Canvas(nouveauFichier) titre = retournerTitre(fichierQuestions) presentation = retournerPresentation(fichierQuestions) colonnes = retournerColonnes(fichierQuestions) ## creation d'une liste contenant toutes les questions questions = retournerQuestions(fichierQuestions) ## Feuilles des questions ###### canvas.setFont('Helvetica-Bold', 12) canvas.drawCentredString(300, 710, titre) canvas.setFont('Helvetica', 12) canvas.drawString(500, 770, "Sujet " + numSujet)
def pdf2(correo): output = io.BytesIO() p = canvas.Canvas("/usr/src/app/project/extractos.pdf") data = request.get_json() envios_recibidos = data[u'total_receive'] envios_realizados = data[u'total_send'] cargas_tarjeta = data[u'total_load'] p.setFont('Helvetica-Bold', 10) p.drawString(20, 810, "Cargas desde tarjeta....... " + str(cargas_tarjeta)) p.drawString(20, 795, "Envios recibidos........... " + str(envios_recibidos)) p.drawString(20, 780, "Envios realizados.......... " + str(envios_realizados)) #Nombres de columna de DINERO RECIBIDO p.setFont('Helvetica-Bold', 12) p.drawString(15, 755, "DINERO RECIBIDO:") p.setFont('Helvetica-Bold', 10) p.drawString(20, 740, "N. Transacción") p.drawString(110, 740, "Remitente") p.drawString(210, 740, "Monto") p.drawString(300, 740, "Estado") p.drawString(370, 740, "Fecha") p.drawString(470, 740, "Hora") aux = 695 - 15 * (envios_recibidos) #Nombres de columna de DINERO ENVIADO p.setFont('Helvetica-Bold', 12) p.drawString(15, aux + 15, "DINERO ENVIADO:") p.setFont('Helvetica-Bold', 10) p.drawString(20, aux, "N. Transacción") p.drawString(110, aux, "Destinatario") p.drawString(210, aux, "Monto") p.drawString(300, aux, "Estado") p.drawString(370, aux, "Fecha") p.drawString(470, aux, "Hora") p.setFont('Helvetica', 9) fila = 15 for i in range(0, len(data[u'list_receive'])): tam_id = len(str(data[u'list_receive'][i][u'id'])) p.drawString(24, 740 - fila, ('0' * (10 - tam_id)) + str(data[u'list_receive'][i][u'id'])) tam_id2 = len(str(data[u'list_receive'][i][u'useridgiving'])) p.drawString(114, 740 - fila, ('0' * (10 - tam_id2)) + str(data[u'list_receive'][i][u'useridgiving'])) p.drawString(214, 740 - fila, '$' + str(data[u'list_receive'][i][u'amount'])) p.drawString(304, 740 - fila, str(data[u'list_receive'][i][u'state'])) s_aux = str(data[u'list_receive'][i][u'updated_at']) hora = "" fecha = "" b_aux = 1 for c in s_aux: if (c == 'T'): b_aux = 0 elif (c == 'Z'): b_aux = 0 elif (b_aux == 1): fecha += c else: hora += c p.drawString(374, 740 - fila, fecha) p.drawString(474, 740 - fila, hora) fila += 15 fila = 15 for i in range(0, len(data[u'list_send'])): tam_id = len(str(data[u'list_send'][i][u'id'])) p.drawString(24, aux - fila, ('0' * (10 - tam_id)) + str(data[u'list_send'][i][u'id'])) tam_id2 = len(str(data[u'list_send'][i][u'useridreceiving'])) p.drawString(114, aux - fila, ('0' * (10 - tam_id2)) + str(data[u'list_send'][i][u'useridreceiving'])) p.drawString(214, aux - fila, '$' + str(data[u'list_send'][i][u'amount'])) p.drawString(304, aux - fila, str(data[u'list_send'][i][u'state'])) s_aux = str(data[u'list_send'][i][u'updated_at']) hora = "" fecha = "" b_aux = 1 for c in s_aux: if (c == 'T'): b_aux = 0 elif (c == 'Z'): b_aux = 0 elif (b_aux == 1): fecha += c else: hora += c p.drawString(374, aux - fila, fecha) p.drawString(474, aux - fila, hora) fila += 15 aux = aux - fila - 30 p.setFont('Helvetica-Bold', 12) p.drawString(15, aux + 15, "DINERO CARGADO DESDE LA TARJETA:") p.setFont('Helvetica-Bold', 10) #Nombres de columna de cargas desde tarjeta p.drawString(20, aux, "N. Transacción") p.drawString(210, aux, "Monto") p.drawString(300, aux, "Estado") p.drawString(370, aux, "Fecha") p.drawString(470, aux, "Hora") p.setFont('Helvetica', 9) fila = 15 for i in range(0, len(data[u'list_load'])): tam_id = len(str(data[u'list_load'][i][u'id'])) p.drawString(24, aux - fila, ('0' * (10 - tam_id)) + str(data[u'list_load'][i][u'id'])) p.drawString(214, aux - fila, '$' + str(data[u'list_load'][i][u'amount'])) p.drawString(304, aux - fila, str(data[u'list_load'][i][u'state'])) s_aux = str(data[u'list_load'][i][u'updated_at']) hora = "" fecha = "" b_aux = 1 for c in s_aux: if (c == 'T'): b_aux = 0 elif (c == 'Z'): b_aux = 0 elif (b_aux == 1): fecha += c else: hora += c p.drawString(374, aux - fila, fecha) p.drawString(474, aux - fila, hora) fila += 15 #p.showPage() p.save() msg = Message("Extractos", sender="*****@*****.**", recipients=[correo]) with app.open_resource("extractos.pdf") as fp: msg.attach("extractos.pdf", "application/pdf", fp.read()) mail.send(msg) pdf_out = output.getvalue() output.close() return "Sent"
def factsheetbrewer(png_region=None, png_spaghetti=None, png_uncertainty=None, png_robustness=None): """ Put graphics into the climate fact sheet template to generate the final climate fact sheet :param png_region: World map graphic with countries polygons. :param png_uncertainty: Graphic showing a timeseries with fieldmean values and corresponding uncertainty :param png_spaghetti: Graphic showing each datatset as a single timeseries :param png_robustness: Map of the signal change including hashes and dots for robutsness values :return pdf foumular: pdf with fillable text boxes for interpretation text """ from PyPDF2 import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas from flyingpigeon.config import data_path try: try: _, pdf_region = mkstemp(dir='.', suffix='.pdf') c = canvas.Canvas(pdf_region) c.drawImage(png_region, 340, 490, width=130, height=130) # , mask=None, preserveAspectRatio=False) c.save() pfr_region = PdfFileReader(open(pdf_region, 'rb')) except: LOGGER.exception('failed to convert png to pdf') try: _, pdf_uncertainty = mkstemp(dir='.', suffix='.pdf') c = canvas.Canvas(pdf_uncertainty) c.drawImage(png_uncertainty, 20, 350, width=250, height=130) # , mask=None, preserveAspectRatio=False) c.save() pfr_uncertainty = PdfFileReader(open(pdf_uncertainty, 'rb')) except: LOGGER.exception('failed to convert png to pdf') try: _, pdf_spaghetti = mkstemp(dir='.', suffix='.pdf') c = canvas.Canvas(pdf_spaghetti) c.drawImage(png_spaghetti, 280, 350, width=250, height=130) # , mask=None, preserveAspectRatio=False) c.save() pfr_spagetthi = PdfFileReader(open(pdf_spaghetti, 'rb')) except: LOGGER.exception('failed to convert png to pdf') try: _, pdf_robustness = mkstemp(dir='.', suffix='.pdf') c = canvas.Canvas(pdf_robustness) c.drawImage(png_robustness, 30, 100, width=200, height=170) # , mask=None, preserveAspectRatio=False) c.save() pfr_robustness = PdfFileReader(open(pdf_robustness, 'rb')) except: LOGGER.exception('failed to convert png to pdf') output_file = PdfFileWriter() pfr_template = PdfFileReader( file(data_path() + '/pdf/climatefactsheettemplate.pdf', 'rb')) LOGGER.debug('template: %s' % pfr_template) page_count = pfr_template.getNumPages() for page_number in range(page_count): LOGGER.debug("Plotting png to {} of {}".format( page_number, page_count)) input_page = pfr_template.getPage(page_number) try: input_page.mergePage(pfr_region.getPage(0)) except: LOGGER.warn('failed to merge courtry map') try: input_page.mergePage(pfr_uncertainty.getPage(0)) except: LOGGER.warn('failed to merge uncertainty plot') try: input_page.mergePage(pfr_spagetthi.getPage(0)) except: LOGGER.warn('failed to merge spaghetti plot') try: input_page.mergePage(pfr_robustness.getPage(0)) except: LOGGER.warn('failed to merge robustness plot') try: output_file.addPage(input_page) except: LOGGER.warn('failed to add page to output pdf') try: _, climatefactsheet = mkstemp(dir='.', suffix='.pdf') with open(climatefactsheet, 'wb') as outputStream: output_file.write(outputStream) LOGGER.info('sucessfully brewed the demanded factsheet') except: LOGGER.exception( 'failed write filled template to pdf. empty template will be set as output' ) climatefactsheet = data_path( ) + '/pdf/climatefactsheettemplate.pdf' except: LOGGER.exception( "failed to brew the factsheet, empty template will be set as output" ) return climatefactsheet
def gerar_pdf_carteirinha(request, pk): aluno = Aluno.objects.get(pk=pk) # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="carteirinha_webCGAE.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) x1 = 190 x2 = 450 y1 = 585 y2 = 420 #retangulo p.line(x1, y1, x2, y1) #horizontal superior p.line(x1, y1, x1, y2) #vertical esquerda p.line(x2, y1, x2, y2) #vertical direita p.line(x1, y2, x2, y2) #horizontal inferior p.setFont("Times-Roman", 14) fn = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static/Atividades/icon_ifc.png') p.drawImage(fn, 200, 514, width=135, height=70) try: img = aluno.perfil_aluno.foto.name fn = os.path.join(os.path.dirname(os.path.abspath('__file__')), 'media/%s' % img) p.drawImage(fn, 369, 504, width=80, height=80) except: pass # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. x1 = 195 x2 = x1 + 250 y1 = 498 y2 = y1 - 20 X_NOME = 205 Y_NOME = y1 - 15 p.drawString(x1 + 5, y1 + 2, "NOME:") p.line(x1, y1, x2, y1) #hor sup p.line(x1, y1, x1, y2) #vert esq p.line(x2, y1, x2, y2) #vert dir p.line(x1, y2, x2, y2) #hor inf p.drawString(X_NOME, Y_NOME, "%s" % aluno.nome.upper()) x1 = 195 x2 = x1 + 110 y1 = 455 y2 = y1 - 20 X_MAT = X_NOME Y_MAT = y1 - 15 p.drawString(x1 + 5, y1 + 2, "MATRÍCULA:") p.line(x1, y1, x2, y1) #hor sup p.line(x1, y1, x1, y2) #vert esq p.line(x2, y1, x2, y2) #vert dir p.line(x1, y2, x2, y2) #hor inf p.drawString(X_MAT, Y_MAT, "%s" % aluno.matricula) x1 = 320 x2 = x1 + 50 y1 = 455 y2 = y1 - 20 X_ALOJA = x1 + 5 Y_ALOJA = y1 - 15 p.drawString(x1, y1 + 2, "ALOJA:") p.line(x1, y1, x2, y1) #hor sup p.line(x1, y1, x1, y2) #vert esq p.line(x2, y1, x2, y2) #vert dir p.line(x1, y2, x2, y2) #hor inf p.drawString(X_ALOJA, Y_ALOJA, "%s" % aluno.alojamento) x1 = 385 x2 = x1 + 60 y1 = 455 y2 = y1 - 20 X_TURMA = x1 + 5 Y_TURMA = y1 - 15 p.drawString(x1, y1 + 2, "TURMA:") p.line(x1, y1, x2, y1) #hor sup p.line(x1, y1, x1, y2) #vert esq p.line(x2, y1, x2, y2) #vert dir p.line(x1, y2, x2, y2) #hor inf p.drawString(X_TURMA, Y_TURMA, "%s" % aluno.turma) # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response
def gerar_pdf(): nome = orca.nome.text() cpf = orca.cpf.text() endereco = orca.endereco.text() bairro = orca.bairro.text() cidade = orca.cidade.text() cep = orca.cep.text() telefone = orca.telefone.text() email = orca.email.text() modelo = orca.modelo.text() marca = orca.marca.text() ano = orca.ano.text() placa = orca.placa.text() km = orca.km.text() data = orca.data.text() cor = orca.cor.currentText() data_atual = date.today() data_em_texto = '{}/{}/{}'.format(data_atual.day, data_atual.month, data_atual.year) data_em_texto = str(data_em_texto) pdfmetrics.registerFont( TTFont('Times-New-Roman', 'c:\\windows\\fonts\\times.ttf')) pdfmetrics.registerFont( TTFont('Times-New-RomanBd', 'c:\\windows\\fonts\\timesBd.ttf')) pdfmetrics.registerFont( TTFont('Times-New-RomanIt', 'c:\\windows\\fonts\\timesI.ttf')) pdfmetrics.registerFont( TTFont('Times-New-RomanBI', 'c:\\windows\\fonts\\timesBI.ttf')) packet = io.BytesIO() # Veiculo can = canvas.Canvas(packet, pagesize=letter) can.setFont('Times-New-Roman', 12) #Modelo can.drawString(72, 701, modelo.upper()) #Marca can.drawString(72, 687, marca.upper()) #Cor can.drawString(55, 673, cor) #Ano can.drawString(202, 701, ano) #Placa can.drawString(208, 687, placa.upper()) #Km can.drawString(200, 673, km + ' Km') #Data da Retirada can.drawString(500, 701, data) #Cliente can.setFont('Times-New-Roman', 10) #Nome can.drawString(70, 191, nome.title()) #CPF can.drawString(83, 181, cpf) #Endereço can.drawString(73, 168, endereco.title()) #Bairro can.drawString(65, 157, bairro.title()) #Telefone can.drawString(75, 146, telefone) #Email can.drawString(65, 134, email) #Cidade can.drawString(385, 191, cidade.title()) #CEP can.drawString(375, 181, cep) can.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(open("system_control_mecanica_666.pdf", "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) # finally, write "output" to a real file outputStream = open(nome + ".pdf", "wb") output.write(outputStream) outputStream.close()
def post(self, request): order = request.data.get('order') print(order) user_id = request.user user_folder = os.path.join(settings.STATIC_DIR, 'sentinels', f'user_{user_id}') orders_folders = os.path.join(settings.STATIC_DIR, 'orders') zipes_directory = os.path.join(settings.STATIC_DIR, 'sentinels', f'user_{user_id}', 'zipes') reprojected_directory = os.path.join(settings.STATIC_DIR, 'sentinels', f'user_{user_id}', 'reprojected') extract_directory = os.path.join(settings.STATIC_DIR, 'sentinels', f'user_{user_id}', 'extract') rasters_directory = os.path.join(settings.STATIC_DIR, 'sentinels', f'user_{user_id}', 'rasters') field_directory = os.path.join(settings.STATIC_DIR, 'sentinels', f'user_{user_id}', 'field') for file in os.listdir(zipes_directory): with ZipFile(os.path.join(zipes_directory, file), 'r') as zip: zip.extractall(path=extract_directory) for folder in os.listdir(extract_directory): path_to_granule = os.path.join(extract_directory, folder, 'GRANULE') for granule_folder in os.listdir(path_to_granule): path = os.path.join(path_to_granule, granule_folder, 'IMG_DATA') + '\\' bands_list = os.listdir(path) bands = {item[-7:-4].lower() for item in bands_list} if make_ndvi(path, bands, bands_list, True, user_id): print(path, 'completed') schema = {'geometry': 'Polygon', 'properties': {'fld_a': 'str:50'}} with fiona.open(os.path.join(user_folder, 'polygon.shp'), 'w', 'ESRI Shapefile', schema, crs='EPSG:4326') as layer: layer.write({ 'geometry': json.loads(order['geoJson']), 'properties': { 'fld_a': 'test' } }) for raster in os.listdir(rasters_directory): ds = gdal.Open(os.path.join(rasters_directory, raster)) gdal.Warp(os.path.join(reprojected_directory, raster), ds, dstSRS='EPSG:4326') with fiona.open(os.path.join(user_folder, 'polygon.shp'), "r") as shapefile: shapes = [feature["geometry"] for feature in shapefile] for raster in os.listdir(reprojected_directory): with rasterio.open(os.path.join(reprojected_directory, raster)) as src: out_image, out_transform = rasterio.mask.mask(src, shapes, crop=True) out_meta = src.meta out_meta.update({ "driver": "GTiff", "height": out_image.shape[1], "width": out_image.shape[2], "transform": out_transform }) with rasterio.open(os.path.join(field_directory, raster), "w", **out_meta) as dest: dest.write(out_image) add_lut('d:\\Education\\graduateWork\\task2\\ndvi_palette.lut', os.path.join(field_directory, raster)) values = [] dates = [] for field in os.listdir(field_directory): with rasterio.open(os.path.join(field_directory, field)) as ds: arr = ds.read() weighted_avg = get_weighted_average(arr) parsed_date = parse_date(field) if weighted_avg > 0 and 3 < parsed_date.month < 10: values.append(weighted_avg) dates.append(parsed_date) client = Client.objects.get(id=request.user) police = Police(geoJson=order['geoJson'], cadastralNumber=order['cadastralNumber'], price=order['price'], term=order['term'], coating=order['coating'], startDate=order['startDate'], docType=order['docType'], docId=order['docId'], status=order['status'], ndvi=values, dates=dates) police.save() client.polices.add(police) notification = Notification(notes='police_created') notification.save() client.notifications.add(notification) client = Client.objects.get(id=request.user) c = canvas.Canvas( os.path.join(orders_folders, 'Police_' + police.id + '_user_' + str(request.user))) pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf')) c.setFont("Verdana", 14) c.drawString(50, 800, u'Страховий договір') c.drawString(50, 740, u'Дата народження: ' + str(client.birth_date)) c.drawString(50, 710, u'Електронна пошта: ' + client.email) c.drawString(50, 680, u'Мобільний телефон: ' + client.email) c.drawString(50, 650, u'Місцезнаходження майна: ' + order['geoJson']) c.drawString( 50, 620, u'Загальна страхова сума за договором: ' + order['coating']) c.showPage() c.save() return Response(status=status.HTTP_201_CREATED)
def main(bids_dir): """ Extract CMP3 connectome in a bids dataset and create PDF report""" # Read BIDS dataset try: bids_layout = BIDSLayout(bids_dir) print("BIDS: %s" % bids_layout) subjects = [] for subj in bids_layout.get_subjects(): subjects.append('sub-' + str(subj)) print("Available subjects : ") print(subjects) except Exception: print( "BIDS ERROR: Invalid BIDS dataset. Please see documentation for more details." ) sys.exit(1) c = canvas.Canvas(os.path.join(bids_dir, 'derivatives', 'cmp', 'report.pdf'), pagesize=A4) width, height = A4 print("Page size : %s x %s" % (width, height)) startY = 841.89 - 50 c.drawString(245, startY, 'Report') c.drawString(10, startY - 20, 'BIDS : %s ' % bids_dir) offset = 0 for subj in bids_layout.get_subjects(): print("Processing %s..." % subj) sessions = bids_layout.get(target='session', return_type='id', subject=subj) if len(sessions) > 0: print("Warning: multiple sessions") for ses in sessions: gpickle_fn = os.path.join( bids_dir, 'derivatives', 'cmp', 'sub-' + str(subj), 'ses-' + str(ses), 'dwi', 'sub-%s_ses-%s_dwi_connectome_scale1.gpickle' % (str(subj), str(ses))) if os.path.isfile(gpickle_fn): # c.drawString(10,20+offset,'Subject: %s / Session: %s '%(str(subj),str(sess))) G = nx.read_gpickle(gpickle_fn) con_metric = 'number_of_fibers' con = nx.to_numpy_matrix(G, weight=con_metric, dtype=np.float64) fig = figure(figsize=(8, 8)) suptitle('Subject: %s / Session: %s ' % (str(subj), str(ses)), fontsize=11) title('Connectivity metric: %s' % con_metric, fontsize=10) # copy the default cmap (0,0,0.5156) my_cmap = copy.copy(cm.get_cmap('inferno')) my_cmap.set_bad((0, 0, 0)) imshow(con, interpolation='nearest', norm=colors.LogNorm(), cmap=my_cmap) colorbar() imgdata = io.StringIO() fig.savefig(imgdata, format='png') imgdata.seek(0) # rewind the data Image = ImageReader(imgdata) posY = startY - 20 - 4.5 * inch - offset c.drawImage(Image, 10, posY, 4 * inch, 4 * inch) offset += 4.5 * inch if posY - offset < 0: c.showPage() offset = 0 else: print("No session") gpickle_fn = os.path.join( bids_dir, 'derivatives', 'cmp', 'sub-' + str(subj), 'connectivity', 'sub-%s_label-L2008_desc-scale1_conndata-snetwork_connectivity.gpickle' % (str(subj))) if os.path.isfile(gpickle_fn): # c.drawString(10,20+offset,'Subject : %s '%str(subj)) G = nx.read_gpickle(gpickle_fn) con_metric = 'number_of_fibers' con = nx.to_numpy_matrix(G, weight=con_metric, dtype=np.float64) fig = figure(figsize=(8, 8)) suptitle('Subject: %s ' % (str(subj)), fontsize=11) title('Connectivity metric: %s' % con_metric, fontsize=10) # copy the default cmap (0,0,0.5156) my_cmap = copy.copy(cm.get_cmap('inferno')) my_cmap.set_bad((0, 0, 0)) imshow(con, interpolation='nearest', norm=colors.LogNorm(), cmap=my_cmap) colorbar() imgdata = io.StringIO() fig.savefig(imgdata, format='png') imgdata.seek(0) # rewind the data Image = ImageReader(imgdata) posY = startY - 20 - 4.5 * inch - offset c.drawImage(Image, 10, posY, 4 * inch, 4 * inch) offset += 4.5 * inch if posY - offset < 0: c.showPage() offset = 0 c.save()
def build_logo_overlay_pdf( fn_matrix_pdf, fn_pic, fn_out, x0, y0, scale=1.0, mask=None, pages='auto', # [], follow_rotate=False, url=''): str_datetime = datetime.now().strftime("%Y-%m-%d_%H-%M-%S_%f") #str_datetime = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") fn_logo_temp = fn_matrix_pdf.replace( ".pdf", "__logo_temp__" + str_datetime + ".pdf") pdf_dim = get_pdf_dimensions(fn_matrix_pdf) pagecount = pdf_dim['numPages'] pic_width, pic_height = get_pic_size(fn_pic) output = PdfFileWriter() outputStream = file(fn_logo_temp, "wb") for i in range(pagecount): rotate = int(pdf_dim['d_pageno2rotate'][i]) % 360 w, h = pdf_dim['d_pageno2size'][i] translation_scale = 1.0 s_out = StringIO.StringIO() if rotate % 180: c = canvas.Canvas(s_out, pagesize=(h, w)) else: c = canvas.Canvas(s_out, pagesize=(w, h)) x1 = x0 * translation_scale y1 = y0 * translation_scale - 0.51 if rotate and not follow_rotate: if rotate == 90: c.translate(w, 0) elif rotate == 180: c.translate(w, h) elif rotate == 270: c.translate(0, h) c.rotate(rotate) c.setFont("Helvetica", 10.5) if i in pages: width = int(pic_width * scale + 0.5) height = int(pic_height * scale + 0.5) c.drawImage(fn_pic, x1, y1, width=int(pic_width * scale + 0.5), height=int(pic_height * scale + 0.5), preserveAspectRatio=True, mask=mask) if url: pass #r1 = (x1, y1, x1 + width, y1 + height) # # c.linkURL(url, # r1, # thickness=1, # color=colors.green) c.drawString(x1 + int(pic_width * scale + 0.5), y1 + int(pic_height * scale + 0.5) / 2, url) else: c.drawString(0, 0, '') c.save() watermark = PdfFileReader(s_out) p = watermark.getPage(0) output.addPage(p) output.write(outputStream) outputStream.close() utils.process.call( ("pdftk", fn_matrix_pdf, "multistamp", fn_logo_temp, "output", fn_out)) return
def T_quote(odata, ldata, pdata1, pdata2, pdata3, cache, invodate): # pdata1:Bid (Bill To) # pdata2:Lid (Load At) # pdata3:Did (Delv To) # All dates must begin in datetime format and will be converted to strings as required joborder = odata.Jo file1 = addpath(f'tmp/{scac}/data/vquote/Quote_' + joborder + '.pdf') file2 = addpath(f'tmp/{scac}/data/vquote/Quote_' + joborder + 'c' + str(cache) + '.pdf') today = datetime.datetime.today().strftime('%m/%d/%Y') type = joborder[1] if invodate is None or invodate == 0: invodate = today else: invodate = invodate.strftime('%m/%d/%Y') date1 = odata.Date.strftime('%m/%d/%Y') date2 = odata.Date2.strftime('%m/%d/%Y') billto = list(range(5)) if pdata1 is not None: billto[0] = comporname( pdata1.Company, fullname(pdata1.First, pdata1.Middle, pdata1.Last)) billto[1] = nononestr(pdata1.Addr1) billto[2] = nononestr(pdata1.Addr2) billto[3] = nononestr(pdata1.Telephone) # billto[4]=nononestr(pdata1.Email) billto[4] = ' ' else: for i in range(5): billto[i] = ' ' loadat = list(range(5)) if pdata2 is not None: loadat[0] = pdata2.Entity.title() loadat[1] = nononestr(pdata2.Addr1).title() loadat[2] = nononestr(pdata2.Addr2).title() loadat[3] = '' loadat[4] = '' else: for i in range(5): loadat[i] = ' ' loadat[0] = 'None Assigned Yet' shipto = list(range(5)) if pdata3 is not None: shipto[0] = pdata3.Entity.title() shipto[1] = nononestr(pdata3.Addr1).title() shipto[2] = nononestr(pdata3.Addr2).title() shipto[3] = '' shipto[4] = '' else: for i in range(5): shipto[i] = ' ' shipto[0] = 'Not Assigned Yet' if type == 'T': line1 = [ 'Quote #', 'Booking #', 'Est Start', 'Est Finish', 'Bill of Lading', 'Container Type' ] line2 = ['Quantity', 'Item Code', 'Description', 'Price Each', 'Amount'] if type == 'T': chassis = ' ' time1 = date1 + ' ' + nononestr(odata.Time) time2 = date2 + ' ' + nononestr(odata.Time2) try: line3 = [ odata.Order, odata.Booking, time1, time2, odata.BOL, odata.Type ] except: line3 = [odata.Order, odata.Booking, time1, time2, ' ', ' '] qnote, note, bank, us, lab, logoi = bankdata('FC') lab1 = lab[0] lab2 = lab[1] # ___________________________________________________________ ltm = 36 rtm = 575 ctrall = 310 left_ctr = 170 right_ctr = 480 dl = 17.6 tdl = dl * 2 hls = 530 m1 = hls - dl m2 = hls - 2 * dl m3 = hls - 3 * dl m4 = hls - 4 * dl m5 = hls - 12 * dl m6 = hls - 19.5 * dl m7 = hls - 27 * dl fulllinesat = [m1, m2, m3, m4, m5, m6, m7] p1 = ltm + 87 p2 = ltm + 180 p3 = ctrall p4 = rtm - 180 p5 = rtm - 100 sds1 = [p1, p2, p3, p4, p5] n1 = ltm + 58 n2 = ltm + 128 n3 = rtm - 140 n4 = rtm - 70 sds2 = [n1, n2, n3, n4] q1 = ltm + 180 q2 = rtm - 150 sds3 = [q2] bump = 2.5 tb = bump * 2 c = canvas.Canvas(file1, pagesize=letter) c.setLineWidth(1) c.drawImage(logoi, 180, 670, mask='auto') # Date and JO boxes dateline = m1 + 8.2 * dl c.rect(rtm - 150, m1 + 7 * dl, 150, 2 * dl, stroke=1, fill=0) c.line(rtm - 150, dateline, rtm, dateline) c.line(rtm - 75, m1 + 7 * dl, rtm - 75, m1 + 9 * dl) if type == 'T': # Address boxes ctm = 218 c.rect(ltm, m1 + dl, 175, 5 * dl, stroke=1, fill=0) c.rect(ctm, m1 + dl, 175, 5 * dl, stroke=1, fill=0) c.rect(rtm - 175, m1 + dl, 175, 5 * dl, stroke=1, fill=0) level1 = m1 + 5 * dl c.line(ltm, level1, ltm + 175, level1) c.line(ctm, level1, ctm + 175, level1) c.line(rtm - 175, level1, rtm, level1) for i in fulllinesat: c.line(ltm, i, rtm, i) for k in sds1: c.line(k, m1, k, m3) for l in sds2: c.line(l, m3, l, m5) for m in sds3: c.line(m, m6, m, m7) # Side lines: c.line(ltm, m1, ltm, m7) c.line(rtm, m1, rtm, m7) #Horiz Line h1 = avg(m6, m7) - 3 c.line(q2, h1, rtm, h1) c.setFont('Helvetica-Bold', 24, leading=None) c.drawCentredString(rtm - 75, dateline + 1.5 * dl, 'Quote') c.setFont('Helvetica', 11, leading=None) c.drawCentredString(rtm - 112.5, dateline + bump, 'Date') c.drawCentredString(rtm - 37.7, dateline + bump, 'Quote #') c.drawString(ltm + bump * 3, m1 + 5 * dl + bump * 2, 'Bill To') c.drawString(ctm + bump * 3, m1 + 5 * dl + bump * 2, 'Load At') c.drawString(rtm - 170 + bump * 2, m1 + 5 * dl + bump * 2, 'Deliver To') ctr = [ avg(ltm, p1), avg(p1, p2), avg(p2, p3), avg(p3, p4), avg(p4, p5), avg(p5, rtm) ] for j, i in enumerate(line1): c.drawCentredString(ctr[j], m2 + tb, i) ctr = [avg(ltm, n1), avg(n1, n2), avg(n2, n3), avg(n3, n4), avg(n4, rtm)] for j, i in enumerate(line2): c.drawCentredString(ctr[j], m4 + tb, i) dh = 12 ct = 305 top = m1 + 9 * dl - 5 for i in us: c.drawString(ltm + bump, top, i) top = top - dh bottomline = m6 - 23 c.setFont('Helvetica-Bold', 12, leading=None) c.drawString(q2 + tb, bottomline, 'Quoted Total:') c.setFont('Helvetica', 10, leading=None) c.drawCentredString(avg(q2, rtm), m7 + 12, 'International wires add $39.00') j = 0 dh = 11.95 top = m5 - dh for i in qnote: c.drawString(ltm + tb, top, qnote[j]) j = j + 1 top = top - dh if j == 10: top = top - dh c.drawString( ltm + tb, m7 + tb, 'Signature Date' ) # _______________________________________________________________________ # Insert data here # _______________________________________________________________________ c.setFont('Helvetica', 12, leading=None) if type == 'T': dh = 13 top = level1 - dh lft = ltm + bump * 3 for i in billto: c.drawString(lft, top, i) top = top - dh top = level1 - dh lft = ctm + bump * 3 for i in loadat: c.drawString(lft, top, i) top = top - dh top = level1 - dh lft = rtm - 175 + bump * 3 for i in shipto: c.drawString(lft, top, i) top = top - dh x = avg(rtm - 75, rtm) y = dateline - dh - bump c.drawCentredString(x, y, joborder) x = avg(rtm - 75, rtm - 150) c.drawCentredString(x, y, invodate) c.setFont('Helvetica', 9, leading=None) j = 0 for i in line3: ctr = [ avg(ltm, p1), avg(p1, p2), avg(p2, p3), avg(p3, p4), avg(p4, p5), avg(p5, rtm) ] i = nononestr(i) c.drawCentredString(ctr[j], m3 + tb, i) j = j + 1 total = 0 top = m4 - dh for data in ldata: qty = float(float(data.Qty)) try: each = float(float(data.Ea)) except: each = 0.00 subtotal = qty * each total = total + subtotal line4 = [str(qty), data.Service] line5 = nononestr(data.Description) line6 = [each, subtotal] j = 0 for i in line4: ctr = [avg(ltm, n1), avg(n1, n2)] c.drawCentredString(ctr[j], top, i) j = j + 1 c.drawString(n2 + tb, top, line5) j = 0 for i in line6: ctr = [n4 - tb * 2, rtm - tb * 2] c.drawRightString(ctr[j], top, dollar(i)) j = j + 1 top = top - dh c.drawRightString(rtm - tb * 2, bottomline, dollar(total)) c.showPage() c.save() # # Now make a cache copy shutil.copy(file1, file2) return file2
def generate_completed_document(self): if len(self.template_id.sign_item_ids) <= 0: self.completed_document = self.template_id.attachment_id.datas return old_pdf = PdfFileReader(io.BytesIO( base64.b64decode(self.template_id.attachment_id.datas)), strict=False, overwriteWarnings=False) font = "Helvetica" normalFontSize = 0.015 packet = io.BytesIO() can = canvas.Canvas(packet) itemsByPage = self.template_id.sign_item_ids.getByPage() SignItemValue = self.env['sign.item.value'] for p in range(0, old_pdf.getNumPages()): page = old_pdf.getPage(p) width = float(page.mediaBox.getUpperRight_x()) height = float(page.mediaBox.getUpperRight_y()) # Set page orientation (either 0, 90, 180 or 270) rotation = page.get('/Rotate') if rotation: can.rotate(rotation) # Translate system so that elements are placed correctly # despite of the orientation if rotation == 90: width, height = height, width can.translate(0, -height) elif rotation == 180: can.translate(-width, -height) elif rotation == 270: width, height = height, width can.translate(-width, 0) items = itemsByPage[p + 1] if p + 1 in itemsByPage else [] for item in items: value = SignItemValue.search( [('sign_item_id', '=', item.id), ('sign_request_id', '=', self.id)], limit=1) if not value or not value.value: continue value = value.value if item.type_id.type == "text": can.setFont(font, height * item.height * 0.8) can.drawString( width * item.posX, height * (1 - item.posY - item.height * 0.9), value) elif item.type_id.type == "textarea": can.setFont(font, height * normalFontSize * 0.8) lines = value.split('\n') y = (1 - item.posY) for line in lines: y -= normalFontSize * 0.9 can.drawString(width * item.posX, height * y, line) y -= normalFontSize * 0.1 elif item.type_id.type == "checkbox": can.setFont(font, height * item.height * 0.8) value = 'X' if value == 'on' else '' can.drawString( width * item.posX, height * (1 - item.posY - item.height * 0.9), value) elif item.type_id.type == "signature" or item.type_id.type == "initial": image_reader = ImageReader( io.BytesIO( base64.b64decode(value[value.find(',') + 1:]))) _fix_image_transparency(image_reader._image) can.drawImage(image_reader, width * item.posX, height * (1 - item.posY - item.height), width * item.width, height * item.height, 'auto', True) can.showPage() can.save() item_pdf = PdfFileReader(packet, overwriteWarnings=False) new_pdf = PdfFileWriter() for p in range(0, old_pdf.getNumPages()): page = old_pdf.getPage(p) page.mergePage(item_pdf.getPage(p)) new_pdf.addPage(page) output = io.BytesIO() new_pdf.write(output) self.completed_document = base64.b64encode(output.getvalue()) output.close()
from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 def drawMyRuler(pdf): pdf.drawString(100, 810, 'x100') pdf.drawString(200, 810, 'x200') pdf.drawString(300, 810, 'x300') pdf.drawString(400, 810, 'x400') pdf.drawString(500, 810, 'x500') pdf.drawString(10, 800, 'y800') pdf.drawString(10, 700, 'y700') pdf.drawString(10, 600, 'y600') pdf.drawString(10, 500, 'y500') pdf.drawString(10, 400, 'y400') pdf.drawString(10, 300, 'y300') pdf.drawString(10, 200, 'y200') pdf.drawString(10, 100, 'y100') logo = "tn-logo.jpg" baslik = "Veri İmha Raporu123" pdf.drawImage(logo, 450, 800) pdf.drawString(50, 700, baslik) pdf = canvas.Canvas(dosyaadi, pagesize=A4) pdf.setTitle(title) drawMyRuler(pdf) pdf.save()
vi_gen = str(vi.patient.gender) dob = vi.patient.date_of_birth age = str(relativedelta(date.today(), dob).years) today = str(date.today()) def coord(x, y, unit=1): x, y = x * unit, y * unit return x, y ## This generates the PDF file response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename= "prescription.pdf"' pr1 = canvas.Canvas("prescription.pdf", pagesize=HALF_LETTER) ''' This draws the header info on the prescription form.''' pr1.setLineWidth(.5) ## This generates the doctor's information ### Line 1 = Doctor Name pr1.setFont('Helvetica', 14) x = 200 pdf_text_object = canvas.beginText((PAGE_WIDTH - lw1) / 2.0, x) pdf_text_object.textOut(l1) ### Line 2 Diplomate pr1.setFont('Helvetica', 10) x = 194
# --Content-- fileName = 'job.pdf' #' + str(jobID) + '# Add this piece after 'job' for custom ID files documentTitle = 'Job Number: ' + str(jobID) textLines = [ 'Starting: ' + starting, 'Destination: ' + destination, 'Distance: ' + totalDistance, 'Cargo: ' + cargoTotal, 'Finance: ' + str(finance) ] image = 'https://codysinfo.uk/vtcpy/exampleVTC.png' # --Document Setup-- from reportlab.pdfgen import canvas pdf = canvas.Canvas(fileName) pdf.setTitle(documentTitle) # --Document Addons-- # Guild Lines (Only Active When Editing File) #drawMyRuler(pdf) # Register A New Font from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics # Colours - colors.[colour] # from reportlab.lib import colors pdfmetrics.registerFont(