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

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

    pdf.output(outputname, 'F')
Exemplo n.º 2
1
def pdf_convert(fname, data):
    pdf = FPDF()
    pdf.set_margins(left=10, top=15, right=10)
    pdf.add_page()
    pdf.add_font('calibri', fname=r'c:\Windows\Fonts\calibri.ttf', uni=True)
    pdf.image('gables.jpg', x=90, w=30)
    pdf.set_font("calibri", size=12)
    pdf.multi_cell(0, 5, txt=data)
    pdf.output(fname)
Exemplo n.º 3
1
def dotest(outputname, nostamp):
    # filename - output filename
    # nostamp - do no use stamp in result file
    pdf = FPDF()
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.add_page()
    pdf.set_font('Arial', '', 16)
    pdf.write(8, "Test template")
    pdf.output(outputname, 'F')
Exemplo n.º 4
0
 def test_hello_world(self):
     pdf=FPDF()
     pdf.add_page()
     pdf.set_font('Arial','B',16)
     pdf.cell(40,10,hello_world)
     pdf.output(hello_world_file,'F')
     self.assertTrue(os.path.exists(hello_world_file))
Exemplo n.º 5
0
def randompdf (path) :

	numpdf = (randint(1500,2000))

	for i in range(10):
	
		name = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"
	
		numwords = (randint(200,1000))
	
		pdf = FPDF()
		pdf.add_page()
		pdf.set_font("Arial", size=12)
	
		words =[]
	
		for i in range(numwords):
		
			randomword  = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))])
			words.append(randomword)
	
		wordsinstring = ''.join(words)
	
		pdf.cell(200, 10, txt=wordsinstring, align="C")
		
		pdf.output(name)
		
		for i in range(numpdf):
			
			dupli = path + ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(randint(5,15))]) + ".pdf"
			
			copyfile(name, dupli)
Exemplo n.º 6
0
def generate(pdfname):
    datamanager = DataManager('127.0.0.1', 27017) 

    pdf = FPDF()

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

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

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

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

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

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

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

        #pdf.cell(20, 10, row['text'], 0, 0)# + '  ' + ','.join(row['meaning']))
        pdf.multi_cell(0, 8, line, 1, 'J')
    pdf.output(pdfname, 'F')
Exemplo n.º 7
0
    def createPDF(self, name=None, size='10kb'):
        from PyPDF2 import PdfFileReader, PdfFileWriter
        from fpdf import FPDF
        import os
        import random
        name = os.path.basename(name)
        tmp_name = '/tmp/' + name
        output_name = self.sharepath + '/' + name

        if size == '10kb':
            randlength = random.randint(10000,90000)
        elif size == '100kb':
            randlength = random.randint(100000,900000)
        elif size == '1mb':
            randlength = random.randint(1000000,9000000)

        #create file
        pdf=FPDF()
        pdf.add_page()
        pdf.set_font('Arial','B',8)
        pdf.cell(0,0,os.urandom(randlength))
        pdf.output(tmp_name, "F")

        #encrypt it
        output = PdfFileWriter()
        input1 = PdfFileReader(open(tmp_name, "rb"))
        output.encrypt(user_pwd="ihasapass")
        output.addPage(input1.getPage(0))

        outputStream = file(output_name, "wb")
        output.write(outputStream)
        outputStream.close()
Exemplo n.º 8
0
	def generate_pdf(self,qrs,pdf_filename):
		self.progress.setValue(0)
		self.label.setText('Writing PDF...')
		pdf=FPDF()
		pdf.add_page()
		col = 10
		row = 20
		pdf.set_font('Arial','B',20)
		pdf.text(10, 10, 'QRS')
		pdf.set_font('Arial','',5)
		c = 1
		for qr in qrs:
			if col > 250:
				row = row + 40
				col = 10
			pdf.text(col+3,row-3,qr)
			pdf.image('qrs/'+qr+'.png',col,row,30)
			col = col + 40
			self.progress.setValue((c*100)/len(qrs))
			c = c + 1
		try: 
			if not os.path.exists('pdfs'):
				os.makedirs('pdfs')
			pdf.output('pdfs/'+pdf_filename+'.pdf','F')
			self.messageBox('PDF', 'Pdf is Done! ' + 'pdfs/'+pdf_filename+'.pdf')
			self.label.setText('')

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

		except Exception as e:
			self.messageBox('PDF.', str(e))
Exemplo n.º 9
0
def write_cover_letter(cover_letter, skills):

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

        reader = csv.reader(skills_csv)
        rownum = 0

        for row in reader:

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

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

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

                for line in model_cover_letter:

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

                    pdf.write(6, line)

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

            rownum = rownum + 1
Exemplo n.º 10
0
def print_receipt(Student):
    """
    Print receipts related to specified Student
    Contain all three amounts paid - mess fees, room rent, amenities charge
    """

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

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

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

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

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

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

    # Write generated output file to PDF
    pdf.output(('receipt_%s.pdf' % Student.hall_ID), 'F')
Exemplo n.º 11
0
def generate_salary_list(Hall):
    """
    Print list of all employees and respective salary details for specified hall
    Take dict of Worker objects as parameter
    """

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

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

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

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

    # Write generated output file to PDF
    pdf.output(('hall_salary_%s.pdf' % Hall.hall_ID), 'F')
Exemplo n.º 12
0
class Document(object):

    def __init__(self, **kwargs):
        self.pdf = FPDF(**kwargs)
        self.pdf.add_page()
        self.pdf.set_margins(20, 20, 0)
        self.pdf.ln()
        self._add_font('DejaVu', 'DejaVuSansCondensed.ttf')
        self._add_font('DejaVu-Bold', 'DejaVuSansCondensed-Bold.ttf')

    def _add_font(self, font_name, file_name):
        self.pdf.add_font(font_name, '', asset_path(file_name), uni=True)

    def _font(self, size, bold=False):
        font_name = 'DejaVu' if not bold else 'DejaVu-Bold'
        self.pdf.set_font(font_name, '', size)

    def _text_cell(self, w, h, text, size=10, bold=False, align='L', border=BORDER_DEBUG):
        self._font(size, bold=bold)
        self.pdf.cell(w, h, text, align=align, border=border)

    def _multi_cell(self, w, h, text, size=10, bold=False, align='L', border=BORDER_DEBUG):
        self._font(size, bold=bold)
        self.pdf.multi_cell(w, h, text, align=align, border=border)

    def output(self):
        return self.pdf.output(dest='S')
def gerarPDF(qtd_img, Tamanho, qtd_Arq, diretorio):

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


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

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

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

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

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

# gerarPDF(0,0,0,0)
def createPDF(tFile):
    # Create PDF output dir if not exist
    if args.op.split("/")[0] not in listdir(curdir):
        mkdir(args.op)

    # Set fuzzed pdf name
    sPfile = tFile.split(".ttf")[0]
    tempPDF = FPDF()
    # Add our fuzzed ttf into PDF
    try:
        tempPDF.add_font(sPfile, "", args.o + "/" + tFile, uni=True)
    except:
        return
    tempPDF.set_font(sPfile, "", 16)

    # Create blank page and fill it with data
    tempPDF.add_page()
    tempPDF.cell(40, 10, "PDF TEST FILE")

    # Create fuzzed PDF
    try:
        tempPDF.output(args.op + sPfile + ".pdf", "F")
    except:
        return

    tempPDF.close()
Exemplo n.º 15
0
def hourpdf(request): # use to see working of temporary employee.
    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page()
    ganY = [46, 54]  # line bettwen collumn.
    
    pdf.add_font('Kinnari', '', 'Kinnari.ttf', uni=True)
    pdf.set_font('Kinnari', '', 12)
    
    gen_single_text(pdf, 60, u'ใบลงเวลาทำงานลูกจ้างชั่วคราวรายชั่วโมง')
    gen_single_text(pdf, 45, u'มหาวิทยาลัยเทคโนโลยีพระจอมเกล้าพระนครเหนือ')
    gen_single_text(pdf, 70, u'ชื่อ')
    
    pdf.ln(8)
    pdf.cell(0, 18, u'    วัน           วันที่ เดือน ปี          เวลาทำงาน      รวมชั่วโมง       ลายมือชื่อ          หมายเหตุ')
    drawAttr2(pdf, ganY[0], ganY[1], True)
    
    gen_single_text(pdf, 90, u'รวมจำนวนชั่วโมง ' + u'ชั่วโมง') # call spacial funtion to write a text per line.
    gen_single_text(pdf, 90, u'อัตรา 45.45 บาท ชั่วโมง')
    gen_single_text(pdf, 90, u'รวมเป็นเงินทั้งสิ้น' + u'บาท')
    gen_single_text(pdf, 90, u'(                   )')
    gen_single_text(pdf, 90, u'ได้ตรวจสอบถูกต้องแล้ว')
    gen_single_text(pdf, 75, u'ลงชื่อ.......................................................')
    gen_single_text(pdf, 80, u'(...................................................)')
    
    pdf.output("group3/hour.pdf", 'F')
    
    with open('group3/hour.pdf', 'rb') as pdf: # path to pdf in directory views.
        response = HttpResponse(pdf.read(),content_type='application/pdf')
        response['Content-Disposition'] = 'filename=hour.pdf'
        return response
    pdf.closed
Exemplo n.º 16
0
def issue_student_admission_letter(Student, body):
    """
    Print letter for Student at time of admission
    Contains details as provided by the Student
    """

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

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

    # Write generated output file to PDF
    pdf.output(('admission_letter_%s.pdf' % Student.student_ID), 'F')
Exemplo n.º 17
0
 def test_pdf_write(self):
     pdf=FPDF()
     pdf.add_page()
     pdf.set_font('Arial','',12)
     pdf.write(30, 'small text')
     pdf.set_font('Arial','',24)
     pdf.write(30, 'Large text')
     pdf.output('out/fpdf/test_pdf_write.pdf', 'F')
Exemplo n.º 18
0
    def render(self, outfile):
        pdf = FPDF()
        pdf.add_page();
        pdf.set_font('Arial','B',16);

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

        pdf.output(outfile,"F")
Exemplo n.º 19
0
 def test_ttf(self):
     pdf=FPDF()
     pdf.add_font('test','','font/lmroman7-italic.ttf',uni=True)
     pdf.add_page()
     pdf.set_font('test', '', 14)
     pdf.write(10, 'hello')
     pdf.set_font('test', '', 24)
     pdf.write(10, 'hello')
     pdf.output('out/fpdf/test_ttf.pdf', 'F')
Exemplo n.º 20
0
 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'))
Exemplo n.º 21
0
def pdfGen(Input,fontName,Output):
    pdf = FPDF()
    pdf.add_page()
    ttfName=fontName+'.ttf'
    pdf.add_font(fontName, '', ttfName, uni=True) 
    pdf.set_font(fontName, '', 14)
    linestring = open(Input, 'r').read()
    pdf.write(8,linestring)
    pdf.ln(20)
    pdf.output(Output, 'F')
Exemplo n.º 22
0
def dotest(outputname, nostamp):
    pdf = FPDF(orientation = "L", format = "A5")
    pdf.compress = False
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.set_font('Arial', '', 14)
    for i in range(10):
        o = ["p", "L", "P", "l"][i % 4]
        page(pdf, "Page %d from 10\nOrientation: %s" % (i + 1, o), o)
    pdf.output(outputname, 'F')
Exemplo n.º 23
0
 def test_unicode_font(self):
     pdf=FPDF()
     pdf.add_page()
     #pdf.add_font('DejaVu','','font/DejaVuSansCondensed.ttf',uni=True)
     pdf.add_font('DejaVu','I','font/DejaVuSerif-Italic.ttf',uni=True)
     pdf.set_font('DejaVu','I',16)
     #pdf.set_font('Arial','B',16)
     pdf.cell(40,10,u'Здравствуй мир  \u2200 x \u2203 y \u223c \u221e')
     pdf.output('HelloWorld.pdf', 'F')
     
     
Exemplo n.º 24
0
def fpdf():
	pdf = FPDF()
	pdf.add_page()
	pdf.set_font('Arial', 'B', 16)
	pdf.cell(40, 10, 'Reporte')
	pdf.output('reporte.pdf', 'F')
	import os
    	try:
        	os.startfile('reporte.pdf')
    	except Exception:
        	os.system("xdg-open \"%s\"" % 'reporte.pdf')
Exemplo n.º 25
0
def create_pdf(traceback):
	traceback = traceback.split("\n")
	pdf = FPDF()
	pdf.add_page()
	pdf.set_font('Arial', 'B', 12)
	pdf.cell(40, 10, "Send this error report to the administrator if the problem occurs again: \n", 0, 1)
	
	for x in xrange(0, len(traceback)):
		pdf.cell(40, 10, traceback[x], 0, 1)
		print traceback[x]
	pdf.output('pdf/stack.pdf', 'F')
Exemplo n.º 26
0
def dotest(outputname, nostamp):
    pdf = FPDF(orientation = "L", format = (100, 250))
    pdf.compress = False
    if nostamp:
        pdf._putinfo = lambda: common.test_putinfo(pdf)
    pdf.set_font('Arial', '', 14)
    for i in range(16):
        o = ["p", "l"][i % 2]
        f = ["a3", "a4", "a5", "letter", "legal", "",
            (100, 250), (320, 240)][i % 8]
        page(pdf, "Page %d from 16\nFormat: %s\nOrientation: %s" % 
            (i + 1, f, o), o, f)
    pdf.output(outputname, 'F')
Exemplo n.º 27
0
def createPDF(values):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", "B", 24)
    pdf.cell(0, 20, TITLE_PDF, border=0,align="C", ln=1)
    #pdf.image(LETTERHEAD_PNG,5, 5, 0, 0)     #### COMENTED OUT TO DUE NO IMAGE
    pdf.set_font("Courier", "", 10)
    i = 0
    for i in range(len(values)):
        pdf.multi_cell(0, 6, values["res"+str(i)], border=1)  ## Must be dynamic
        i += 1

    curUTC = strftime("%Y-%m-%dT%H-%M-%SZ", gmtime(time()))
    pdf.output(PDF_SAVE_TEMPLATE + "-" + curUTC + ".pdf", "F")
Exemplo n.º 28
0
 def test_greek_letters(self):
     pdf=FPDF()
     initPDF(pdf)
     setFontPDF(pdf,'symbol')
     
     p = lp.ListParser( lp.CommandParser(lp.ParagraphItemCreator) )
     s = r'\alpha\beta\gamma'
     p.match( s )
     self.assertTrue( p.hasMatch() )
     res =  p[0].docItem.writePDF()+' '+p[1].docItem.writePDF()+' '+p[2].docItem.writePDF()
     self.assertEquals( res, u'\u03b1 \u03b2 \u03b3')
     
     pdf.write(0, res)
     pdf.add_font('djv','','font/DejaVuSans.ttf',uni=True)
     pdf.set_font('djv','',12)
     pdf.write(0, u'  \u23a8 \u23a7 \u23a9 \u23aa \u239e \u2320 \u2321 \u23ae')
     
     pdf.ln(10)
     pdf.add_font('smb','','font/Symbola.ttf',uni=True)
     pdf.set_font('smb','',12)
     pdf.write(0, u'  \u23b7 \u03b1 \u03b2 \u03b3')
     
     pdf.ln(10)
     pdf.add_font('jax','','font/mathjax_amsregular.ttf',uni=True)
     pdf.set_font('jax','',12)
     pdf.write(0, u' abc \u23b7 \u03b1 \u03b2 \u03b3')
     
     pdf.ln(10)
     pdf.add_font('jax','','font/MathJax/ttf/mathjax_size1regular.ttf',uni=True)
     pdf.set_font('jax','',12)
     pdf.write(0, u' abc \u23b7 \u03b1 \u03b2 \u03b3')
     
     
     pdf.output('out/latex/test_greek_letters.pdf', 'F')
Exemplo n.º 29
0
def print_results(top_hosts,hosts):
    pdf=FPDF()
    pdf.add_page()
    pdf.set_font('Arial','B',24)
    pdf.cell(60,10,'PCAP Analysis results','C')
    pdf.ln(20)
    for i in range(1,len(top_hosts)):
        pdf.set_font('Arial','B',16)
        pdf.ln(10)
        pdf.cell(70,20,"top%d"%i)
        pdf.ln(10)
        pdf.set_font('Arial','B',12)
        pdf.cell(70,20,"host:"+str(top_hosts[i-1][0]))
        pdf.ln(10)
        pdf.cell(70,20,"num:"+str(hosts[top_hosts[i-1][0]]['num']))
        pdf.ln(10)
        pdf.cell(70,20,"start static time:"+str(hosts[top_hosts[i-1][0]]['start_time']))
        pdf.ln(10)
        pdf.cell(70,20,"end static time:"+str(hosts[top_hosts[i-1][0]]['start_time']))
        pdf.ln(10)
        pdf.cell(70,20,"flow:"+str(float(hosts[top_hosts[i-1][0]]['flow'])/1024)+"kb")
        pdf.ln(10)
        pdf.cell(70,20,"visitors:")
        pdf.set_font('Arial','B',10)
        for visitor in hosts[top_hosts[i-1][0]]['visitors']:
            pdf.ln(7)
            pdf.cell(200,20,"     time: "+time.strftime('%Y-%m-%d',time.localtime(float(visitor[0])))+"     srcip: "+str(visitor[1])+"     country: "+str(visitor[2])+"     dstip: "+str(visitor[3])+"     country:"+str(visitor[4]))
    pdf.output('result.pdf','F')
Exemplo n.º 30
0
def pdfGen(request):
    pdf = FPDF()
    pdf.add_page()
    #pdf.add_font('gargi', '', 'gargi.ttf', uni=True) 
    #pdf.set_font('gargi', '', 14)
    #pdf.write(8, u'Hindi: एक अमरीकि')
    pdf.add_font('Kedage-b', '', 'Kedage-b.ttf', uni=True) 
    pdf.set_font('Kedage-b', '', 14)
    #pdf.add_font('TSCu_SaiIndira', '', 'TSCu_SaiIndira.ttf', uni=True) 
    #pdf.set_font('TSCu_SaiIndira', '', 14)
    linestring = open('DigiFiles/KannadaInput.txt', 'r').read()
    pdf.write(8,linestring)
    pdf.ln(20)
    pdf.output("DigiFiles/KannadaOutput.pdf", 'F')
Exemplo n.º 31
0
#font_dir = fpdf.FPDF_FONT_DIR
font_dir = os.path.join(base, 'font')

with open(os.path.join(base, 'HelloWorld.txt')) as file:
    txt = file.read()

# Add a Unicode font (uses UTF-8)
for font in os.listdir(font_dir):
    if font.lower().endswith('.ttf'):
        fontpath = os.path.join(font_dir, font)
        print(fontpath)
        t0 = time.time()
        pdf.add_font(font, '', fontpath, uni=True)
        t1 = time.time()
        pdf.set_font(font, '', 14)
        t2 = time.time()
        pdf.write(8, font)
        pdf.ln()
        pdf.write(8, txt)
        pdf.ln()
        t3 = time.time()
        print("ttf loading time", t1 - t0)
        print("ttf total time", t3 - t0)
        print()

fn = 'unifonts.pdf'
pdf.output(fn, 'F')
import os
try:
    os.startfile(fn)
Exemplo n.º 32
0
def create_chart():
    name = input("\nEnter name of student: ")
    pdf_file_name = input("Enter preferred output file name (must end in .pdf): ")

    all_schools = []
    school_keys = []
    other_info = []
    category = ["School", "Grades", "Location", "Deadline",
                "Application", "Testing", "Learning Support", "URL"]
    categories = [category]

    n = int(input("Enter number of Schools you would like to include in the green zone then type their keys out, "
                  "followed by an enter : "))

    for i in range(0, n):
        ele = str(input())

        school_keys.append(ele)

    for key in school_keys:
        s = shelve.open('test_shelf.db')
        try:
            existing = s[key]
            all_schools.append([existing['name'], existing['age'], existing['location'], existing['application deadline'],
                                existing['application method'], existing['testing accepted'],
                                existing['learning support'], existing['other']])
            other_info.append([existing['name'], existing['extra']])
        finally:
            s.close()

    yellow_schools = []
    yellow_school_keys = []

    n = int(input("Enter number of Schools you would like to include in the yellow zone then type their keys out"
                  "followed by an enter : "))

    for i in range(0, n):
        ele = str(input())

        yellow_school_keys.append(ele)  # adding the element

    for key in yellow_school_keys:
        s = shelve.open('test_shelf.db')
        try:
            existing = s[key]
            yellow_schools.append([existing['name'], existing['age'], existing['location'], existing['application deadline'],
                                existing['application method'], existing['testing accepted'],
                                existing['learning support'], existing['other']])
            other_info.append([existing['name'], existing['extra']])
        finally:
            s.close()

    red_schools = []
    red_school_keys = []

    n = int(input("Enter number of Schools you would like to include in the red zone then type their keys out"
                  "followed by an enter : "))

    for i in range(0, n):
        ele = str(input())

        red_school_keys.append(ele)  # adding the element

    for key in red_school_keys:
        s = shelve.open('test_shelf.db')
        try:
            existing = s[key]
            red_schools.append([existing['name'], existing['age'], existing['location'], existing['application deadline'],
                                existing['application method'], existing['testing accepted'],
                                existing['learning support'], existing['other']])
            other_info.append([existing['name'], existing['extra']])
        finally:
            s.close()

    pdf = FPDF(format=(266.7, 457.2))

    # Add a page
    pdf.add_page()

    # set style and size of font
    # that you want in the pdf
    pdf.set_font("Times", size=11)
    pdf.image("hall.jpg", 82, 10, 105)
    pdf.cell(0, 10, ln=1, align='C')
    pdf.cell(0, 10, ln=1, align='C')
    pdf.cell(0, 10, ln=1, align='C')
    pdf.cell(0, 10, ln=1, align='C')

    pdf.set_font("Times", 'B', size=11)
    title_string = "Initial School Exploration List: " + name
    pdf.cell(0, 10, txt=title_string, ln=1, align='L')

    pdf.set_font("Times", size=11)

    pdf.line(10, 58, 255, 58)

    pdf.set_font("Times", 'B', size=11)
    pdf.cell(13, 7, txt="Green: ", align='L')
    pdf.set_font("Times", size=11)

    pdf.cell(0, 7, txt="Schools we should actively pursue now.", ln=1, align='L')

    pdf.set_font("Times", 'B', size=11)
    pdf.cell(15, 7, txt="Yellow: ", align='L')
    pdf.set_font("Times", size=11)

    pdf.cell(0, 7, txt="Schools we would like you to proceed with, although not as strong a fit.", ln=1, align='L')

    pdf.set_font("Times", 'B', size=11)
    pdf.cell(10, 7, txt="Red: ", align='L')
    pdf.set_font("Times", size=11)

    pdf.cell(0, 7, txt="These schools could be a fit but less likely than the yellow and green.", ln=1, align='L')
    pdf.ln(1)

    epw = pdf.w - 2 * pdf.l_margin
    pdf.set_font('Times', 'B', 10)
    col_width = epw / 8
    th = pdf.font_size

    pdf.set_fill_color(0, 230, 0)
    pdf.rect(pdf.x, pdf.y, epw, 7, style='DF')
    pdf.cell(0, 7, txt="Green: Schools we should actively pursue now.", ln=1, align='C')

    pdf.set_font("Times", 'B', size=10)

    for row in categories:
        for datum in row:
            pdf.cell(col_width, 2 * th, str(datum), border=1)

        pdf.ln(2 * th)
    pdf.set_font('Times', '', 7)

    link_counter = 0
    for row in all_schools:
        for datum in row:
            link_counter = link_counter + 1
            if link_counter == 8:
                pdf.cell(col_width, 2 * th, str(datum), border=1)
                pdf.link(pdf.x - col_width, pdf.y - (2 * th), 3, 3, str(datum))
            else:
                pdf.cell(col_width, 2 * th, str(datum), border=1)
        link_counter = 0
        pdf.ln(2 * th)

    pdf.set_fill_color(255, 255, 0)
    pdf.rect(pdf.x, pdf.y, epw, 7, style='DF')
    pdf.set_font('Times', 'B', 10)
    pdf.cell(0, 7, txt="Yellow: Schools we should pursue, but not as strong as green.", ln=1, align='C')
    pdf.set_font('Times', '', 7)

    link_counter = 0
    for row in yellow_schools:
        for datum in row:
            link_counter = link_counter + 1
            if link_counter == 8:
                pdf.cell(col_width, 2 * th, str(datum), border=1)
                pdf.link(pdf.x - col_width, pdf.y - (2 * th), 3, 3, str(datum))
            else:
                pdf.cell(col_width, 2 * th, str(datum), border=1)
        link_counter = 0
        pdf.ln(2 * th)

    pdf.set_fill_color(255, 0, 0)
    pdf.rect(pdf.x, pdf.y, epw, 7, style='DF')
    pdf.set_font('Times', 'B', 10)
    pdf.cell(0, 7, txt="Red: These schools could be a fit but less likely than "
                       "the yellow and green.", ln=1, align='C')
    pdf.set_font('Times', '', 7)

    link_counter = 0
    for row in red_schools:
        for datum in row:
            link_counter = link_counter + 1
            if link_counter == 8:
                pdf.cell(col_width, 2 * th, str(datum), border=1)
                pdf.link(pdf.x - col_width, pdf.y - (2 * th), 3, 3, str(datum))
            else:
                pdf.cell(col_width, 2 * th, str(datum), border=1)
        link_counter = 0
        pdf.ln(2 * th)

    pdf.set_font("Times", 'B', size=14)
    pdf.cell(0, 13, txt="Extra Information", ln=1, align='C')
    pdf.set_font("Times", size=11)

    for entry in other_info:
        if entry[1] != "":
            input_string = entry[0] + ": " + entry[1]
            pdf.cell(0, 7, txt=input_string, ln=1, align='L')

    pdf.output(pdf_file_name)

    main()
Exemplo n.º 33
0
def resumenPDF(inicial, final):
        global alimentosConCantitdadTotal, dias,cc
        pdf=FPDF(orientation='P', unit='mm', format='A4')
        pdf.add_page()
        pdf.set_font("Arial", size=15,style='B')
        textoAEscribir=f'Información comida del {inicial.strftime("%A %d-%m-%Y")} al {final.strftime("%A %d-%m-%Y")}'
        pdf.cell(200, 10, txt=textoAEscribir, ln=1, align="C")
        textoAEscribir="Información de cada comida: "
        pdf.set_font("Arial", size=12,style='B')
        pdf.cell(200, 10, txt=textoAEscribir, ln=2, align="C")
        i=3
        for dia in dias.keys():
                textoAEscribir=f'{dia.strftime("%A %d-%m-%Y")}\n'
                pdf.set_font("Arial", size=10,style='B')
                pdf.cell(200, 10, txt=textoAEscribir, ln=i)
                i+=1
                comidasDeEseDia=dias[dia]
                for comidaActual in comidasDeEseDia.keys():
                        textoAEscribir=f"\t{comidaActual}"
                        pdf.set_font("Arial", size=10)
                        pdf.set_text_color(255,0,0)
                        pdf.cell(200, 10, txt=textoAEscribir, ln=i)
                        pdf.set_text_color(0,0,0)
                        i+=1
                        alimentosComidaActual = comidasDeEseDia[comidaActual]
                        for alimiento in alimentosComidaActual.keys():
                                textoAEscribir="\t\t"+str(alimentosComidaActual[alimiento])
                                pdf.set_font("Arial", size=8)
                                pdf.cell(200, 10, txt=textoAEscribir, ln=i)
                                i+=1
        textoAEscribir="Información para la lista de la compra"
        pdf.set_font("Arial", size=12,style='B')
        pdf.cell(200, 10, txt=textoAEscribir, ln=i+2)
        i+=1
        for alimento in alimentosConCantitdadTotal.keys():
                textoAEscribir="\t"+str(alimentosConCantitdadTotal[alimento])
                pdf.set_font("Arial", size=8,)
                pdf.cell(200, 10, txt=textoAEscribir, ln=i)
                i+=1
        i+=1
        return pdf.output(dest="S").encode("latin-1")
Exemplo n.º 34
0
    def PDF_maker(self, fname, lname, month, percent_month, percent,
                  rank_month, overall_rank, file_location):
        percent = round(percent)
        percent_month = round(percent_month)

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

        pdf.set_fill_color(200, 220, 255)

        pdf.image(self.cwd + "\\Other_necessary_items\\" + "campusX_logo.png",
                  x=10,
                  y=5,
                  w=20)
        if percent >= 92:
            pdf.image(self.cwd + "\\Other_necessary_items\\" + "grade-aa.jpg",
                      x=168,
                      y=2,
                      w=27)
        elif (percent >= 84) & (percent < 92):
            pdf.image(self.cwd + "\\Other_necessary_items\\" + "grade-a.jpg",
                      x=168,
                      y=2,
                      w=27)
        elif (percent >= 75) & (percent < 84):
            pdf.image(self.cwd + "\\Other_necessary_items\\" + "grade-b.jpg",
                      x=168,
                      y=2,
                      w=27)
        elif (percent >= 60) & (percent < 75):
            pdf.image(self.cwd + "\\Other_necessary_items\\" + "grade-c.jpg",
                      x=168,
                      y=2,
                      w=27)
        else:
            pdf.image(self.cwd + "\\Other_necessary_items\\" + "grade-d.jpg",
                      x=168,
                      y=2,
                      w=27)

        pdf.set_font("times", 'B', size=50)
        pdf.cell(0, 10, txt="Report Card", ln=1, align="C")
        pdf.cell(0, 20, ln=2)

        pdf.set_font("times", 'B', size=18)
        pdf.cell(0, 7, txt="Name :- " + fname + " " + lname, ln=2, align="L")

        if overall_rank == 1:
            pdf.cell(0,
                     7,
                     txt="Overall Rank :- " + str(overall_rank) + "st",
                     ln=2,
                     align="L")
        elif overall_rank == 3:
            pdf.cell(0,
                     7,
                     txt="Overall Rank :- " + str(overall_rank) + "nd",
                     ln=2,
                     align="L")
        elif overall_rank == 4:
            pdf.cell(0,
                     7,
                     txt="Overall Rank :- " + str(overall_rank) + "rd",
                     ln=2,
                     align="L")
        else:
            pdf.cell(0,
                     7,
                     txt="Overall Rank :- " + str(overall_rank) + "th",
                     ln=2,
                     align="L")

        pdf.cell(0,
                 7,
                 txt="Overall Percentage :- " + str(percent) + "%",
                 ln=2,
                 align="L")
        pdf.cell(0, 7, ln=2)

        pdf.set_font("times", 'B', size=18)
        pdf.cell(0,
                 7,
                 txt="Your Stats for " + month + " is as follows :- ",
                 ln=2,
                 align="L")

        pdf.image(self.cwd + "\\Student_images\\" + fname + "_" + lname +
                  ".jpg",
                  x=158,
                  y=35,
                  w=40)

        pdf.image(self.cwd + "\\Report_card\\" + month + "\\" + fname + "_" +
                  lname + "\\styled_table.jpg",
                  x=5,
                  y=77,
                  w=200)

        pdf.set_font("times", 'I', size=11)
        pdf.cell(0, 73, ln=2)

        pdf.set_font("times", 'B', size=16)
        pdf.cell(0, 7, ln=2)
        pdf.cell(
            0,
            7,
            txt=
            "Graphs showing your performance throughout this month are given below :-",
            border=0,
            ln=1,
            align="L")

        pdf.set_font("times", 'BU', size=14)
        pdf.image(self.cwd + "\\Report_card\\" + month + "\\" + fname + "_" +
                  lname + "\\radar_plot.jpg",
                  x=36,
                  y=164,
                  w=135)

        pdf.cell(0, 107, ln=2)
        pdf.cell(
            0,
            5,
            txt=
            "These skills were tested this month and here is your performance.",
            align='C',
            ln=1)
        pdf.cell(
            0,
            5,
            txt=
            "Your vs the topper vs average performance of each task is given below.",
            align='C',
            ln=1)
        pdf.image(self.cwd + "\\Report_card\\" + month + "\\" + fname + "_" +
                  lname + "\\comparison.jpg",
                  x=38,
                  y=18,
                  w=135)

        pdf.cell(0, 108, ln=2)
        pdf.cell(0,
                 5,
                 txt="Now, where do you stand compared to previous months.",
                 align='C',
                 ln=1)
        pdf.image(self.cwd + "\\Report_card\\" + month + "\\" + fname + "_" +
                  lname + "\\monthlygraph.jpg",
                  x=40,
                  y=130,
                  w=130)

        pdf.cell(0, 93, ln=2)
        pdf.cell(0, 6, ln=2)
        pdf.set_font("times", 'B', size=17)
        if rank_month == 1:
            pdf.set_font("times", 'B', size=16)
            pdf.cell(
                0,
                5,
                txt=
                "Congo! You have achieved 1st position this month with a percentage of "
                + str(percent_month) + "%.",
                border=0,
                ln=2,
                align="U")
        elif rank_month == 2:
            pdf.set_font("times", 'B', size=16)
            pdf.cell(
                0,
                5,
                txt=
                "Congo! You have achieved 2nd position this month with a percentage of "
                + str(percent_month) + "%.",
                border=0,
                ln=2,
                align="U")
        elif rank_month == 3:
            pdf.set_font("times", 'B', size=16)
            pdf.cell(
                0,
                5,
                txt=
                "Congo! You have achieved 3rd position this month with a percentage of "
                + str(percent_month) + "%.",
                border=0,
                ln=2,
                align="U")
        elif (rank_month == 4) | (rank_month == 5):
            pdf.cell(0,
                     5,
                     txt="Well Done! You are in top 5 and have ranked " +
                     str(rank_month) + "th this month with a",
                     border=0,
                     ln=2,
                     align="U")
            pdf.cell(0,
                     5,
                     txt="percentage of " + str(percent_month) + "%.",
                     border=0,
                     ln=2,
                     align="U")
        elif (rank_month >= 6) & (rank_month <= 10):
            pdf.cell(0,
                     5,
                     txt="Well Done! You are in top 10 and have ranked " +
                     str(rank_month) + "th this month with a",
                     border=0,
                     ln=2,
                     align="U")
            pdf.cell(0,
                     5,
                     txt="percentage of " + str(percent_month) + "%.",
                     border=0,
                     ln=2,
                     align="U")
        else:
            pdf.cell(0,
                     5,
                     txt="Your have ranked " + str(rank_month) +
                     "th this month with a percentage of " +
                     str(percent_month) + "% and your",
                     border=0,
                     ln=2,
                     align="U")
            pdf.cell(0,
                     5,
                     txt="performance needs to improve.",
                     border=0,
                     ln=2,
                     align="U")

        pdf.cell(0, 5, ln=2)
        pdf.set_font("times", 'I', size=14)
        pdf.cell(
            0,
            5,
            txt=
            "N.B.:- The tasks which have been performed by other students and evaluated this month are",
            ln=2,
            align='U')
        pdf.cell(
            0,
            5,
            txt=
            "           considered above. Previous tasks are not taken into consideration.",
            ln=2,
            align='U')

        pdf.cell(0, 8, ln=1)
        pdf.set_font("times", 'B', size=18)
        pdf.cell(
            0,
            8,
            ln=2,
            txt="Date :- " + str(date.today()) +
            "                                                             Place :- Kolkata",
            align='L')
        pdf.cell(0, 5, ln=1)
        pdf.set_font("times", 'I', size=12)
        pdf.cell(
            0,
            2,
            ln=2,
            txt=
            "**This is a computer generated document. If you have any queries, please contact +91 8420166148."
        )

        pdf.output(file_location + "" + fname + "_" + lname + ".pdf")
Exemplo n.º 35
0
Arquivo: pdf.py Projeto: mhaya/weko
def make_combined_pdf(pid, obj_file_uri, fileobj, obj, lang_user):
    """Make the cover-page-combined PDF file.

    :param pid: PID object
    :param file_uri: URI of the file object
    :param lang_user: LANGUAGE of access user
    :return: cover-page-combined PDF file object
    """
    lang_filepath = current_app.config['PDF_COVERPAGE_LANG_FILEPATH']\
        + lang_user + current_app.config['PDF_COVERPAGE_LANG_FILENAME']

    pidObject = PersistentIdentifier.get('recid', pid.pid_value)
    item_metadata_json = ItemsMetadata.get_record(pidObject.object_uuid)
    item_type = ItemsMetadata.get_by_object_id(pidObject.object_uuid)
    item_type_id = item_type.item_type_id
    type_mapping = Mapping.get_record(item_type_id)
    item_map = get_mapping(type_mapping, "jpcoar_mapping")

    with open(lang_filepath) as json_datafile:
        lang_data = json.loads(json_datafile.read())

    # Initialize Instance
    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page()
    pdf.set_margins(20.0, 20.0)
    pdf.set_fill_color(100, 149, 237)

    pdf.add_font('IPAexg',
                 '',
                 current_app.config["JPAEXG_TTF_FILEPATH"],
                 uni=True)
    pdf.add_font('IPAexm',
                 '',
                 current_app.config["JPAEXM_TTF_FILEPATH"],
                 uni=True)

    # Parameters such as width and height of rows/columns
    w1 = 40  # width of the left column
    w2 = 130  # width of the right column
    footer_w = 90  # width of the footer cell
    # url_oapolicy_h = 7  # height of the URL & OA-policy
    # height of the URL & OA-policy
    url_oapolicy_h = current_app.config['URL_OA_POLICY_HEIGHT']
    # title_h = 8  # height of the title
    title_h = current_app.config['TITLE_HEIGHT']  # height of the title
    # header_h = 20  # height of the header cell
    header_h = current_app.config['HEADER_HEIGHT']  # height of the header cell
    # footer_h = 4  # height of the footer cell
    footer_h = current_app.config['FOOTER_HEIGHT']  # height of the footer cell
    # meta_h = 9  # height of the metadata cell
    # height of the metadata cell
    meta_h = current_app.config['METADATA_HEIGHT']
    max_letters_num = 51  # number of maximum letters that can be contained \
    # in the right column
    cc_logo_xposition = 160  # x-position of Creative Commons logos

    # Get the header settings
    record = PDFCoverPageSettings.find(1)
    header_display_type = record.header_display_type
    header_output_string = record.header_output_string
    header_output_image = record.header_output_image
    header_display_position = record.header_display_position

    # Set the header position
    positions = {}
    if header_display_position == 'left':
        positions['str_position'] = 'L'
        positions['img_position'] = 20
    elif header_display_position == 'center' or header_display_position is None:
        positions['str_position'] = 'C'
        positions['img_position'] = 85
    elif header_display_position == 'right':
        positions['str_position'] = 'R'
        positions['img_position'] = 150

    # Show header(string or image)
    if header_display_type == 'string':
        pdf.set_font('IPAexm', '', 22)
        pdf.multi_cell(w1 + w2, header_h, header_output_string, 0,
                       positions['str_position'], False)
    else:
        pdf.image(header_output_image,
                  x=positions['img_position'],
                  y=None,
                  w=0,
                  h=30,
                  type='')
        pdf.set_y(55)

    # Title settings
    title = item_metadata_json['title']
    pdf.set_font('IPAexm', '', 20)
    pdf.multi_cell(w1 + w2, title_h, title, 0, 'L', False)
    pdf.ln(h='15')

    # Metadata
    fg = WekoFeedGenerator()
    fe = fg.add_entry()

    _file = 'file.URI.@value'
    _file_item_id = None
    if _file in item_map:
        _file_item_id = item_map[_file].split('.')[0]

    _creator = 'creator.creatorName.@value'
    _creator_item_id = None
    if _creator in item_map:
        _creator_item_id = item_map[_creator].split('.')[0]

    publisher_attr_lang = '[email protected]:lang'
    publisher_value = 'publisher.@value'
    publisher_item_id = None
    publisher_lang_id = None
    publisher_text_id = None

    keyword_attr_lang = '[email protected]:lang'
    keyword_attr_value = 'subject.@value'
    keyword_base = None
    keyword_lang = None

    pdf.set_font('Arial', '', 14)
    pdf.set_font('IPAexg', '', 14)

    if item_metadata_json['lang'] == 'en':
        item_metadata_json['lang'] = 'English'
    elif item_metadata_json['lang'] == 'ja':
        item_metadata_json['lang'] = 'Japanese'

    try:
        lang = item_metadata_json.get('lang')
    except (KeyError, IndexError):
        lang = None
    try:
        publisher_item_id = item_map[publisher_attr_lang].split('.')[0]
        publisher_lang_id = item_map[publisher_attr_lang].split('.')[1]
        publisher_text_id = item_map[publisher_value].split('.')[1]
        publisher = None
        default_publisher = None
        publishers = item_metadata_json[publisher_item_id]
        for publisher_data in publishers:
            if publisher_data[publisher_lang_id] == lang_user:
                publisher = publisher_data[publisher_text_id]
            if publisher_data[publisher_lang_id] == 'en':
                default_publisher = publisher_data[publisher_text_id]

        if publisher is None:
            publisher = default_publisher
    except (KeyError, IndexError):
        publisher = None
    try:
        pubdate = item_metadata_json.get('pubdate')
    except (KeyError, IndexError):
        pubdate = None
    try:
        keyword_item_id = item_map[keyword_attr_lang].split('.')[0]
        keyword_item_lang = item_map[keyword_attr_lang].split('.')[1]
        keyword_item_value = item_map[keyword_attr_value].split('.')[1]
        keyword_base = item_metadata_json.get(keyword_item_id)
        if keyword_base:
            keyword_lang = keyword_base.get(keyword_item_lang)
        if keyword_lang == 'ja':
            keywords_ja = keyword_base.get(keyword_item_value)
            keywords_en = None
        elif keyword_lang == 'en':
            keywords_en = keyword_base.get(keyword_item_value)
            keywords_ja = None
        else:
            keywords_ja = None
            keywords_en = None
    except (KeyError, IndexError):
        keywords_ja = None
        keywords_en = None
    creator_item = item_metadata_json.get(_creator_item_id)
    try:
        creator_mail = creator_item['creatorMails'][0].get('creatorMail')
    except (KeyError, IndexError):
        creator_mail = None
    try:
        creator_name = None
        default_creator_name = None
        for creator_metadata in creator_item['creatorNames']:
            if creator_metadata.get('creatorNameLang') == lang_user:
                creator_name = creator_metadata.get('creatorName')
            if creator_metadata.get('creatorNameLang') == 'en':
                default_creator_name = creator_metadata.get('creatorName')

        if creator_name is None:
            creator_name = default_creator_name
    except (KeyError, IndexError):
        creator_name = None
    try:
        affiliation = creator_item['affiliation'][0].get('affiliationNames')
    except (KeyError, IndexError):
        affiliation = None

    metadata_dict = {
        "lang": lang,
        "publisher": publisher,
        "pubdate": pubdate,
        "keywords_ja": keywords_ja,
        "keywords_en": keywords_en,
        "creator_mail": creator_mail,
        "creator_name": creator_name,
        "affiliation": affiliation
    }

    # Change the values from None to '' for printing
    for key in metadata_dict:
        if metadata_dict[key] is None:
            metadata_dict[key] = ''

    metadata_list = [
        "{}: {}".format(lang_data["Metadata"]["LANG"], metadata_dict["lang"]),
        "{}: {}".format(lang_data["Metadata"]["PUBLISHER"],
                        metadata_dict["publisher"]),
        "{}: {}".format(lang_data["Metadata"]["PUBLICDATE"],
                        metadata_dict["pubdate"]),
        "{} (Ja): {}".format(lang_data["Metadata"]["KEY"],
                             metadata_dict["keywords_ja"]),
        "{} (En): {}".format(lang_data["Metadata"]["KEY"],
                             metadata_dict["keywords_en"]),
        "{}: {}".format(lang_data["Metadata"]["AUTHOR"],
                        metadata_dict["creator_name"]),
        "{}: {}".format(lang_data["Metadata"]["EMAIL"],
                        metadata_dict["creator_mail"]),
        "{}: {}".format(lang_data["Metadata"]["AFFILIATED"],
                        metadata_dict["affiliation"])
    ]

    metadata = '\n'.join(metadata_list)
    metadata_lfnum = int(metadata.count('\n'))
    for item in metadata_list:
        metadata_lfnum += int(
            get_east_asian_width_count(item)) // max_letters_num

    url = ''  # will be modified later
    url_lfnum = int(get_east_asian_width_count(url)) // max_letters_num

    oa_policy = ''  # will be modified later
    oa_policy_lfnum = int(
        get_east_asian_width_count(oa_policy)) // max_letters_num

    # Save top coordinate
    top = pdf.y
    # Calculate x position of next cell
    offset = pdf.x + w1
    pdf.multi_cell(
        w1, meta_h,
        lang_data["Title"]["METADATA"] + '\n' * (metadata_lfnum + 1), 1, 'C',
        True)
    # Reset y coordinate
    pdf.y = top
    # Move to computed offset
    pdf.x = offset
    pdf.multi_cell(w2, meta_h, metadata, 1, 'L', False)
    top = pdf.y
    pdf.multi_cell(w1, url_oapolicy_h,
                   lang_data["Title"]["URL"] + '\n' * (url_lfnum + 1), 1, 'C',
                   True)
    pdf.y = top
    pdf.x = offset
    pdf.multi_cell(w2, url_oapolicy_h, url, 1, 'L', False)
    top = pdf.y
    pdf.multi_cell(
        w1, url_oapolicy_h,
        lang_data["Title"]["OAPOLICY"] + '\n' * (oa_policy_lfnum + 1), 1, 'C',
        True)
    pdf.y = top
    pdf.x = offset
    pdf.multi_cell(w2, url_oapolicy_h, oa_policy, 1, 'L', False)
    pdf.ln(h=1)

    # Footer
    pdf.set_font('Courier', '', 10)
    pdf.set_x(108)

    license = item_metadata_json[_file_item_id][0].get('licensetype')
    if license == 'license_free':  # Free writing
        txt = item_metadata_json[_file_item_id][0].get('licensefree')
        if txt is None:
            txt = ''
        pdf.multi_cell(footer_w, footer_h, txt, 0, 'L', False)
    elif license == 'license_0':  # Attribution
        txt = lang_data["License"]["LICENSE_0"]
        src = blueprint.root_path + "/static/images/creative_commons/by.png"
        lnk = "http://creativecommons.org/licenses/by/4.0/"
        pdf.multi_cell(footer_w, footer_h, txt, 0, 1, 'L', False)
        pdf.ln(h=2)
        pdf.image(src,
                  x=cc_logo_xposition,
                  y=None,
                  w=0,
                  h=0,
                  type='',
                  link=lnk)
    elif license == 'license_1':  # Attribution-ShareAlike
        txt = lang_data["License"]["LICENSE_1"]
        src = blueprint.root_path + "/static/images/creative_commons/by-sa.png"
        lnk = "http://creativecommons.org/licenses/by-sa/4.0/"
        pdf.multi_cell(footer_w, footer_h, txt, 0, 1, 'L', False)
        pdf.ln(h=2)
        pdf.image(src,
                  x=cc_logo_xposition,
                  y=None,
                  w=0,
                  h=0,
                  type='',
                  link=lnk)
    elif license == 'license_2':  # Attribution-NoDerivatives
        txt = lang_data["License"]["LICENSE_2"]
        src = blueprint.root_path + "/static/images/creative_commons/by-nd.png"
        lnk = "http://creativecommons.org/licenses/by-nd/4.0/"
        pdf.multi_cell(footer_w, footer_h, txt, 0, 'L', False)
        pdf.ln(h=2)
        pdf.image(src,
                  x=cc_logo_xposition,
                  y=None,
                  w=0,
                  h=0,
                  type='',
                  link=lnk)
    elif license == 'license_3':  # Attribution-NonCommercial
        txt = lang_data["License"]["LICENSE_3"]
        src = blueprint.root_path + "/static/images/creative_commons/by-nc.png"
        lnk = "http://creativecommons.org/licenses/by-nc/4.0/"
        pdf.multi_cell(footer_w, footer_h, txt, 0, 'L', False)
        pdf.ln(h=2)
        pdf.image(src,
                  x=cc_logo_xposition,
                  y=None,
                  w=0,
                  h=0,
                  type='',
                  link=lnk)
    elif license == 'license_4':  # Attribution-NonCommercial-ShareAlike
        txt = lang_data["License"]["LICENSE_4"]
        src = blueprint.root_path + "/static/images/creative_commons/\
            by-nc-sa.png"

        lnk = "http://creativecommons.org/licenses/by-nc-sa/4.0/"
        pdf.multi_cell(footer_w, footer_h, txt, 0, 'L', False)
        pdf.ln(h=2)
        pdf.image(src,
                  x=cc_logo_xposition,
                  y=None,
                  w=0,
                  h=0,
                  type='',
                  link=lnk)
    elif license == 'license_5':  # Attribution-NonCommercial-NoDerivatives
        txt = lang_data["License"]["LICENSE_5"]
        src = blueprint.root_path + "/static/images/creative_commons/\
            by-nc-nd.png"

        lnk = "http://creativecommons.org/licenses/by-nc-nd/4.0/"
        pdf.multi_cell(footer_w, footer_h, txt, 0, 'L', False)
        pdf.ln(h=2)
        pdf.image(src,
                  x=cc_logo_xposition,
                  y=None,
                  w=0,
                  h=0,
                  type='',
                  link=lnk)
    else:
        pdf.multi_cell(footer_w, footer_h, '', 0, 'L', False)
    """ Convert PDF cover page data as bytecode """
    output = pdf.output(dest='S').encode('latin-1')
    b_output = io.BytesIO(output)

    # Combine cover page and existing pages
    cover_page = PdfFileReader(b_output)
    f = open(obj_file_uri, "rb")
    existing_pages = PdfFileReader(f)

    # In the case the PDF file is encrypted by the password, ''(i.e. not
    # encrypted intentionally)
    if existing_pages.isEncrypted:
        try:
            existing_pages.decrypt('')
        except BaseException:  # Errors such as NotImplementedError
            return ObjectResource.send_object(
                obj.bucket,
                obj,
                expected_chksum=fileobj.get('checksum'),
                logger_data={
                    'bucket_id': obj.bucket_id,
                    'pid_type': pid.pid_type,
                    'pid_value': pid.pid_value,
                },
                as_attachment=False)

    # In the case the PDF file is encrypted by the password except ''
    if existing_pages.isEncrypted:
        return ObjectResource.send_object(
            obj.bucket,
            obj,
            expected_chksum=fileobj.get('checksum'),
            logger_data={
                'bucket_id': obj.bucket_id,
                'pid_type': pid.pid_type,
                'pid_value': pid.pid_value,
            },
            as_attachment=False)

    combined_pages = PdfFileWriter()
    combined_pages.addPage(cover_page.getPage(0))
    for page_num in range(existing_pages.numPages):
        existing_page = existing_pages.getPage(page_num)
        combined_pages.addPage(existing_page)

    # Download the newly generated combined PDF file
    try:
        combined_filename = 'CV_' + datetime.now().strftime('%Y%m%d') + '_' + \
            item_metadata_json[_file_item_id][0].get("filename")

    except (KeyError, IndexError):
        combined_filename = 'CV_' + title + '.pdf'
    combined_filepath = "/code/invenio/{}.pdf".format(combined_filename)
    combined_file = open(combined_filepath, "wb")
    combined_pages.write(combined_file)
    combined_file.close()

    return send_file(combined_filepath,
                     as_attachment=True,
                     attachment_filename=combined_filename,
                     mimetype='application/pdf',
                     cache_timeout=-1)
Exemplo n.º 36
0
def create_pdf(bank_name, inn, kpp, bik, recipient, account_number1,
               account_number2, doc_number, date, provider, customer, reason):
    header = [['Банк получателя: ' + bank_name, 'БИК: ' + bik],
              [
                  "ИНН: " + inn + "   " + "КПП: " + kpp,
                  'Сч. №' + account_number1
              ], ['Получатель: ' + recipient, 'Сч. №' + account_number2]]
    pdf = FPDF()
    pdf.add_page()
    pdf.add_font('DejaVu', '', './fonts/DejaVuSansCondensed.ttf', uni=True)
    pdf.add_font('DejaVu',
                 'B',
                 './fonts/DejaVuSansCondensed-Bold.ttf',
                 uni=True)

    pdf.set_font('DejaVu', '', 12)

    # header
    col_width = pdf.w / 2.2
    row_height = pdf.font_size
    spacing = 2
    for row in header:
        for item in row:
            pdf.cell(col_width, row_height * spacing, txt=item, border=1)
        pdf.ln(row_height * spacing)

    font_size = 16
    pdf.set_font('DejaVu', 'B', font_size)
    pdf.ln(font_size / 2)
    pdf_common_line(pdf, font_size,
                    "Счёт на оплату №{} от {}г.".format(doc_number, date))
    pdf_common_line(pdf, font_size, "_" * 74)

    font_size = 12
    pdf.ln(font_size)
    pdf.set_font('DejaVu', '', font_size)
    pdf_common_line(pdf, font_size, "Поставщик")
    pdf_common_line(pdf, font_size, "(Исполнитель): {}".format(provider))
    pdf_common_line(pdf, font_size, "")
    pdf_common_line(pdf, font_size, "Покупатель")
    pdf_common_line(pdf, font_size, "(Заказчик): {}".format(customer))
    pdf_common_line(pdf, font_size, "")
    pdf_common_line(pdf, font_size, "Основание: {}".format(reason))
    pdf_common_line(pdf, font_size, "")

    # table
    font_size = 10
    row_height = pdf.font_size
    pdf.set_font('DejaVu', '', font_size)

    table = [['№', "Товары (работы, услуги)", "Кол-во", "Ед.", "Сумма"]]
    counter = 1

    # in calls
    for in_record in in_calls:
        table.append([
            str(counter), "Входящий звонок от {}".format(in_record[0]),
            "{} мин.".format(in_record[1]), "{} руб.".format(in_min_cost),
            "{} руб.".format(in_record[1] * in_min_cost)
        ])
        counter += 1

    if in_min_free:
        min_to_calc = min(in_min_free, res_count_in)
        table.append([
            str(counter), "Бесплатные минуты входящих звонков",
            "{} мин.".format(in_min_free), '',
            "{} руб.".format(min_to_calc * in_min_cost * -1)
        ])
        counter += 1

    # out calls
    for out_record in out_calls:
        table.append([
            str(counter), "Исходящий звонок к {}".format(out_record[0]),
            "{} мин.".format(out_record[1]), "{} руб.".format(out_min_cost),
            "{} руб.".format(out_record[1] * out_min_cost)
        ])
        counter += 1

    if out_min_free:
        min_to_calc = min(out_min_free, res_count_out)
        table.append([
            str(counter), "Бесплатные минуты исходящих звонков",
            "{} мин.".format(out_min_free), '',
            "{} руб.".format(min_to_calc * out_min_cost * -1)
        ])
        counter += 1

    # sms
    for sms_record in sms_list:
        table.append([
            str(counter), "SMS для {}".format(sms_record[0]),
            "{} шт.".format(sms_record[1]), "{} руб.".format(sms_cost),
            "{} руб.".format(sms_record[1] * sms_cost)
        ])
        counter += 1

    if sms_free:
        min_to_calc = min(sms_free, res_count_sms)
        table.append([
            str(counter), "Бесплатные SMS", "{} шт.".format(sms_free), '',
            "{} руб.".format(min_to_calc * sms_cost * -1)
        ])
        counter += 1

    # internet
    table.append([
        str(counter), "Интернет трафик (за МБ)", "{} МБ".format(traffic_mb),
        "{} руб.".format(Mb_cost), "{} руб.".format(net_cost)
    ])

    table.append(['', "ВСЕГО", '', '', "{} руб.".format(cost_tel + net_cost)])

    one_part = pdf.w / 18
    for row in table:
        pdf.cell(one_part * 1, row_height * spacing, txt=row[0],
                 border=1)  # number
        pdf.cell(one_part * 8, row_height * spacing, txt=row[1],
                 border=1)  # title
        pdf.cell(one_part * 2, row_height * spacing, txt=row[2],
                 border=1)  # count
        pdf.cell(one_part * 2, row_height * spacing, txt=row[3],
                 border=1)  # cost per one
        pdf.cell(one_part * 3, row_height * spacing, txt=row[4],
                 border=1)  # total cost
        pdf.ln(row_height * spacing)

    # footer
    font_size = 16
    pdf.set_font('DejaVu', 'B', font_size)
    pdf_common_line(pdf, font_size,
                    "Всего к оплате: {} руб.".format(cost_tel + net_cost))
    pdf_common_line(pdf, font_size, "")

    font_size = 8
    pdf.set_font('DejaVu', '', font_size)
    pdf_common_line(pdf, font_size, "Внимание!")
    pdf_common_line(
        pdf, font_size,
        "Оплата данного счёта означает согласие с условиями поставки товара/предоставления услуг."
    )
    pdf_common_line(pdf, font_size, "")

    font_size = 16
    pdf.set_font('DejaVu', 'B', font_size)
    pdf.ln(font_size / 2)
    pdf_common_line(pdf, font_size, "_" * 74)
    font_size = 12
    pdf.set_font('DejaVu', '', font_size)
    pdf.ln(font_size / 2)
    pdf_common_line(
        pdf, font_size,
        "Руководитель " + "_" * 20 + " " * 25 + "Бухгалтер " + "_" * 20)

    pdf.output(name=PDF_FILE, dest='F').encode('utf-8')
Exemplo n.º 37
0
    def process(self,
                output_file_name=None,
                dpi=150,
                offset=0,
                fps=10,
                height_mm=50,
                margins=Margin(10, 10, 10, 10),
                paper_format='a4'):

        def draw_raster():
            for ix in range(0, nx + 1):
                xx = x0 + ix * total.width
                pdf.line(xx, y0, xx, y1)
                if offset > 0 and ix != nx:
                    pdf.line(xx + offset, y0, xx + offset, y1)
            for iy in range(0, ny + 1):
                yy = y0 + iy * total.height
                pdf.line(x0, yy, x1, yy)

        height_mm = float(height_mm)
        tmp_files = []
        if self.clip:
            if fps != self.clip.fps:
                if self.verbosity > 0:
                    print 'Transcoding from {} fps to {} fps ...'.format(self.clip.fps, fps)
                self.clip.write_videofile('tmp.mp4', fps=fps, audio=False)
                tmp_files.append('tmp.mp4')
                self.clip = VideoFileClip('tmp.mp4')
                self.fps = self.clip.fps
                self.frame_count = int(self.clip.duration * self.fps)
            clip_size = Size.from_tuple(self.clip.size)
        elif self.frames:
            clip_size = Size.from_tuple(self.im.size)

        paper = self.PAPER_SIZES[paper_format.lower()]
        printable_area = Size(paper.width - margins.left - margins.right,
                              paper.height - margins.top - margins.bottom)
        frame_mm = Size(height_mm / clip_size.height * clip_size.width, height_mm)
        total = Size(offset + frame_mm.width, frame_mm.height)
        frame = Size(int(frame_mm.width / 25.4 * dpi),
                     int(frame_mm.height / 25.4 * dpi))
        nx = int(printable_area.width / total.width)
        ny = int(printable_area.height / total.height)
        if self.verbosity > 0:
            print 'Input:  {} fps, {}x{}, {} frames'\
                '\n        from: {}'\
                .format(
                    self.fps,
                    clip_size.width,
                    clip_size.height,
                    self.frame_count,
                    self.input_file_name
                )
            print 'Output: {}dpi, {}x{}, {:.2f}mm x {:.2f}mm, {}x{} tiles'\
                '\n        to: {}'\
                .format(
                    dpi,
                    frame.width, frame.height,
                    frame_mm.width, frame_mm.height,
                    nx, ny,
                    output_file_name
                )
        pdf = FPDF(unit='mm', format=paper_format.upper(), orientation='L')
        pdf.set_compression(True)
        pdf.set_title('Funny video')
        pdf.set_author('Oliver Lau <*****@*****.**> - Heise Medien GmbH & Co. KG')
        pdf.set_creator('flippy')
        pdf.set_keywords('flip-book, video, animated GIF')
        pdf.set_draw_color(128, 128, 128)
        pdf.set_line_width(0.1)
        pdf.set_font('Helvetica', '', 12)
        pdf.add_page()
        i = 0
        page = 0
        tx, ty = -1, 0
        x0, y0 = margins.left, margins.top
        x1, y1 = x0 + nx * total.width, y0 + ny * total.height

        if self.clip:
            all_frames = self.clip.iter_frames()
        elif self.frames:
            all_frames = AnimatedGif(self.im)
        else:
            all_frames = []
        for f in all_frames:
            ready = float(i + 1) / self.frame_count
            if self.verbosity:
                sys.stdout.write('\rProcessing frames |{:30}| {}%'
                                 .format('X' * int(30 * ready), int(100 * ready)))
                sys.stdout.flush()
            tx += 1
            if type(f) == GifImagePlugin.GifImageFile:
                f.putpalette(self.palette)
                self.last_im.paste(f)
                im = self.last_im.convert('RGBA')
            else:
                im = Image.fromarray(f)
                im.thumbnail(frame.to_tuple())
            if tx == nx:
                tx = 0
                ty += 1
                if ty == ny:
                    ty = 0
                    draw_raster()
                    pdf.add_page()
                    page += 1
            temp_file = 'tmp-{}-{}-{}.jpg'.format(page, tx, ty)
            im.save(temp_file)
            tmp_files.append(temp_file)
            x = x0 + tx * total.width
            y = y0 + ty * total.height
            pdf.image(temp_file,
                      x=x + offset,
                      y=y,
                      w=frame_mm.width,
                      h=frame_mm.height)
            text = Point(x, y + frame_mm.height - 2)
            if offset > 0:
                pdf.rotate(90, text.x, text.y)
                pdf.text(text.x, text.y + 5, '{}'.format(i))
                pdf.rotate(0)
            i += 1

        if y != 0 and x != 0:
            draw_raster()

        if self.verbosity > 0:
            print '\nGenerating PDF ...'
        pdf.output(name=output_file_name)
        if self.verbosity > 0:
            print 'Removing temporary files ...'
        for temp_file in tmp_files:
            os.remove(temp_file)
Exemplo n.º 38
0
class MathWorksheetGenerator:
    """class for generating math worksheet of specified size and main_type"""
    def __init__(self, type_: str, max_number: int):
        self.main_type = type_
        self.max_number = max_number
        self.pdf = FPDF()

        self.small_font_size = 10
        self.middle_font_size = 15
        self.large_font_size = 30
        self.size = 21
        self.tiny_pad_size = 2
        self.pad_size = 10
        self.large_pad_size = 30
        self.num_x_cell = 4
        self.num_y_cell = 2
        self.total_question = 80  # Must be a multiple of 40
        self.font_1 = 'Times'
        self.font_2 = 'Arial'

    def generate_question(self) -> QuestionInfo:
        """Generates each question and calculate the answer depending on the type_ in a list
        To keep it simple, number is generated randomly within the range of 0 to 100
        :return:  list of value1, main_type, value2, and answer for the generated question
        """
        num_1 = random.randint(0, self.max_number)
        num_2 = random.randint(0, self.max_number)
        if self.main_type == 'mix':
            current_type = random.choice(['+', '-', 'x'])
        else:
            current_type = self.main_type

        if current_type == '+':
            answer = num_1 + num_2
        elif current_type == '-':
            #  avoid having a negative answer which is an advanced concept
            num_1, num_2 = sorted((num_1, num_2))
            answer = num_1 - num_2
        elif current_type == 'x':
            answer = num_1 * num_2
        else:
            raise RuntimeError(
                f'Question main_type {current_type} not supported')
        return num_1, current_type, num_2, answer

    def get_list_of_questions(self) -> List[QuestionInfo]:
        """Generate all the questions for the worksheet in a list. Initially trying for unique questions, but
        allowing duplicates if needed (e.g. asking for 80 addition problems with max size 3 requires duplication)
        :return: list of questions
        """
        questions = []
        duplicates = 0
        while len(questions) < self.total_question:
            new_question = self.generate_question()
            if new_question not in questions or duplicates >= 10:
                questions.append(new_question)
            else:
                duplicates += 1
        return questions

    def make_question_page(self, data: List[QuestionInfo]):
        """Prepare a single page of questions"""
        total_page = int(self.total_question /
                         (self.num_x_cell * self.num_y_cell))
        for page in range(total_page):
            self.pdf.add_page(orientation='L')
            self.print_question_row(data, page * (2 * self.num_x_cell))
            self.print_horizontal_separator()
            self.print_question_row(
                data,
                page * (2 * self.num_x_cell) + self.num_x_cell)

    def print_top_row(self, question_num: str):
        """Helper function to print first character row of a question row"""
        self.pdf.set_font(self.font_1, size=self.middle_font_size)
        self.pdf.cell(self.pad_size,
                      self.pad_size,
                      txt=question_num,
                      border='LT',
                      align='C')
        self.pdf.cell(self.size, self.pad_size, border='T', align='C')
        self.pdf.cell(self.size, self.pad_size, border='T', align='C')
        self.pdf.cell(self.pad_size, self.pad_size, border='TR', align='C')

    def print_second_row(self, num: int):
        """Helper function to print second character row of a question row"""
        self.pdf.set_font(self.font_2, size=self.large_font_size)
        self.pdf.cell(self.pad_size, self.size, border='L', align='C')
        self.pdf.cell(self.size, self.size, align='C')
        self.pdf.cell(self.size, self.size, txt=str(num), align='R')
        self.pdf.cell(self.pad_size, self.size, border='R', align='C')

    def print_third_row(self, num: int, current_type: str):
        """Helper function to print third character row of a question row"""
        self.pdf.set_font(self.font_2, size=self.large_font_size)
        self.pdf.cell(self.pad_size, self.size, border='L', align='C')
        self.pdf.cell(self.size, self.size, txt=current_type, align='L')
        self.pdf.cell(self.size, self.size, txt=str(num), align='R')
        self.pdf.cell(self.pad_size, self.size, border='R', align='C')

    def print_bottom_row(self):
        """Helper function to print bottom row of question"""
        self.pdf.set_font(self.font_2, size=self.large_font_size)
        self.pdf.cell(self.pad_size, self.size, border='LB', align='C')
        self.pdf.cell(self.size, self.size, border='TB', align='C')
        self.pdf.cell(self.size, self.size, border='TB', align='R')
        self.pdf.cell(self.pad_size, self.size, border='BR', align='C')

    def print_edge_vertical_separator(self):
        """Print space between question for the top or bottom row"""
        self.pdf.cell(self.pad_size, self.pad_size)

    def print_middle_vertical_separator(self):
        """Print space between question for the second or third row"""
        self.pdf.cell(self.pad_size, self.size)

    def print_horizontal_separator(self):
        """Print line breaker between two rows of questions"""
        self.pdf.cell(self.size, self.size, align='C')
        self.pdf.ln()

    def print_question_row(self, data: List[QuestionInfo], offset: int):
        """Print a single row of questions (total question in a row is set by num_x_cell)"""
        for x in range(self.num_x_cell):
            self.print_top_row(str(x + 1 + offset))
            self.print_edge_vertical_separator()
        self.pdf.ln()
        for x in range(self.num_x_cell):
            self.print_second_row(data[x + offset][0])
            self.print_middle_vertical_separator()
        self.pdf.ln()
        for x in range(self.num_x_cell):
            self.print_third_row(data[x + offset][2], data[x + offset][1])
            self.print_middle_vertical_separator()
        self.pdf.ln()
        for _ in range(self.num_x_cell):
            self.print_bottom_row()
            self.print_edge_vertical_separator()
        self.pdf.ln()

    def make_answer_page(self, data):
        """Print answer sheet"""
        self.pdf.add_page(orientation='L')
        self.pdf.set_font(self.font_1, size=self.large_font_size)
        self.pdf.cell(self.large_pad_size,
                      self.large_pad_size,
                      txt='Answers',
                      ln=1,
                      align='C')

        for i in range(len(data)):
            self.pdf.set_font(self.font_1, size=self.small_font_size)
            self.pdf.cell(self.pad_size,
                          self.pad_size,
                          txt=f'{i + 1}:',
                          border='TLB',
                          align='R')
            self.pdf.set_font(self.font_2, size=self.small_font_size)
            self.pdf.cell(self.pad_size,
                          self.pad_size,
                          txt=str(data[i][3]),
                          border='TB',
                          align='R')
            self.pdf.cell(self.tiny_pad_size,
                          self.pad_size,
                          border='TRB',
                          align='R')
            self.pdf.cell(self.tiny_pad_size, self.pad_size, align='C')
            if i >= 9 and (i + 1) % 10 == 0:
                self.pdf.ln()
Exemplo n.º 39
0
        #new_lot_string = lot_string[:index] + "\n" + lot_string[index:]
        #return new_lot_string

    else:
        return lot_string


# the size of the pdf doc in pts
height = 1080
width = 1920

# prep pdf doc
pdf = FPDF(orientation='L', unit='pt', format=(height, width))
pdf.set_fill_color(0, 0, 0)
pdf.set_text_color(252, 255, 48)
pdf.set_font("Arial", "B", size=350)
pdf.set_margins(0, 0, 0)
pdf.set_auto_page_break(False, 0)

# open the csv file of lot info
with open('import.csv', newline='') as csvfile:
    lot_list = list(csv.reader(csvfile))

length = len(lot_list)
i = 1  #start at index 1 since row 1 of csv is column headers

while i < length:
    # create slide for group lots
    group = get_lot_group(lot_list[i])
    if group != "":
        count = 1  #counter to track number of lots in group
Exemplo n.º 40
0
    def export_to_pdf(self):
        """
        Exporting report to pdf.
        """
        pdf = FPDF()
        pdf.add_page()

        pdf.set_font("Arial", "B", size=20)
        pdf.cell(
            200, 10, txt="Analysis for {} on YouTube".format(self.keyword), ln=1, align="C"
        )
        pdf.set_font("Arial", size=14)
        pdf.cell(
            200,
            10,
            txt="Between {} and {}".format(self.start_date[0:10], self.end_date[0:10]),
            ln=2,
            align="C",
        )
        pdf.cell(200, 10, txt="", ln=3, align="C")
        pdf.set_font("Arial", "B", size=14)
        pdf.cell(200, 10, txt="Overall statistics", ln=4, align="L")
        pdf.set_font("Arial", size=12)
        pdf.cell(
            200, 10, txt="No. of views: {}".format(self.sum_views), ln=5, align="L"
        )
        pdf.cell(
            200,
            10,
            txt="No. of comments: {}".format(self.sum_comments),
            ln=6,
            align="L",
        )
        pdf.cell(
            200, 10, txt="No. of likes: {}".format(self.sum_likes), ln=7, align="L"
        )
        pdf.cell(
            200,
            10,
            txt="No. of dislikes: {}".format(self.sum_dislikes),
            ln=8,
            align="L",
        )
        pdf.cell(200, 10, txt="", ln=9, align="L")

        pdf.set_font("Arial", "B", size=14)
        new_inx = 10
        if "yearly" in self.analysis_type:

            pdf.cell(200, 10, txt="Yearly breakdown of statistics", ln=10, align="L")
            pdf.image(self.path + "/yearly_stats.png", w=150, h=150)
            new_inx = new_inx + 1

        if "monthly" in self.analysis_type:

            pdf.cell(200, 10, txt="Monthly breakdown of statistics", ln=11, align="L")
            pdf.image(self.path + "/monthly_views.png", w=150, h=90)
            pdf.image(self.path + "/monthly_comments.png", w=150, h=90)
            pdf.image(self.path + "/monthly_likes.png", w=150, h=90)
            pdf.image(self.path + "/monthly_dislikes.png", w=150, h=90)
            new_inx = new_inx + 1

        pdf.cell(
            200,
            10,
            txt="The content spoken about in the published videos",
            ln=new_inx,
            align="L",
        )
        pdf.image(self.path + "/videos.png", w=75, h=75)

        pdf.cell(
            200,
            10,
            txt="The locations mentioned in comments",
            ln=new_inx + 1,
            align="L",
        )
        pdf.image(self.path + "/comment_locations.png", w=75, h=75)

        output_path = self.path + "/{}_report.pdf".format(self.keyword.replace(" ", "_"))
        pdf.output(output_path)

        return output_path
Exemplo n.º 41
0
def Comandos():
    if request.form.get('Enviar') == 'Enviar':
        global comando
        comando = request.form['comando']
        now = datetime.datetime.now()
        newDirName = now.strftime("%H:%M:%S %d-%m-%Y")
        database_entry = {
            'Usuario:': usuario,
            'Comado:': comando,
            'Hora y Fecha:': newDirName,
            'Ip Del Servidor:': request.remote_addr
        }
        todos.insert_one(database_entry)
        os.system(comando + " > Respuesta.txt")
        with open("Respuesta.txt", "r") as myfile:
            data = myfile.read().replace('\n', ' ')
            myfile.close()
        if not data:
            data = "Comando invalido, intenta con uno nuevo!"
        else:
            data = data
        return render_template("Comandos.html", data=data)
    elif request.form.get('Excel') == 'Excel':
        datos = pd.read_csv('Respuesta.txt',
                            error_bad_lines=False,
                            engine="python",
                            index_col=False,
                            header=None)
        datos.to_excel("Excel.xlsx", index=False, header=False)
        Fuente = request.form.get("Fuente")
        Tamaño = request.form.get("Tamaño")
        Color = request.form.get("Color")
        if Color == "Negro":
            Colorfont = "000000"
        elif Color == "Rojo":
            Colorfont = "DB0000"
        elif Color == "Verde":
            Colorfont = "0B6623"
        file = 'Excel.xlsx'
        wb = load_workbook(filename=file)
        ws = wb['Sheet1']
        colorfuente = Font(name=Fuente, color=Colorfont, size=Tamaño)
        for cell in ws["A"]:
            cell.font = colorfuente
        wb.save(filename=file)
        print("\nEl archivo excel se ha creado con exito!")
        # Iniciamos los parámetros del script
        remitente = '*****@*****.**'
        destinatarios = correo
        asunto = '[FLASK]Resultado del comando ' + comando + ' en formato Excel'
        cuerpo = 'EL siguiente archivo contiene el resultado del comando solicitado!'
        ruta_adjunto = 'Excel.xlsx'
        nombre_adjunto = 'Excel.xlsx'
        mensaje = MIMEMultipart()
        mensaje['From'] = remitente
        mensaje['To'] = destinatarios
        mensaje['Subject'] = asunto
        mensaje.attach(MIMEText(cuerpo, 'plain'))
        archivo_adjunto = open(ruta_adjunto, 'rb')
        adjunto_MIME = MIMEBase('application', 'octet-stream')
        adjunto_MIME.set_payload((archivo_adjunto).read())
        encoders.encode_base64(adjunto_MIME)
        adjunto_MIME.add_header('Content-Disposition',
                                "attachment; filename= %s" % nombre_adjunto)
        mensaje.attach(adjunto_MIME)
        sesion_smtp = smtplib.SMTP('smtp.gmail.com', 587)
        sesion_smtp.starttls()
        sesion_smtp.login('*****@*****.**', 'Solariumdelvalle')
        texto = mensaje.as_string()
        sesion_smtp.sendmail(remitente, destinatarios, texto)
        sesion_smtp.quit()
        return render_template("ExcelE.html", datos=datos)
    elif request.form.get('Pdf') == 'Pdf':
        with open("Respuesta.txt", "r", encoding="utf-8") as myfile:
            data = myfile.read().replace('\n', ' ')
            myfile.close()
        Fuente = request.form.get("Fuente")
        Tamaño = request.form.get("Tamaño")
        Orientacion = request.form.get("Orientacion")
        Color = request.form.get("Color")
        if Color == "Negro":
            R = 0
            G = 0
            B = 0
        elif Color == "Rojo":
            R = 255
            G = 0
            B = 0
        elif Color == "Verde":
            R = 0
            G = 255
            B = 0
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font(Fuente, "", int(Tamaño))
        pdf.set_text_color(R, G, B)
        pdf.set_margins(10, 10, 10)
        pdf.multi_cell(0, 6, data, 0, Orientacion)
        pdf.ln(h="")
        pdf.output("PDF.pdf", "f")
        print("\nEl archivo pdf se ha creado con exito!")
        remitente = '*****@*****.**'
        destinatarios = correo
        asunto = '[FLASK]Resultado del comando ' + comando + ' en formato PDF'
        cuerpo = 'EL siguiente archivo contiene el resultado del comando solicitado!'
        ruta_adjunto = 'PDF.pdf'
        nombre_adjunto = 'PDF.pdf'
        mensaje = MIMEMultipart()
        mensaje['From'] = remitente
        mensaje['To'] = destinatarios
        mensaje['Subject'] = asunto
        mensaje.attach(MIMEText(cuerpo, 'plain'))
        archivo_adjunto = open(ruta_adjunto, 'rb')
        adjunto_MIME = MIMEBase('application', 'octet-stream')
        adjunto_MIME.set_payload((archivo_adjunto).read())
        encoders.encode_base64(adjunto_MIME)
        adjunto_MIME.add_header('Content-Disposition',
                                "attachment; filename= %s" % nombre_adjunto)
        mensaje.attach(adjunto_MIME)
        sesion_smtp = smtplib.SMTP('smtp.gmail.com', 587)
        sesion_smtp.starttls()
        sesion_smtp.login('*****@*****.**', 'Solariumdelvalle')
        texto = mensaje.as_string()
        sesion_smtp.sendmail(remitente, destinatarios, texto)
        sesion_smtp.quit()
        return render_template("PdfE.html", data=data)
    return render_template("Comandos.html")
Exemplo n.º 42
0
class PdfGenerator(object):
    """
    Allows a pdf file to be created. The user of class can use the various methods
    available to manually create data in a given Pdf file. For example by calling
    the title method the user can add a title to the top of the page or change
    the color by calling the color method. The class also allows the use to add
    a single line of data to a cell but to add multiple data to a cell the
    insert_data_multiple_cell must be called
    """
    def __init__(self, file_name, font_family="Arial", size=10, style="B"):
        self.file_name = file_name
        self._pdf = FPDF(unit="pt", format="A4")
        self._pdf.add_page()
        self._pdf.set_font(family=font_family, size=size, style=style)

    def generate(self):
        """when called this creates the full pdf file and stores it in the root folder."""
        self._pdf.output(self.file_name)

    def change_font_color(self, red: int, green: int, blue: int) -> None:
        """change_font_color(red:int, green: int, blue: int)"

           Uses the RGB color system to change the font color of a text.
           In order to change the text of a color this method must be
           called first then unless this is called again and new color
           system added any text added will be the color that was set
           when this method was called
        """
        self._pdf.set_text_color(r=red, g=green, b=blue)

    def change_font(self, font_family="Arial", style="", size=16):
        """change_font(font_family: str, style:str, size: int) -> returns None

           When this is called allows the font text to be set. This style
           and the size of the font can also be set.

           :parameter

                style: The style takes three options
                    B: Bold
                    I: Italic
                    U: Underline

                    The style can also be combined in the following ways

                    For example:
                        BI: This makes the text bold and italic
                        BU: This makes the text bold and then underline
                        BIU: This makes the text bold, italic and then underlines the text

        """
        self._pdf.set_font(family=font_family, style=style, size=size)

    def insert_title(self,
                     title,
                     cell_height,
                     cell_width=0,
                     border=0,
                     align="C"):
        """insert_title(title: str, cell_height:int, cell_width: int, border: int, align: str)


        """
        self._pdf.cell(cell_width,
                       cell_height,
                       txt=str(title),
                       border=border,
                       align=align)

    def insert_data_multiple_cell(self,
                                  cell_width,
                                  cell_height,
                                  data_txt,
                                  align="L",
                                  border=0):
        self._pdf.multi_cell(w=cell_width,
                             h=cell_height,
                             txt=str(data_txt),
                             border=border,
                             align=align)

    def insert_data_single_cell(self,
                                cell_width,
                                cell_height,
                                data_txt,
                                align="L",
                                border=0):
        self._pdf.cell(cell_width,
                       cell_height,
                       data_txt,
                       align=align,
                       border=border)

    def add_new_line(self):
        self._pdf.ln()

    def add_img(self, img, width, height):
        self._pdf.image(img, w=width, h=height)
Exemplo n.º 43
0
def generate_pdf(uncommon, dow_data):
    # convert numeric days to words
    dayOfWeek = {
        0: 'Monday',
        1: 'Tuesday',
        2: 'Wednesday',
        3: 'Thursday',
        4: 'Friday',
        5: 'Saturday',
        6: 'Sunday'
    }
    dow_data = pd.DataFrame({
        'day': dow_data.index,
        'avg_visits': dow_data.values
    })
    dow_data['weekday'] = dow_data['day'].map(dayOfWeek)

    from fpdf import FPDF

    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    pdf.cell(40, 10, 'Vector Space Member Data Report')
    pdf.cell(10, 40, datetime.now().strftime('%m-%d-%Y'))

    pdf.add_page()
    pdf.set_font('Arial', '', 10)
    pdf.image('percent_active.png', x=None, y=None, w=180, type='', link='')

    pdf.add_page()
    pdf.set_font('Arial', '', 10)
    pdf.cell(
        40, 20,
        'The following people have keyed into the space in the last 90 days, but not in the last 30 days.',
        0, 2, "L")
    for i in range(0, len(uncommon)):
        if i % 2 == 0:
            pdf.cell(50, 8, '%s' % (uncommon['member'].loc[i]), 0, 0, 'C')
        else:
            pdf.cell(50, 8, '%s' % (uncommon['member'].loc[i]), 0, 2, 'C')
            pdf.cell(-50)

    pdf.add_page()
    pdf.cell(40, 20, 'Average number of unique entries by day of week.', 0, 2,
             "L")

    dow_data = dow_data.drop(columns=['day'])
    dow_data = dow_data.set_index('avg_visits')
    data = dow_data.sort_values(by=['avg_visits'], ascending=False).to_string()

    for line in data.splitlines()[1:]:
        pdf.cell(50, 8, '%s' % (line), 0, 2, 'R')

    pdf.add_page()
    today = datetime.now().strftime('%Y-%m-%d')
    pdf.image('weekly_visits_' + today + '.png',
              x=None,
              y=None,
              w=180,
              type='',
              link='')
    pdf.add_page()
    pdf.image('daily_uniques.png', x=None, y=None, w=180, type='', link='')
    pdf.add_page()
    pdf.image('monthly_visits_' + today + '.png',
              x=None,
              y=None,
              w=180,
              type='',
              link='')

    Path("./reports").mkdir(parents=True, exist_ok=True)
    pdf.output('./reports/member-data_' + today + '.pdf', 'F')

    # cleanup plots
    fileList = glob.glob(
        '/vsfs01/home/aspontarelli/Documents/member_data_analysis/*.png')
    for filePath in fileList:
        try:
            os.remove(filePath)
        except:
            print("Error while deleting file : ", filePath)
Exemplo n.º 44
0
def generatePDFshares(splits, threshold, shared_key, txid):
    for i in range(splits):
        pdf = FPDF()
        pdf.add_page()
        try:
            pdf.image('Flo.png', 80, 20, 33)
            pdf.ln(50)
        except:
            pdf.set_font('Courier', '', 12)
            pdf.cell(40, 40, 'No Image', 1, 10, 'C')
            pdf.ln(10)
        pdf.set_font('Courier', '', 50)
        pdf.multi_cell(0, 10, 'FLO Secret', 0, 'C', False)
        pdf.set_font('Courier', '', 12)
        pdf.multi_cell(0, 10, 'Powered by the FLO Blockchain', 0, 'C', False)
        pdf.set_font('Times', '', 16)
        pdf.ln(20)
        pdf.multi_cell(
            0, 10,
            'A secret has been encrypted and stored on the blockchain of the FLO cryptocurrency and your Secret ID is : ',
            0, 'J', False)
        pdf.set_font('Courier', '', 12)
        pdf.multi_cell(0, 10, str(txid), 1, 'C', False)
        pdf.set_font('Times', '', 16)
        pdf.ln(10)
        pdf.multi_cell(
            0, 10,
            'The key to decrypt this secret has been split in ' + str(splits) +
            ' shares like this one. By design, the secret can be decrypted with any '
            + str(threshold) + ' of these shares.', 0, 'J', False)
        pdf.ln(10)
        pdf.multi_cell(
            0, 10, 'Below is the part of the key that belongs to this share',
            0, 'J', False)
        pdf.set_font('Courier', '', 12)
        pdf.multi_cell(0, 5, str(shared_key[i]), 1, 'L', False)
        pdf.set_font('Times', '', 16)
        pdf.ln(10)
        pdf.multi_cell(0, 10, 'Use the FLO Secret app to decrypt the secret',
                       0, 'J', False)
        pdf.multi_cell(0, 20, 'Download FLO Secret from the below link', 0,
                       'J', False)
        pdf.set_font('Courier', '', 14)
        pdf.cell(0, 0, 'https://github.com/akhil2015/FLO-shared-secret', 0, 0,
                 'L', False, "https://github.com/akhil2015/FLO-shared-secret")
        filename = 'Flo_Secret_' + txid + '/sharedkey_' + str(i + 1) + '.pdf'
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        pdf.output(filename, 'F')
Exemplo n.º 45
0
    def get(self, data = None):
        out_type = self.get_argument('type', 'html')
        components = []
        components = self.get_query_arguments('action[]', [])
        multiply = int(self.get_argument('multiply', 5))
        layout = self.get_argument('template', '70x40_simple')
        skip = int(self.get_argument('skip', 0))
        #print("Soucastky..",components)
        if len(components) > 0:
            comp = list(self.mdb.stock.find({'_id' : {'$in' : components}}))
        else:
            comp = list(self.mdb.stock.find().sort([("category", 1), ("_id",1)]))
        page = 0
        #print("Budeme tisknout:", comp)

        if layout == 'souhrn_01':
            autori = self.get_query_argument('autor', None)
            if not autori: autori = ['autory vlozite pridanim autoru do adresy s parametrem "autor"', 'autoru muze byt vice, pouzijte vice parametru', 'Například pridanim tohoto na konec adresy: &autor=Tester První']
            datum = self.get_argument('datum', ">>pro specifikovani pridejte parametr 'datum' do GET parametru<<")
            page = 1
            money_sum = 0
            Err = []

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')
            pdf.set_auto_page_break(False)

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans', '', 12)
            pdf.add_page()

            pdf.set_xy(0, 40)
            pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2)
            pdf.set_xy(0, 46)
            pdf.cell(pdf.w, 0, 'Universal Scientific Technologies s.r.o.', align='C', ln=2)

            pdf.set_xy(20, 200)
            pdf.cell(1,0, 'Inventuru provedli:', ln=2)
            for x in autori:
                pdf.cell(1,20, x, ln=2)

            pdf.set_font('pt_sans', '', 8)
            pdf.set_xy(120, 288)
            pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

            pdf.add_page()


            data = self.mdb.stock.aggregate([
                    {'$addFields': {'count': {'$sum': '$history.bilance'}}}
                ])


            gen_time = datetime.datetime(2018, 10, 1)
            lastOid = ObjectId.from_datetime(gen_time)


            for i, component in enumerate(data):
            #for i, component in enumerate(list(data)[:30]):
                print(i, "=============================")
                print(component['_id'])
                try:
                    ## Pokud je konec stránky
                    if pdf.get_y() > pdf.h-20:
                        pdf.line(10, pdf.get_y()+0.5, pdf.w-10, pdf.get_y()+0.5)

                        pdf.set_font('pt_sans', '', 10)
                        pdf.set_xy(150, pdf.get_y()+1)
                        pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

                        pdf.add_page()

                    ## Pokud je nová strana
                    if page != pdf.page_no():
                        pdf.set_font('pt_sans', '', 8)
                        page = pdf.page_no()
                        pdf.set_xy(120, 288)
                        pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

                        pdf.set_font('pt_sans', '', 11)
                        pdf.set_xy(10, 10)
                        pdf.cell(100, 5, 'Skladová položka')
                        pdf.set_x(95)
                        pdf.cell(10, 5, "Počet kusů", align='R')
                        pdf.set_x(120)
                        pdf.cell(10, 5, "Cena za 1ks", align='R')
                        pdf.set_x(180)
                        pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2)
                        pdf.line(10, 15, pdf.w-10, 15)
                        pdf.set_y(18)
                        page_sum = 0

                    pdf.set_font('pt_sans', '', 10)

                    count = component['count']

                    if count >0:
                        price = 0
                        price_ks = 0
                        first_price = 0


                        pdf.set_x(10)
                        pdf.cell(100, 5, component['_id'])

                        pdf.set_x(95)
                        pdf.cell(10, 5, "%5.d" %(count), align='R')

                    pdf.set_x(10)
                    pdf.cell(100, 5, "{:5.0f}  {}".format(i, component['_id']))


                    inventura = False
                    for x in reversed(component.get('history', [])):
                        if x.get('operation', None) == 'inventory':
                            print("inventura", x)
                            if x['_id'].generation_time > lastOid.generation_time:
                                print("#############")
                                inventura = True
                                count = x['absolute']

                                pdf.set_x(110)
                                pdf.cell(1, 5, "i")
                                break;

                    pdf.set_font('pt_sans', '', 10)
                    pdf.set_x(95)
                    pdf.cell(10, 5, "{} j".format(count), align='R')

                    rest = count

                    for x in reversed(component.get('history', [])):

                        if x.get('price', 0) > 0:
                            if first_price == 0:
                                first_price = x['price']
                            if x['bilance'] > 0:
                                if x['bilance'] <= rest:
                                    price += x['price']*x['bilance']
                                    rest -= x['bilance']
                                else:
                                    price += x['price']*rest
                                    rest = 0

                    print("Zbývá", rest, "ks, secteno", count-rest, "za cenu", price)
                    if(count-rest): price += rest*first_price
                    money_sum += price
                    page_sum +=price

                    if price == 0.0 and x.get('count', 0) > 0:
                        Err.append('Polozka >%s< nulová cena, nenulový počet' %(component['_id']))

                    pdf.set_x(120)
                    if count > 0: pdf.cell(10, 5, "%6.2f Kč" %(price/count), align='R')
                    else: pdf.cell(10, 5, "%6.2f Kč" %(0), align='R')

                    pdf.set_font('pt_sans-bold', '', 10)
                    pdf.set_x(180)
                    pdf.cell(10, 5, "%6.2f Kč" %(price), align='R')


                except Exception as e:
                    Err.append('Err' + repr(e) + component['_id'])
                    print(e)

                pdf.set_y(pdf.get_y()+4)

            pdf.line(10, pdf.get_y(), pdf.w-10, pdf.get_y())
            pdf.set_font('pt_sans', '', 8)
            pdf.set_x(180)
            pdf.cell(10, 5, "Konec souhrnu", align='R')

            pdf.set_font('pt_sans', '', 10)
            pdf.set_xy(150, pdf.get_y()+3)
            pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

            pdf.page = 1
            pdf.set_xy(20,175)
            pdf.set_font('pt_sans', '', 12)
            pdf.cell(20,20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %(datum, money_sum))
            if len(Err) > 0:
                pdf.set_xy(30,80)
                pdf.cell(1,6,"Pozor, chyby ve skladu:", ln=2)
                pdf.set_x(32)
                for ch in Err:
                    pdf.cell(1,5,ch,ln=2)
            pdf.page = page

            print(autori)



        if layout == '105x74_simple':
            page = 0
            page_cols = 2
            page_rows = 4
            page_cells = page_cols * page_rows
            cell_w = 105
            cell_h = 75

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+10)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w, h=10)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+5, cell_y+23)
                try:
                    pdf.multi_cell(cell_w-10, 5, component['description'])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-15)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")


        if layout == '70x42-3_simple':
            page = 0
            page_cols = 3
            page_rows = 7
            page_cells = page_cols * page_rows
            cell_w = 210/page_cols
            cell_h = 297/page_rows


            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['name'].strip().replace('/', '_')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                pdf.set_xy(cell_x+5, cell_y+6.75)
                if len(component['name'])<23:
                    pdf.set_font('pt_sans-bold', '', 14)
                else:
                    pdf.set_font('pt_sans-bold', '', 10)
                pdf.cell(cell_w-10, 0, component['name'][:35])
                pdf.set_xy(cell_x+2.5, cell_y+9)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w-5, h=7)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+4, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-8, 4, component['description'][:185])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-7)
                pdf.set_xy(cell_x+5, cell_y+13)
                pdf.set_font('pt_sans', '', 7.5)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + " |" + str(datetime.date.today()) + "| " + component['_id'])



        if layout == '105x48_simple':
            page = 0
            page_cols = 2
            page_rows = 6
            page_cells = page_cols * page_rows
            #cell_w = 105
            #cell_h = 48
            cell_w = 210/page_cols
            cell_h = 297/page_rows

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+10)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w, h=10)

                pdf.set_font('pt_sans', '', 10)
                pdf.set_xy(cell_x+5, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-10, 4, component['description'][:275])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 4, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-10)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")


        elif layout == '105x48_panorama':
            page = 0
            page_cols = 6
            page_rows = 2
            page_cells = page_cols * page_rows
            cell_w = 48
            cell_h = 105

            print ("pozadovany format je:", layout)
            pdf = FPDF('L', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+cell_h)
                pdf.rotate(90)
                pdf.image('static/barcode/%s.png'%(id), w = cell_h-5, h=10)
                pdf.rotate(0)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+8, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-10, 5, component['description'])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-15)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")



        pdf.output("static/tmp/sestava.pdf")
        with open('static/tmp/sestava.pdf', 'rb') as f:
            self.set_header("Content-Type", 'application/pdf; charset="utf-8"')
            self.set_header("Content-Disposition", "inline; filename=UST_tiskova_sestava.pdf")
            self.write(f.read())
        f.close()
Exemplo n.º 46
0
    def get(self, request, *args, **kwargs):
        from fpdf import FPDF

        pdf = FPDF()
        pdf.add_font('DejaVu','','rink/fonts/DejaVuSansCondensed.ttf',uni=True)

        roster = Roster.objects.filter(event__slug=self.event.slug)

        for roster_entry in roster:

            registration_data = roster_entry.registrationdata_set.first()

            pdf.add_page()
            pdf.set_margins(16, 2)
            pdf.ln(20)

            pdf.set_font('DejaVu','',16)
            pdf.cell(40,40,'Derby Name:')
            pdf.set_font('DejaVu','',48)
            pdf.cell(40,40, roster_entry.user.derby_name)
            pdf.ln(20)
            
            pdf.set_font('DejaVu','',16)
            pdf.cell(40,40,'Real Name:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(40,40, roster_entry.user.first_name + " " + roster_entry.user.last_name)
            pdf.ln(20)
            
            pdf.set_font('DejaVu','',16)
            pdf.cell(60,40,'Date of Birth:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, str(registration_data.emergency_date_of_birth))
            pdf.ln(10)
            
            pdf.set_font('DejaVu','',16)
            pdf.cell(60,40,'Emergency Contact:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, registration_data.emergency_contact)
            pdf.ln(10)
            pdf.cell(60,40,'')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, registration_data.emergency_phone)
            pdf.ln(10)
            pdf.cell(60,40,'')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, registration_data.emergency_relationship)
            pdf.ln(15)
            
            if registration_data.emergency_contact_second:
                pdf.set_font('DejaVu','',16)
                pdf.cell(60,40,'Emergency Contact #2:')
                pdf.set_font('DejaVu','',24)
                pdf.cell(0,40, registration_data.emergency_contact_second)
                pdf.ln(10)
                pdf.cell(60,40,'')
                pdf.set_font('DejaVu','',24)
                pdf.cell(0,40, registration_data.emergency_phone_second)
                pdf.ln(10)
                pdf.cell(60,40,'')
                pdf.set_font('DejaVu','',24)
                pdf.cell(0,40, registration_data.emergency_relationship_second)
                pdf.ln(15)

            pdf.set_font('DejaVu','',16)
            pdf.cell(60,40,'Hosptial Preference:')
            pdf.set_font('DejaVu','',24)
            pdf.cell(0,40, registration_data.emergency_hospital)
            pdf.ln(15)
            
            pdf.set_font('DejaVu','',12)
            pdf.multi_cell(0,40,'Medical Conditions:')
            pdf.ln(-15)
            pdf.set_font('DejaVu','',24)
            if registration_data.emergency_allergies == "":
                details = "<none>"
            else:
                details = registration_data.emergency_allergies
            
            pdf.write(12, details)
            pdf.ln(25)

            wftda = ""
            try:
                wftda = int(registration_data.derby_insurance_number)
            except:
                pass

            pdf.set_font('Courier','',7)
            pdf.write(4, 'RINK #' + str(registration_data.user.id) + " | " + str(registration_data.user.email) + " | WFTDA #" + str(wftda) + " | generated on " + strftime("%Y-%m-%d", gmtime()))

        pdf.output('/tmp/rink_medical.pdf', 'F')

        with open('/tmp/rink_medical.pdf', 'rb') as pdf:
            response = HttpResponse(pdf.read(), content_type='application/pdf')
            response['Content-Disposition'] = 'inline;filename=rink_medical.pdf'

        os.remove('/tmp/rink_medical.pdf')
        return response
Exemplo n.º 47
0
class MakePDF(FPDF):


    def __init__(self, result_dict: dict, filename: str):
        super().__init__()
        # try:
        self._result = SelectIndividual(result_dict)
        self._result_dict = self._result.get_result_dict()
        self.annotation = "Даний підбір виконано автоматично. Для підтвердження підбору зверніться у проектну організацію"
        self.title1 = "З/б балка Б-1. Опалубне креслення"
        self.title2 = "З/б балка Б-1. Армування"
        self.title3 = "Специфікація"
        if int(self._result_dict["Б-1"][2]) < 2500 and int(self._result_dict["Б-1"][3]) < 400:
            self.scale = 10
        else:
            self.scale = 20
        self.count_of_lines = 11
        self.form3 = FPDF(orientation="L", unit="mm", format="A3")
        self.form3.add_page()
        self.form3.add_font("iso", "", "static/ISOCPEUR/ISOCPEUR.ttf", uni=True)
        self._draw_form_3()
        self._draw_specification(self._result_dict, 20, 184, self.title3)
        self._make()
        self.form3.output(f"static/{filename}")
        # except:
        #     self.make_error()

    # def _initial_scale_dimension(self):
    #     self.scale = 10
    #     self.l = (int(self._result_dict["Б-1"][2]) + 500) / self.scale
    #     self.h = int(self._result_dict["Б-1"][3]) / self.scale
    #     self.b = int(self._result_dict["Б-1"][4]) / self.scale
    #     diam_pos1 = self._result_dict["1"][1] / self.scale
    #     diam_pos2 = self._result_dict["2"][1] / self.scale
    #     diam_pos3 = self._result_dict["3"][1] / self.scale
    #     diam_pos4 = self._result_dict["4"][1] / self.scale
    #     self.a = diam_pos1 / 2 + 20 / self.scale

    def make_error(self):
        return "Помилка! З даними параметрами неможливо виконати розрахунок. Збільшіть висоту перерізу."

    def _make(self):
        self._draw_beam(36, 30)
        self._draw_rainforcment(36, 110)

    def _draw_beam(self, x, y):
        x0 = x
        y0 = y
        l = (int(self._result_dict["Б-1"][2]) + 500) / self.scale
        h = int(self._result_dict["Б-1"][3]) / self.scale
        b = int(self._result_dict["Б-1"][4]) / self.scale
        self.form3.set_font("iso", "", 14)
        self.form3.text(x0 + l / 2.5, y0 - 5, self.title1)
        self.form3.set_line_width(0.5)
        self.form3.rect(x0, y0, l, h)
        self._dim_h(x0, y0 + h, l)
        self._dim_v(x0, y0, h)
        if l > 250:
            self.form3.rect(x0 + l + 16, y0, b, h)
            self._dim_h(x0 + l + 16, y0 + h, b)
        else:
            self.form3.rect(x0 + l + 30, y0, b, h)
            self._dim_h(x0 + l + 30, y0 + h, b)

    def _draw_rainforcment(self, x, y):
        x0 = x
        y0 = y
        l = (int(self._result_dict["Б-1"][2]) + 500) / self.scale
        h = int(self._result_dict["Б-1"][3]) / self.scale
        b = int(self._result_dict["Б-1"][4]) / self.scale
        self.form3.set_font("iso", "", 14)
        self.form3.text(x0 + l / 2.35, y0 - 5, self.title2)
        diam_pos1 = self._result_dict["1"][1] / self.scale
        diam_pos2 = self._result_dict["2"][1] / self.scale
        diam_pos3 = self._result_dict["3"][1] / self.scale
        diam_pos4 = self._result_dict["4"][1] / self.scale
        a = diam_pos1 / 2 + 20 / self.scale
        self.form3.set_line_width(0.05)
        self.form3.rect(x0, y0, l, h)
        pos1_l = int(self._result_dict["1"][3] / self.scale * 1000)
        pos2_l = int(self._result_dict["2"][3] / self.scale * 1000)
        self.form3.set_line_width(0.5)
        self.form3.line(x0 + 30 / self.scale, y0 + h - a, x0 + 30 / self.scale + pos1_l, y0 + h - 30 / self.scale)
        self.form3.line(x0 + 30 / self.scale, y0 + a, x0 + 30 / self.scale + pos2_l, y0 + 30 / self.scale)
        pos3_data = self._result.get_distance_position_3_4()

        def draw_pos3(x, y):
            self.form3.line(
                x,
                y + a - diam_pos2 / 2 - diam_pos3 / 2,
                x,
                y + h - a + diam_pos2 / 2 + diam_pos3 / 2,
            )

        draw_pos3(x0 + (30 + 50) / self.scale, y0)
        draw_pos3(x0 + (30 + 50) / self.scale + pos3_data[1] * 1000 / self.scale, y0)
        draw_pos3(x0 + l - (30 + 50) / self.scale - pos3_data[1] * 1000 / self.scale, y0)
        draw_pos3(x0 + l - (30 + 50) / self.scale, y0)
        mid_dist_temp = round((pos2_l * self.scale - (50 + pos3_data[1] * 1000) * 2 - pos3_data[3] * 1000) / 2)
        mid_dist = mid_dist_temp / self.scale
        draw_pos3(x0 + 30 / self.scale + (50 + pos3_data[1] * 1000) / self.scale + mid_dist, y0)
        draw_pos3(x0 + 30 / self.scale + (50 + pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + mid_dist, y0)
        s = (b - 2 * a) / (self._result_dict["1"][0] - 1)
        if l > 250:
            self.form3.set_line_width(0.05)
            self.form3.rect(x0 + l + 16, y0, b, h)
            self.form3.set_line_width(0.5)
            self.form3.line(
                x0 + l + 16 + a - (diam_pos3 + diam_pos1) / 2,
                y0 + 10 / self.scale,
                x0 + l + 16 + a - (diam_pos3 + diam_pos1) / 2,
                y0 + h - 10 / self.scale
            )
            self.form3.line(
                x0 + l + 16 + b - a + (diam_pos3 + diam_pos1) / 2,
                y0 + 10 / self.scale,
                x0 + l + 16 + b - a + (diam_pos3 + diam_pos1) / 2,
                y0 + h - 10 / self.scale
            )
            self.form3.line(
                x0 + l + 16 + 10 / self.scale,
                y0 + a - (diam_pos3 + diam_pos2) / 2,
                x0 + l + 16 + b - 10 / self.scale,
                y0 + a - (diam_pos3 + diam_pos2) / 2
            )
            self.form3.line(
                x0 + l + 16 + 10 / self.scale,
                y0 + h - a + (diam_pos3 + diam_pos1) / 2,
                x0 + l + 16 + b - 10 / self.scale,
                y0 + h - a + (diam_pos3 + diam_pos1) / 2
            )
            self.form3.set_line_width(0.05)
            self.form3.ellipse(x0 + l + 16 + a - diam_pos1 / 2, y0 + a - diam_pos2 / 2, diam_pos2, diam_pos2, "FD")
            self.form3.ellipse(x0 + l + 16 - a + diam_pos1 / 2 + b - diam_pos2, y0 + a - diam_pos2 / 2, diam_pos2, diam_pos2, "FD")
            for i in range(self._result_dict["1"][0]):
                self.form3.ellipse(x0 + l + 16 + a - diam_pos1 / 2 + s * i, y0 + h - a - diam_pos1 / 2, diam_pos1, diam_pos1, "FD")
        else:
            self.form3.set_line_width(0.05)
            self.form3.rect(x0 + l + 30, y0, b, h)
            self.form3.set_line_width(0.5)
            self.form3.line(
                x0 + l + 30 + a - (diam_pos3 + diam_pos1) / 2,
                y0 + 10 / self.scale,
                x0 + l + 30 + a - (diam_pos3 + diam_pos1) / 2,
                y0 + h - 10 / self.scale
            )
            self.form3.line(
                x0 + l + 30 + b - a + (diam_pos3 + diam_pos1) / 2,
                y0 + 10 / self.scale,
                x0 + l + 30 + b - a + (diam_pos3 + diam_pos1) / 2,
                y0 + h - 10 / self.scale
            )
            self.form3.line(
                x0 + l + 30 + 10 / self.scale,
                y0 + a - (diam_pos3 + diam_pos2) / 2,
                x0 + l + 30 + b - 10 / self.scale,
                y0 + a - (diam_pos3 + diam_pos2) / 2
            )
            self.form3.line(
                x0 + l + 30 + 10 / self.scale,
                y0 + h - a + (diam_pos3 + diam_pos1) / 2,
                x0 + l + 30 + b - 10 / self.scale,
                y0 + h - a + (diam_pos3 + diam_pos1) / 2
            )
            self.form3.set_line_width(0.05)
            self.form3.ellipse(x0 + l + 30 + a - diam_pos1 / 2, y0 + a - diam_pos2 / 2, diam_pos2, diam_pos2, "FD")
            self.form3.ellipse(x0 + l + 30 - a + diam_pos1 / 2 + b - diam_pos2, y0 + a - diam_pos2 / 2, diam_pos2, diam_pos2, "FD")
            for i in range(self._result_dict["1"][0]):
                self.form3.ellipse(x0 + l + 30 + a - diam_pos1 / 2 + s * i, y0 + h - a - diam_pos1 / 2, diam_pos1, diam_pos1, "FD")
        self._dim_h(x0, y0 + h, 30 / self.scale, -3.5)
        self._dim_h(x0 + 30 / self.scale, y0 + h, 50 / self.scale, 5)
        self._dim_h(
            x0 + 30 / self.scale + 50 / self.scale,
            y0 + h,
            pos3_data[1] * 1000 / self.scale,
            -5,
            f"{pos3_data[0] - 1}x100={(pos3_data[0] - 1) * 100}"
        )
        self._dim_h(
            x0 + 30 / self.scale + 50 / self.scale + pos3_data[1] * 1000 / self.scale,
            y0 + h,
            mid_dist
        )
        self._dim_h(
            x0 + 30 / self.scale + 50 / self.scale + pos3_data[1] * 1000 / self.scale + mid_dist,
            y0 + h,
            pos3_data[3] * 1000 / self.scale,
            -5,
            f"{pos3_data[2] - 1}x200={(pos3_data[2] - 1) * 200}"
        )
        self._dim_h(
            x0 + 30 / self.scale + 50 / self.scale + pos3_data[1] * 1000 / self.scale + mid_dist + pos3_data[3] * 1000 / self.scale,
            y0 + h,
            mid_dist
        )
        self._dim_h(
            x0 + 30 / self.scale + 50 / self.scale + pos3_data[1] * 1000 / self.scale + 2 * mid_dist + pos3_data[3] * 1000 / self.scale,
            y0 + h,
            pos3_data[1] * 1000 / self.scale,
            -5,
            f"{pos3_data[0] - 1}x100={(pos3_data[0] - 1) * 100}"
        )
        self._dim_h(
            x0 + 30 / self.scale + 50 / self.scale + 2 * pos3_data[1] * 1000 / self.scale + 2 * mid_dist + pos3_data[3] * 1000 / self.scale,
            y0 + h,
            50 / self.scale,
            -4.5
        )
        self._dim_h(
            x0 + 30 / self.scale + 2 * 50 / self.scale + 2 * pos3_data[1] * 1000 / self.scale + 2 * mid_dist + pos3_data[3] * 1000 / self.scale,
            y0 + h,
            30 / self.scale,
            4
        )
        self._dim_v(x0, y0, a, 3)
        self._dim_v(x0, y0 + a, h - 2 * a)
        self._dim_v(x0, y0 - a + h, a, -3)
        if l > 250:
            self._dim_h(x0 + l + 16, y0 + h, a, -3)
            if self._result_dict['1'][0] > 2:
                self._dim_h(
                    x0 + l + 16 + a,
                    y0 + h,
                    b - 2 * a,
                    -1,
                    f" "
                )
                self.form3.set_line_width(0.05)
                self.form3.line(x0 + l + 16 + b / 2, y0 + h + 8, x0 + l + 16 + b / 2, y0 + h + 13)
                self.form3.line(x0 + l + 16 + b / 2, y0 + h + 13, x0 + l + 16 + b / 2 + 15, y0 + h + 13)
                self.form3.text(
                    x0 + l + 16 + b / 2 + 1,
                    y0 + h + 12.5,
                    f"{self._result_dict['1'][0] - 1}x"
                    f"{int(round((b - 2 * a) * self.scale / (self._result_dict['1'][0] - 1), 0))}="
                    f"{int(round((b - 2 * a) * self.scale, 0))}")
            else:
                self._dim_h(
                    x0 + l + 16 + a,
                    y0 + h,
                    b - 2 * a,
                    -1,
                    f"{int(round((b - 2 * a) * self.scale / (self._result_dict['1'][0] - 1), 0))}"
                )
            self._dim_h(x0 + l + 16 - a + b, y0 + h, a, 3.5)
            self._dim_v(x0 + l + 16, y0, a, 3)
            self._dim_v(x0 + l + 16, y0 + a, h - 2 * a)
            self._dim_v(x0 + l + 16, y0 - a + h, a, -3)
        else:
            self._dim_h(x0 + l + 30, y0 + h, a, -3)
            if self._result_dict['1'][0] > 2:
                self._dim_h(
                    x0 + l + 30 + a,
                    y0 + h,
                    b - 2 * a,
                    -1,
                    " "  #f"{self._result_dict['1'][0] - 1}x{int(round((b - 2 * a) * self.scale / (self._result_dict['1'][0] - 1), 0))}"
                )
                self.form3.set_line_width(0.05)
                self.form3.line(x0 + l + 30 + b / 2, y0 + h + 8, x0 + l + 30 + b / 2, y0 + h + 13)
                self.form3.line(x0 + l + 30 + b / 2, y0 + h + 13, x0 + l + 30 + b / 2 + 15, y0 + h + 13)
                self.form3.text(
                    x0 + l + 30 + b / 2 + 1,
                    y0 + h + 12.5,
                    f"{self._result_dict['1'][0] - 1}x"
                    f"{int(round((b - 2 * a) * self.scale / (self._result_dict['1'][0] - 1), 0))}="
                    f"{int(round((b - 2 * a) * self.scale, 0))}")
            else:
                self._dim_h(
                    x0 + l + 30 + a,
                    y0 + h,
                    b - 2 * a,
                    0,
                    f"{int(round((b - 2 * a) * self.scale / (self._result_dict['1'][0] - 1), 0))}"
                )
            self._dim_h(x0 + l + 30 - a + b, y0 + h, a, 3.5)
            self._dim_v(x0 + l + 30, y0, a, 3)
            self._dim_v(x0 + l + 30, y0 + a, h - 2 * a)
            self._dim_v(x0 + l + 30, y0 - a + h, a, -3)
        self.form3.set_line_width(0.05)
        self.form3.set_font("iso", "", 11)
        self.form3.line(x0 + l / 2 + 5, y0 + a, x0 + l / 2 + 5, y0 + a + 5)
        self.form3.line(x0 + l / 2 + 5, y0 + a + 5, x0 + l / 2 + 8, y0 + a + 5)
        self.form3.text(x0 + l / 2 + 6, y0 + a + 4.5, "2")
        self.form3.line(x0 + l / 2 - 5, y0 + h - a, x0 + l / 2 - 5, y0 + h - a - 5)
        self.form3.line(x0 + l / 2 - 5, y0 + h - a - 5, x0 + l / 2 - 2, y0 + h - a - 5)
        self.form3.text(x0 + l / 2 - 4, y0 + h - a - 5.5, "1")
        self.form3.line(x0 + 80 / self.scale, y0 + h / 2, x0 + 80 / self.scale + 8, y0 + h / 2)
        self.form3.text(x0 + 80 / self.scale + 6, y0 + h / 2 - 0.5, "3")
        self.form3.line(
            x0 + (80 + pos3_data[1] * 1000) / self.scale,
            y0 + h / 2,
            x0 + (80 + pos3_data[1] * 1000) / self.scale - 8,
            y0 + h / 2
        )
        self.form3.text(x0 + (80 + pos3_data[1] * 1000) / self.scale - 7, y0 + h / 2 - 0.5, "3")
        self.form3.line(
            x0 + (80 + pos3_data[1] * 1000) / self.scale + mid_dist,
            y0 + h / 2,
            x0 + (80 + pos3_data[1] * 1000) / self.scale + mid_dist + 8,
            y0 + h / 2
        )
        self.form3.text(x0 + (80 + pos3_data[1] * 1000) / self.scale + mid_dist + 6, y0 + h / 2 - 0.5, "3")
        self.form3.line(
            x0 + (80 + pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + mid_dist,
            y0 + h / 2,
            x0 + (80 + pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + mid_dist - 8,
            y0 + h / 2
        )
        self.form3.text(x0 + (80 + pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + mid_dist -7, y0 + h / 2 - 0.5, "3")
        self.form3.line(
            x0 + (80 + pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + 2 * mid_dist,
            y0 + h / 2,
            x0 + (80 + pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + 2 * mid_dist + 8,
            y0 + h / 2
        )
        self.form3.text(x0 + (80 + pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + 2 * mid_dist + 6, y0 + h / 2 - 0.5, "3")
        self.form3.line(
            x0 + (80 + 2 * pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + 2 * mid_dist,
            y0 + h / 2,
            x0 + (80 + 2 * pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + 2 * mid_dist - 8,
            y0 + h / 2
        )
        self.form3.text(x0 + (80 + 2 * pos3_data[1] * 1000 + pos3_data[3] * 1000) / self.scale + 2 * mid_dist - 7, y0 + h / 2 - 0.5, "3")
        if l > 250:
            for i in range(self._result_dict["1"][0]):
                self.form3.line(
                    x0 + l + 16 + a + s * i,
                    y0 + h - a,
                    x0 + l + 16 + a + 2,
                    y0 + h - a - 5
                )
            self.form3.line(
                x0 + l + 16 + a + 2,
                y0 + h - a - 5,
                x0 + l + 16 + a + 5,
                y0 + h - a - 5
            )
            self.form3.text(x0 + l + 16 + a + 3, y0 + h - a - 5.5, "1")
            self.form3.line(
                x0 + l + 16 + a - diam_pos2 / 2,
                y0 + a,
                x0 + l + 16 + a - diam_pos2 / 2 - 2,
                y0 + a - 5
            )
            self.form3.line(
                x0 + l + 16 + a - diam_pos2 / 2 - 2,
                y0 + a - 5,
                x0 + l + 16 + a - diam_pos2 / 2 - 5,
                y0 + a - 5
            )
            self.form3.text(x0 + l + 16 + a - diam_pos2 / 2 - 4, y0 + a - 5.5, "2")
            self.form3.line(
                x0 + l + 16 - a + b - diam_pos2 / 2 + diam_pos1 / 2,
                y0 + a,
                x0 + l + 16 - a + b - diam_pos2 / 2 + diam_pos1 / 2 + 2,
                y0 + a - 5
            )
            self.form3.line(
                x0 + l + 16 - a + b - diam_pos2 / 2 + diam_pos1 / 2 + 2,
                y0 + a - 5,
                x0 + l + 16 - a + b - diam_pos2 / 2 + diam_pos1 / 2 + 5,
                y0 + a - 5
            )
            self.form3.text(x0 + l + 16 - a + b - diam_pos2 / 2 + diam_pos1 / 2 + 3, y0 + a - 5.5, "2")
            self.form3.line(
                x0 + l + 16 + a - (diam_pos3 / 2 + diam_pos1 / 2),
                y0 + h / 2,
                x0 + l + 16 + a - (diam_pos3 / 2 + diam_pos1 / 2) - 6,
                y0 + h / 2
            )
            self.form3.text(x0 + l + 16 + a - (diam_pos3 / 2 + diam_pos1 / 2) - 5, y0 + h / 2 - 0.5, "3")
            self.form3.line(
                x0 + l + 16 - a + (diam_pos3 / 2 + diam_pos1 / 2) + b,
                y0 + h / 2,
                x0 + l + 16 - a + (diam_pos3 / 2 + diam_pos1 / 2) + b + 8,
                y0 + h / 2
            )
            self.form3.text(x0 + l + 16 - a + (diam_pos3 + diam_pos1) / 2 + b + 6, y0 + h / 2 - 0.5, "3")
            self.form3.line(
                x0 + l + 16 + b / 2,
                y0 + a - (diam_pos4 + diam_pos2) / 2,
                x0 + l + 16 + b / 2 - 2,
                y0 + a - (diam_pos4 + diam_pos2) / 2 - 5
            )
            self.form3.line(x0 + l + 16 + b / 2 - 2, y0 + a - (diam_pos4 + diam_pos2) / 2 - 5, x0 + l + 16 + b / 2 + 1, y0 + a - (diam_pos4 + diam_pos2) / 2 - 5)
            self.form3.text(x0 + l + 16 + b / 2 - 1, y0 + a - (diam_pos4 + diam_pos2) / 2 - 5.5, "4")
            self.form3.line(
                x0 + l + 16 + 3,
                y0 + h - a + (diam_pos4 + diam_pos1) / 2,
                x0 + l + 16 - 2,
                y0 + h - a + (diam_pos4 + diam_pos1) / 2 + 5
            )
            self.form3.line(
                x0 + l + 16 - 2,
                y0 + h - a + (diam_pos4 + diam_pos1) / 2 + 5,
                x0 + l + 16 - 5,
                y0 + h - a + (diam_pos4 + diam_pos1) / 2 + 5
            )
            self.form3.text(x0 + l + 16 - 4, y0 + h - a + (diam_pos4 + diam_pos1) / 2 + 4.5, "4")
        else:
            for i in range(self._result_dict["1"][0]):
                self.form3.line(
                    x0 + l + 30 + a + s * i,
                    y0 + h - a,
                    x0 + l + 30 + a + 2,
                    y0 + h - a - 5
                )
            self.form3.line(
                x0 + l + 30 + a + 2,
                y0 + h - a - 5,
                x0 + l + 30 + a + 5,
                y0 + h - a - 5
            )
            self.form3.text(x0 + l + 30 + a + 3, y0 + h - a - 5.5, "1")
            self.form3.line(
                x0 + l + 30 + a - diam_pos2 / 2,
                y0 + a,
                x0 + l + 30 + a - diam_pos2 / 2 - 2,
                y0 + a - 5
            )
            self.form3.line(
                x0 + l + 30 + a - diam_pos2 / 2 - 2,
                y0 + a - 5,
                x0 + l + 30 + a - diam_pos2 / 2 - 5,
                y0 + a - 5
            )
            self.form3.text(x0 + l + 30 + a - diam_pos2 / 2 - 4, y0 + a - 5.5, "2")
            self.form3.line(
                x0 + l + 30 - a + b - diam_pos2 / 2 + diam_pos1 / 2,
                y0 + a,
                x0 + l + 30 - a + b - diam_pos2 / 2 + diam_pos1 / 2 + 2,
                y0 + a - 5
            )
            self.form3.line(
                x0 + l + 30 - a + b - diam_pos2 / 2 + diam_pos1 / 2 + 2,
                y0 + a - 5,
                x0 + l + 30 - a + b - diam_pos2 / 2 + diam_pos1 / 2 + 5,
                y0 + a - 5
            )
            self.form3.text(x0 + l + 30 - a + b - diam_pos2 / 2 + diam_pos1 / 2 + 3, y0 + a - 5.5, "2")
            self.form3.line(
                x0 + l + 30 + a - (diam_pos3 / 2 + diam_pos1 / 2),
                y0 + h / 2,
                x0 + l + 30 + a - (diam_pos3 / 2 + diam_pos1 / 2) - 6,
                y0 + h / 2
            )
            self.form3.text(x0 + l + 30 + a - (diam_pos3 / 2 + diam_pos1 / 2) - 5, y0 + h / 2 - 0.5, "3")
            self.form3.line(
                x0 + l + 30 - a + (diam_pos3 / 2 + diam_pos1 / 2) + b,
                y0 + h / 2,
                x0 + l + 30 - a + (diam_pos3 / 2 + diam_pos1 / 2) + b + 8,
                y0 + h / 2
            )
            self.form3.text(x0 + l + 30 - a + (diam_pos3 + diam_pos1) / 2 + b + 6, y0 + h / 2 - 0.5, "3")
            self.form3.line(
                x0 + l + 30 + b / 2,
                y0 + a - (diam_pos4 + diam_pos2) / 2,
                x0 + l + 30 + b / 2 - 2,
                y0 + a - (diam_pos4 + diam_pos2) / 2 - 5
            )
            self.form3.line(x0 + l + 30 + b / 2 - 2, y0 + a - (diam_pos4 + diam_pos2) / 2 - 5, x0 + l + 30 + b / 2 + 1, y0 + a - (diam_pos4 + diam_pos2) / 2 - 5)
            self.form3.text(x0 + l + 30 + b / 2 - 1, y0 + a - (diam_pos4 + diam_pos2) / 2 - 5.5, "4")
            self.form3.line(
                x0 + l + 30 + 3,
                y0 + h - a + (diam_pos4 + diam_pos1) / 2,
                x0 + l + 30 - 2,
                y0 + h - a + (diam_pos4 + diam_pos1) / 2 + 5
            )
            self.form3.line(
                x0 + l + 30 - 2,
                y0 + h - a + (diam_pos4 + diam_pos1) / 2 + 5,
                x0 + l + 30 - 5,
                y0 + h - a + (diam_pos4 + diam_pos1) / 2 + 5
            )
            self.form3.text(x0 + l + 30 - 4, y0 + h - a + (diam_pos4 + diam_pos1) / 2 + 4.5, "4")

    def _dim_h(self, x, y, l, x_text=0.0, text=""):
        x0 = x
        y0 = y
        x_t = x0 + x_text + l / 2 - 2
        if len(text) == 0:
            dim_text = str(int(l * self.scale))
        else:
            dim_text = text
        self.form3.set_line_width(0.05)
        self.form3.line(x0 - 2, y0 + 8, x0 + l + 2, y0 + 8)
        self.form3.line(x0, y0 + 2, x0, y0 + 10)
        self.form3.line(x0 + l, y0 + 2, x0 + l, y0 + 10)
        self.form3.set_line_width(0.5)
        self.form3.line(x0 - 0.9, y0 + 8.9, x0 + 0.9, y0 + 7.1)
        self.form3.line(x0 + l - 0.9, y0 + 8.9, x0 + l + 0.9, y0 + 7.1)
        self.form3.set_font("iso", "", 11)
        self.form3.text(x_t, y0 + 7.5, dim_text)

    def _dim_v(self, x, y, l, x_text=0.0, text=""):
        x0 = x
        y0 = y
        x_t = x0 + x_text - l / 2 - 2
        self.form3.rotate(90, x0, y0)
        if len(text) == 0:
            dim_text = str(int(l * self.scale))
        else:
            dim_text = text
        self.form3.set_line_width(0.05)
        self.form3.line(x0 + 2, y0 - 8, x0 - l - 2, y0 - 8)
        self.form3.line(x0, y0 - 2, x0, y0 - 10)
        self.form3.line(x0 - l, y0 - 2, x0 - l, y0 - 10)
        self.form3.set_line_width(0.5)
        self.form3.line(x0 + 0.9, y0 - 8.9, x0 - 0.9, y0 - 7.1)
        self.form3.line(x0 - l + 0.9, y0 - 8.9, x0 - l - 0.9, y0 - 7.1)
        self.form3.set_font("iso", "", 11)
        self.form3.text(x_t, y0 - 8.5, dim_text)
        self.form3.rotate(0)

    def _draw_form_3(self, y=0):
        y0 = y
        self.form3.set_line_width(0.5)
        self.form3.rect(20, y0 + 10, 390, y0 + 277)
        self.form3.rect(230, y0 + 232, 180, y0 + 55)
        self.form3.line(240, y0 + 232, 240, y0 + 257)
        self.form3.line(250, y0 + 232, 250, y0 + 287)
        self.form3.line(260, y0 + 232, 260, y0 + 257)
        self.form3.line(270, y0 + 232, 270, y0 + 287)
        self.form3.line(285, y0 + 232, 285, y0 + 287)
        self.form3.line(295, y0 + 232, 295, y0 + 287)
        self.form3.line(365, y0 + 257, 365, y0 + 287)
        self.form3.line(380, y0 + 257, 380, y0 + 272)
        self.form3.line(395, y0 + 257, 395, y0 + 272)
        self.form3.line(295, y0 + 242, 410, y0 + 242)
        self.form3.line(230, y0 + 252, 295, y0 + 252)
        self.form3.line(230, y0 + 257, 410, y0 + 257)
        self.form3.line(365, y0 + 262, 410, y0 + 262)
        self.form3.line(295, y0 + 272, 410, y0 + 272)
        self.form3.set_line_width(0.05)
        self.form3.line(230, y0 + 237, 295, y0 + 237)
        self.form3.line(230, y0 + 242, 295, y0 + 242)
        self.form3.line(230, y0 + 247, 295, y0 + 247)
        self.form3.line(230, y0 + 262, 295, y0 + 262)
        self.form3.line(230, y0 + 267, 295, y0 + 267)
        self.form3.line(230, y0 + 272, 295, y0 + 272)
        self.form3.line(230, y0 + 277, 295, y0 + 277)
        self.form3.line(230, y0 + 282, 295, y0 + 282)
        self.form3.set_font("iso", "", 11)
        self.form3.text(233, y0 + 255.75, "Зм.")
        self.form3.text(240.75, y0 + 255.75, "Кільк.")
        self.form3.text(252, y0 + 255.75, "Арк.")
        self.form3.text(260.5, y0 + 255.75, "№док.")
        self.form3.text(273, y0 + 255.75, "Підпис")
        self.form3.text(286, y0 + 255.75, "Дата")
        self.form3.text(231, y0 + 260.75, "Виконав")
        self.form3.text(251, y0 + 260.75, "Бережний")
        self.form3.text(367, y0 + 260.75, "Стадія")
        self.form3.text(382.5, y0 + 260.75, "Аркуш")
        self.form3.text(396.25, y0 + 260.75, "Аркушів")
        self.form3.text(296, y0 + 275.75, self.title1)
        self.form3.text(296, y0 + 280.75, self.title2)
        self.form3.text(296, y0 + 285.75, self.title3)
        self.form3.set_font("iso", "", 14)
        self.form3.text(370, y0 + 268.75, "ЕП")
        self.form3.text(386.5, y0 + 268.75, "1")
        self.form3.text(401.5, y0 + 268.75, "1")
        self.form3.text(336, y0 + 238.25, str(datetime.utcnow().strftime("%Y—%m—%d %H:%M")))
        self.form3.image("static/images/logo_dark.png", 366.25, y0 + 273.25, 42.5, 12.5)
        
    def _draw_specification(self, result_dict: dict, x=230, y=30, title: str = "Специфікація"):
        x0 = x
        y0 = y
        self.form3.set_line_width(0.5)
        self.form3.line(x0 + 0, y0 + 0, x0 + 180, y0 + 0)
        self.form3.line(x0 + 0, y0 + 15, x0 + 180, y0 + 15)
        self.form3.line(x0 + 0, y0 + 0, x0 + 0, y0 + 15 + self.count_of_lines * 8)
        self.form3.line(x0 + 15, y0 + 0, x0 + 15, y0 + 15 + self.count_of_lines * 8)
        self.form3.line(x0 + 75, y0 + 0, x0 + 75, y0 + 15 + self.count_of_lines * 8)
        self.form3.line(x0 + 135, y0 + 0, x0 + 135, y0 + 15 + self.count_of_lines * 8)
        self.form3.line(x0 + 145, y0 + 0, x0 + 145, y0 + 15 + self.count_of_lines * 8)
        self.form3.line(x0 + 160, y0 + 0, x0 + 160, y0 + 15 + self.count_of_lines * 8)
        self.form3.line(x0 + 180, y0 + 0, x0 + 180, y0 + 15 + self.count_of_lines * 8)
        y = y0 + 23
        self.form3.set_line_width(0.05)
        i = 0
        while i < self.count_of_lines:
            self.form3.set_font("iso", "", 11)
            self.form3.line(x0 + 0, y, x0 + 180, y)
            i += 1
            y += 8
        self.form3.set_font("iso", "", 14)
        self.form3.text(x0 + 85, y0 - 5, title)
        self.form3.set_font("iso", "", 11)
        self.form3.text(x0 + 5, y0 + 9.25, "Поз.")
        self.form3.text(x0 + 35, y0 + 9.25, "Позначення")
        self.form3.text(x0 + 94, y0 + 9.25, "Найменування")
        self.form3.text(x0 + 135.5, y0 + 9.25, "Кільк.")
        self.form3.text(x0 + 145.3, y0 + 7.25, "Маса од.,")
        self.form3.text(x0 + 151, y0 + 11, "кг")
        self.form3.text(x0 + 163, y0 + 9.25, "Примітка")
        self.form3.set_font("iso", "U", 11)
        self.form3.text(x0 + 88, y0 + 20.25 + 0 * 8, "Залізобетонні вироби")
        self.form3.text(x0 + 90, y0 + 20.25 + 2 * 8, "Арматурні вироби")
        self.form3.text(x0 + 96, y0 + 20.25 + 7 * 8, "Матеріали")
        self.form3.set_font("iso", "", 11)
        mark = []
        for key in result_dict.keys():
            mark.append(key)
        text0 = f"Залізобетонна балка {mark[0]}"
        mass = (int(self._result_dict[mark[0]][2]) + 500) * int(self._result_dict[mark[0]][3]) * int(self._result_dict[mark[0]][4]) * 2500 / 1e9
        self.form3.text(x0 + 4, y0 + 20.25 + 1 * 8, mark[0])
        self.form3.text(x0 + 76, y0 + 20.25 + 1 * 8, text0)
        self.form3.text(x0 + 139, y0 + 20.25 + 1 * 8, '1')
        self.form3.text(x0 + 148.5, y0 + 20.25 + 1 * 8, str(mass))
        i = 3
        for p in mark[1:]:
            diameter = self._result_dict[p][1]
            cl = self._result_dict[p][2]
            length = int(self._result_dict[p][3] * 1000)
            quantity = self._result_dict[p][0]
            text1 = f"∅{diameter}{cl}; L={length}"
            mass = round(pi * (diameter / 1000) ** 2 / 4 * 7850 * length / 1000, 3)
            total_mass = f"{round(mass * quantity, 3)} кг"
            self.form3.text(x0 + 6.5, y0 + 20.25 + i * 8, p)
            self.form3.text(x0 + 16, y0 + 20.25 + i * 8, "ДСТУ 3760:2019")
            self.form3.text(x0 + 76, y0 + 20.25 + i * 8, text1)
            self.form3.text(x0 + 139, y0 + 20.25 + i * 8, f"{quantity}")
            self.form3.text(x0 + 148.5, y0 + 20.25 + i * 8, f"{mass}")
            self.form3.text(x0 + 162.5, y0 + 20.25 + i * 8, f"{total_mass}")
            i += 1
        volume = (int(self._result_dict[mark[0]][2]) + 500) * int(self._result_dict[mark[0]][3]) * int(self._result_dict[mark[0]][4]) / 1e9
        self.form3.text(x0 + 16, y0 + 20.25 + 8 * 8, "ДСТУ Б В.2.7-176:2008")
        self.form3.text(x0 + 76, y0 + 20.25 + 8 * 8, "Бетон класу С20/25")
        self.form3.text(x0 + 162.5, y0 + 20.25 + 8 * 8, f"{volume}")
        self.form3.text(x0 + 171, y0 + 20.25 + 8 * 8, f"м")
        self.form3.set_font("iso", "", 7)
        self.form3.text(x0 + 173, y0 + 19.25 + 8 * 8, "3")
Exemplo n.º 48
0
class Report:
    def __init__(self, data: DataSet):
        self.output_path = os.path.join(data.data_path, "stats")
        self.dataset_name = os.path.basename(data.data_path)

        self.mapi_light_light_green = [210, 245, 226]
        self.mapi_light_green = [5, 203, 99]
        self.mapi_light_grey = [218, 222, 228]
        self.mapi_dark_grey = [99, 115, 129]

        self.pdf = FPDF("P", "mm", "A4")
        self.pdf.add_page()

        self.title_size = 20
        self.h1 = 16
        self.h2 = 13
        self.h3 = 10
        self.text = 10
        self.small_text = 8
        self.margin = 10
        self.cell_height = 7
        self.total_size = 190

        self.stats = self._read_stats_file("stats.json")

    def save_report(self, filename):
        self.pdf.output(os.path.join(self.output_path, filename), "F")

    def _make_table(self, columns_names, rows, row_header=False):
        self.pdf.set_font("Helvetica", "", self.h3)
        self.pdf.set_line_width(0.3)

        columns_sizes = [int(self.total_size / len(rows[0]))] * len(rows[0])

        if columns_names:
            self.pdf.set_draw_color(*self.mapi_light_grey)
            self.pdf.set_fill_color(*self.mapi_light_grey)
            for col, size in zip(columns_names, columns_sizes):
                self.pdf.rect(
                    self.pdf.get_x(),
                    self.pdf.get_y(),
                    size,
                    self.cell_height,
                    style="FD",
                )
                self.pdf.set_text_color(*self.mapi_dark_grey)
                self.pdf.cell(size, self.cell_height, col, align="L")
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.cell_height)

        self.pdf.set_draw_color(*self.mapi_light_grey)
        self.pdf.set_fill_color(*self.mapi_light_light_green)

        for row in rows:
            for i, (col, size) in enumerate(zip(row, columns_sizes)):
                if i == 0 and row_header:
                    self.pdf.set_draw_color(*self.mapi_light_grey)
                    self.pdf.set_fill_color(*self.mapi_light_grey)
                self.pdf.rect(
                    self.pdf.get_x(),
                    self.pdf.get_y(),
                    size,
                    self.cell_height,
                    style="FD",
                )
                self.pdf.set_text_color(*self.mapi_dark_grey)
                if i == 0 and row_header:
                    self.pdf.set_draw_color(*self.mapi_light_grey)
                    self.pdf.set_fill_color(*self.mapi_light_light_green)
                self.pdf.cell(size, self.cell_height, col, align="L")
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.cell_height)

    def _read_stats_file(self, filename):
        file_path = os.path.join(self.output_path, filename)
        with io.open_rt(file_path) as fin:
            return io.json_load(fin)

    def _make_section(self, title):
        self.pdf.set_font("Helvetica", "B", self.h1)
        self.pdf.set_text_color(*self.mapi_dark_grey)
        self.pdf.cell(0, self.margin, title, align="L")
        self.pdf.set_xy(self.margin, self.pdf.get_y() + 1.5 * self.margin)

    def _make_subsection(self, title):
        self.pdf.set_xy(self.margin, self.pdf.get_y() - 0.5 * self.margin)
        self.pdf.set_font("Helvetica", "B", self.h2)
        self.pdf.set_text_color(*self.mapi_dark_grey)
        self.pdf.cell(0, self.margin, title, align="L")
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def _make_centered_image(self, image_path, desired_height):
        width, height = PIL.Image.open(image_path).size
        resized_width = width * desired_height / height
        if resized_width > self.total_size:
            resized_width = self.total_size
            desired_height = height * resized_width / width

        self.pdf.image(
            image_path,
            self.pdf.get_x() + self.total_size / 2 - resized_width / 2,
            self.pdf.get_y(),
            h=desired_height,
        )
        self.pdf.set_xy(self.margin,
                        self.pdf.get_y() + desired_height + self.margin)

    def make_title(self):
        # title
        self.pdf.set_font("Helvetica", "B", self.title_size)
        self.pdf.set_text_color(*self.mapi_light_green)
        self.pdf.cell(0, self.margin, "OpenSfM Quality Report", align="C")
        self.pdf.set_xy(self.margin, self.title_size)

        # version number
        try:
            out, _ = subprocess.Popen(
                ["git", "describe", "--tags"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            ).communicate()
            version = out.strip().decode()
        except BaseException as e:
            logger.warning(
                f"Exception thrwon while extracting 'git' version, {e}")
            version = ""

        # indicate we don't know the version
        version = "unknown" if version == "" else version

        self.pdf.set_font("Helvetica", "", self.small_text)
        self.pdf.set_text_color(*self.mapi_dark_grey)
        self.pdf.cell(0,
                      self.margin,
                      f"Processed with OpenSfM version {version}",
                      align="R")
        self.pdf.set_xy(self.margin, self.pdf.get_y() + 2 * self.margin)

    def make_dataset_summary(self):
        self._make_section("Dataset Summary")

        rows = [
            ["Dataset", self.dataset_name],
            ["Date", self.stats["processing_statistics"]["date"]],
            [
                "Area Covered",
                f"{self.stats['processing_statistics']['area']/1e6:.6f} km²",
            ],
            [
                "Processing Time",
                f"{self.stats['processing_statistics']['steps_times']['Total Time']:.2f} seconds",
            ],
        ]
        self._make_table(None, rows, True)
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def _has_meaningful_gcp(self):
        return (self.stats["reconstruction_statistics"]["has_gcp"]
                and "average_error" in self.stats["gcp_errors"])

    def make_processing_summary(self):
        self._make_section("Processing Summary")

        rec_shots, init_shots = (
            self.stats["reconstruction_statistics"]
            ["reconstructed_shots_count"],
            self.stats["reconstruction_statistics"]["initial_shots_count"],
        )
        rec_points, init_points = (
            self.stats["reconstruction_statistics"]
            ["reconstructed_points_count"],
            self.stats["reconstruction_statistics"]["initial_points_count"],
        )

        geo_string = []
        if self.stats["reconstruction_statistics"]["has_gps"]:
            geo_string.append("GPS")
        if self._has_meaningful_gcp():
            geo_string.append("GCP")

        ratio_shots = rec_shots / init_shots * 100 if init_shots > 0 else -1
        rows = [
            [
                "Reconstructed Images",
                f"{rec_shots} over {init_shots} shots ({ratio_shots:.1f}%)",
            ],
            [
                "Reconstructed Points",
                f"{rec_points} over {init_points} points ({rec_points/init_points*100:.1f}%)",
            ],
            [
                "Reconstructed Components",
                f"{self.stats['reconstruction_statistics']['components']} component",
            ],
            [
                "Detected Features",
                f"{self.stats['features_statistics']['detected_features']['median']} features",
            ],
            [
                "Reconstructed Features",
                f"{self.stats['features_statistics']['reconstructed_features']['median']} features",
            ],
            ["Geographic Reference", " and ".join(geo_string)],
        ]

        row_gps_gcp = [" / ".join(geo_string) + " errors"]
        geo_errors = []
        if self.stats["reconstruction_statistics"]["has_gps"]:
            geo_errors.append(
                f"{self.stats['gps_errors']['average_error']:.2f}")
        if self._has_meaningful_gcp():
            geo_errors.append(
                f"{self.stats['gcp_errors']['average_error']:.2f}")
        row_gps_gcp.append(" / ".join(geo_errors) + " meters")
        rows.append(row_gps_gcp)

        self._make_table(None, rows, True)
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

        topview_height = 130
        topview_grids = [
            f for f in os.listdir(self.output_path) if f.startswith("topview")
        ]
        self._make_centered_image(
            os.path.join(self.output_path, topview_grids[0]), topview_height)

        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def make_processing_time_details(self):
        self._make_section("Processing Time Details")

        columns_names = list(
            self.stats["processing_statistics"]["steps_times"].keys())
        formatted_floats = []
        for v in self.stats["processing_statistics"]["steps_times"].values():
            formatted_floats.append(f"{v:.2f} sec.")
        rows = [formatted_floats]
        self._make_table(columns_names, rows)
        self.pdf.set_xy(self.margin, self.pdf.get_y() + 2 * self.margin)

    def make_gps_details(self):
        self._make_section("GPS/GCP Errors Details")

        # GPS
        for error_type in ["gps", "gcp"]:
            rows = []
            columns_names = [error_type.upper(), "Mean", "Sigma", "RMS Error"]
            if "average_error" not in self.stats[error_type + "_errors"]:
                continue
            for comp in ["x", "y", "z"]:
                row = [comp.upper() + " Error (meters)"]
                row.append(
                    f"{self.stats[error_type + '_errors']['mean'][comp]:.3f}")
                row.append(
                    f"{self.stats[error_type +'_errors']['std'][comp]:.3f}")
                row.append(
                    f"{self.stats[error_type +'_errors']['error'][comp]:.3f}")
                rows.append(row)

            rows.append([
                "Total",
                "",
                "",
                f"{self.stats[error_type +'_errors']['average_error']:.3f}",
            ])
            self._make_table(columns_names, rows)
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

    def make_features_details(self):
        self._make_section("Features Details")

        heatmap_height = 60
        heatmaps = [
            f for f in os.listdir(self.output_path) if f.startswith("heatmap")
        ]
        self._make_centered_image(os.path.join(self.output_path, heatmaps[0]),
                                  heatmap_height)
        if len(heatmaps) > 1:
            logger.warning("Please implement multi-model display")

        columns_names = ["", "Min.", "Max.", "Mean", "Median"]
        rows = []
        for comp in ["detected_features", "reconstructed_features"]:
            row = [comp.replace("_", " ").replace("features", "").capitalize()]
            for t in columns_names[1:]:
                row.append(
                    f"{self.stats['features_statistics'][comp][t.replace('.', '').lower()]:.0f}"
                )
            rows.append(row)
        self._make_table(columns_names, rows)

        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def make_reconstruction_details(self):
        self._make_section("Reconstruction Details")

        rows = [
            [
                "Average Reprojection Error (normalized / pixels)",
                (f"{self.stats['reconstruction_statistics']['reprojection_error_normalized']:.2f} / "
                 f"{self.stats['reconstruction_statistics']['reprojection_error_pixels']:.2f}"
                 ),
            ],
            [
                "Average Track Length",
                f"{self.stats['reconstruction_statistics']['average_track_length']:.2f} images",
            ],
            [
                "Average Track Length (> 2)",
                f"{self.stats['reconstruction_statistics']['average_track_length_over_two']:.2f} images",
            ],
        ]
        self._make_table(None, rows, True)
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 1.5)

        residual_histogram_height = 60
        residual_histogram = [
            f for f in os.listdir(self.output_path)
            if f.startswith("residual_histogram")
        ]
        self._make_centered_image(
            os.path.join(self.output_path, residual_histogram[0]),
            residual_histogram_height,
        )
        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def make_camera_models_details(self):
        self._make_section("Camera Models Details")

        for camera, params in self.stats["camera_errors"].items():
            residual_grids = [
                f for f in os.listdir(self.output_path)
                if f.startswith("residuals_" + str(camera.replace("/", "_")))
            ]
            if not residual_grids:
                continue

            initial = params["initial_values"]
            optimized = params["optimized_values"]
            names = [""] + list(initial.keys())

            rows = []
            rows.append(["Initial"] + [f"{x:.4f}" for x in initial.values()])
            rows.append(["Optimized"] +
                        [f"{x:.4f}" for x in optimized.values()])

            self._make_subsection(camera)
            self._make_table(names, rows)
            self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin / 2)

            residual_grid_height = 100
            self._make_centered_image(
                os.path.join(self.output_path, residual_grids[0]),
                residual_grid_height)

    def make_tracks_details(self):
        self._make_section("Tracks Details")
        matchgraph_height = 80
        matchgraph = [
            f for f in os.listdir(self.output_path)
            if f.startswith("matchgraph")
        ]
        self._make_centered_image(
            os.path.join(self.output_path, matchgraph[0]), matchgraph_height)

        histogram = self.stats["reconstruction_statistics"][
            "histogram_track_length"]
        start_length, end_length = 2, 10
        row_length = ["Length"]
        for length, _ in sorted(histogram.items(), key=lambda x: int(x[0])):
            if int(length) < start_length or int(length) > end_length:
                continue
            row_length.append(length)
        row_count = ["Count"]
        for length, count in sorted(histogram.items(),
                                    key=lambda x: int(x[0])):
            if int(length) < start_length or int(length) > end_length:
                continue
            row_count.append(f"{count}")

        self._make_table(None, [row_length, row_count], True)

        self.pdf.set_xy(self.margin, self.pdf.get_y() + self.margin)

    def add_page_break(self):
        self.pdf.add_page("P")

    def generate_report(self):
        self.make_title()
        self.make_dataset_summary()
        self.make_processing_summary()
        self.add_page_break()

        self.make_features_details()
        self.make_reconstruction_details()
        self.add_page_break()

        self.make_tracks_details()
        self.make_camera_models_details()
        self.add_page_break()

        self.make_gps_details()
        self.make_processing_time_details()
Exemplo n.º 49
0
class Invoice:
    """ The model for the invoice resource """
    def __init__(self, data):
        """ Creates an invoice instance with the passed data and the FPDF library """
        self.pdf = FPDF()

        self.data = data
        self.pdf.set_title(f'{self.data["company_name"]} invoice')
        self.pdf.set_title('invoice')
        self.pdf.set_font('Arial', 'B', 8)

    def write_invoice_content(self, total, pages):
        """ The central function for writing invoice content based on invoice data in instance """
        all_products = self.data['products']

        if len(all_products) <= 10:
            last_page = True
            # 10 or less products posted to service, thus only one page required
            self.pdf.add_page()

            self.write_header()
            self.write_content(total, all_products, last_page)
        else:
            # more than 10 products posted to service, 2 or more pages required
            for i in range(pages):
                if i == pages - 1:  # if current page we're writing to is the last page, then set flag to true
                    last_page = True
                else:
                    last_page = False

                first_index = 0 + i * 10
                second_index = 10 + i * 10

                products = all_products[
                    first_index:
                    second_index]  # products on a given page will be a sublist of all products...
                # ...  based on page number so that a page always has 10 products
                self.pdf.add_page()

                self.write_header()
                self.write_content(total, products, last_page)

    def write_header(self):
        """ Draws the generic header content on the first page of the invoice """
        #image and title
        self.pdf.image('invoice_pic.png', 10, 8, 25, 25)
        self.pdf.set_font('Arial', size=22)
        self.write_text(34, 25, 'Generic Invoice Service')

        #invoice
        self.pdf.set_font('Arial', size=30)
        self.write_text(155, 30, 'Invoice')

        #date, invoice number, and period
        self.pdf.set_font('Arial', size=12)
        self.write_text(155, 38, f'Date: {self.data["date"]}')
        self.write_text(155, 44,
                        f'Invoice Number: {self.data["invoice_number"]}')
        self.write_text(155, 50, f'Period: {self.data["period"]}')

        #to and from
        self.write_text(35, 54, f'From: {self.data["company_name"]}')
        self.write_text(35, 60, f'To: {self.data["invoice_to"]}')

    def write_content(self, total, products, last_page):
        """ Draws the cells for products and the writes the products to the pages """
        #draw cells
        self.pdf.set_line_width(0.2)
        self.pdf.set_xy(15, 70)
        self.pdf.cell(180, 190, '', border=1)
        self.pdf.set_xy(15, 70)
        self.pdf.cell(125, 190, '', border=1)
        self.pdf.set_xy(110, 70)
        self.pdf.cell(30, 190, '', border=1)
        self.pdf.set_xy(140, 70)
        self.pdf.cell(30, 190, '', border=1)

        #write titles and underline (line width 0.5mm, then reset to default)
        self.pdf.set_font('Arial', 'B', 12)
        self.write_text(18, 75, 'Product name:')
        self.write_text(112, 75, 'SKU:')
        self.write_text(142, 75, 'Quantity:')
        self.write_text(172, 75, 'Price:')
        self.pdf.set_line_width(0.3)
        self.pdf.line(15, 76.5, 195, 76.5)
        self.pdf.set_line_width(0.2)

        self.pdf.set_font('Arial', size=10)
        y = 81

        for product in products:
            title = product['title']
            quantity = product['quantity']
            price = product['price']
            sku = product['sku']

            if len(title) > 30:
                title = title[
                    0:
                    26] + '...'  # truncating title and suffixing with dots, if product title longer than 30 chars

            self.write_text(18, y, title)
            self.write_text(112, y, str(sku))
            self.write_text(142, y, str(quantity))
            self.write_text(172, y, str(price))

            y += 5

        if last_page:  #if the the page we're currently writing to is the last page, then..
            #draw total amount cell
            self.pdf.set_xy(140, 260)
            self.pdf.cell(55, 15, '', border=1)

            #draw total amount value
            self.pdf.set_font('Arial', 'B', 22)
            self.write_text(145, 270, '$' + str(total) + ' due')

    def write_notes(self):
        """ Creates the last page and adds  """
        self.pdf.add_page()

        self.pdf.set_font('Arial', 'B', 14)
        self.write_text(10, 20, 'Notes:')
        self.pdf.set_line_width(0.5)
        self.pdf.line(10, 21, 25, 21)

        self.pdf.set_font('Arial', size=8)
        self.pdf.set_xy(10, 25)
        self.pdf.write(5, self.data['notes'])

    def write_text(self, x, y, text):
        """ A function to write text to some coordinates on a page of the invoice """
        self.pdf.text(x, y, text)

    def output(self, filename):
        """ A function to save the file locally with the passed filename """
        self.pdf.output(filename, 'F')
Exemplo n.º 50
0
class YaFTe():
    def __init__(self, filename):

        with open(filename, 'r') as f:
            self.tconfig = yaml.load(f.read())
        self.tconfig.pop('templates', {})
        self.elements = {}
        self.pdf = FPDF(**self.get_fpdfoptions(), unit="mm")
        self.add_fonts()
        self.set_docoptions()
        self.prepare_elements()
        self.pdf.set_auto_page_break(False)

    def get_fpdfoptions(self):
        options = {}
        try:
            options['format'] = self.tconfig['docoptions'].pop('format', 'A4')
            options['orientation'] = self.tconfig['docoptions'].pop(
                'orientation', 'portrait')
        except:
            MissingParameterError('docoptions')
        return options

    def add_fonts(self):
        for name, spec in self.tconfig['docoptions'].pop('fonts', {}).items():
            self.pdf.add_font(name, **spec)

    def add_page(self, debug=False, **kwargs):
        self.pdf.add_page()
        for key, element in sorted(self.elements.items(),
                                   key=lambda x: x[1]['priority']):
            current_element = element.copy()
            if debug:
                current_element['text'] = key
                if current_element['type'] == 'image':
                    current_element['type'] = 'text'
            elif key in kwargs:
                if 'format' in current_element:
                    current_element['text'] = current_element['format'].format(
                        kwargs[key])
                else:
                    current_element['text'] = str(kwargs[key])
            self.add_to_page(current_element)
        pass

    def add_to_page(self, element):
        try:
            type = element.pop('type', 'unknown')
            getattr(self, 'element_{0}'.format(type))(**element)
        except Exception as e:
            print(e)
            pass

    def output(self, *args, **kwargs):
        return self.pdf.output(*args, **kwargs)

    def set_docoptions(self):
        for key, value in self.tconfig.pop('docoptions', {}).items():
            getattr(self.pdf, 'set_{0}'.format(key))(value)

    def prepare_elements(self):
        defaults = self.tconfig.pop('defaults', {})
        for key, telement in self.tconfig.items():
            elem = defaults.copy()
            elem.update(telement)
            try:

                def setreplace(dct, key, replace):
                    if not key in dct:
                        dct[key] = replace(dct)

            except KeyError as ke:
                raise MissingParameterError(key) from ke

            self.elements[key] = elem

    def __getitem__(self, name):
        if name in self.elements:
            return self.elements[name]['text']

    def __setitem__(self, name, value):
        if name in self.elements:
            self.elements[name]['text'] = value
        else:
            raise KeyError('{name} is no element'.format(name=name))

    def element_text(self,
                     x,
                     y,
                     w,
                     h,
                     text,
                     font,
                     size,
                     style='',
                     align='L',
                     foreground=None,
                     border=0,
                     bordercolor=0,
                     fill=False,
                     background=None,
                     multiline=False,
                     **kwargs):
        if background is not None:
            self.pdf.set_fill_color(*rgb(background))
        if foreground is not None:
            self.pdf.set_text_color(*rgb(foreground))
        if bordercolor is not None:
            self.pdf.set_draw_color(*rgb(bordercolor))
        self.pdf.set_font(font, style, size)
        self.pdf.set_xy(x, y)
        if not multiline in [1, True, 'true']:
            self.pdf.cell(w=w,
                          h=h,
                          txt=text,
                          border=border,
                          ln=0,
                          align=align,
                          fill=fill)
        else:
            self.pdf.multi_cell(w=w,
                                h=self.pdf.k * size / 10 * 1.2,
                                txt=text,
                                border=border,
                                align='J')

    def element_box(self,
                    x,
                    y,
                    w,
                    h,
                    border,
                    background=0,
                    bordercolor=0xFFFFFF,
                    style='D',
                    **kwargs):
        if background is not None:
            self.pdf.set_fill_color(*rgb(background))
        if bordercolor is not None:
            self.pdf.set_draw_color(*rgb(bordercolor))
        self.pdf.rect(x, y, w, h, style=style)
        pass

    def element_rect(self, **kwargs):
        self.rect(**kwargs, style='F')
        pass

    def element_image(self, x, y, w, h, text, link='', type='', **kwargs):
        self.pdf.image(text, x, y, w, h, type=type, link=link)
        pass

    def element_unknown(self, type, **kwargs):
        print('detected unknown type: {0}'.format(type))
        pass
Exemplo n.º 51
0
# PyFPDF documentation
# https://pyfpdf.readthedocs.io/en/latest/index.html

#################################################################
# First Page - Trying out the methods                           #
#################################################################

# Generate FPDF object and add page
# FPDF(orientation, unit, format)
pdf = FPDF("P", "mm", "A4")
pdf.add_page()

# fpdf.set_font(family, style = '', size = 0)
# Before writing text
pdf.set_font("Arial", "B", 16)

# fpdf.text(x: float, y: float, txt: str)
# Must specify `x,y`
"""
pdf.text(10,10,"Hello, World")
wi = pdf.get_string_width("Hello, World ")
pdf.text(10+wi,10,"Goodbye, World")
"""

# fpdf.cell(w, h = 0, txt = '', border = 0, ln = 0, align = '', fill = False, link = '')
# Rely on cursor for `x,y`
pdf.cell(0, 10, "Hello, World", 1, 1, "C")

pdf.set_font("Courier", "", 14)
pdf.cell(95, 10, "print('Hello, World')", 1, 0, "C")
Exemplo n.º 52
0
from fpdf import FPDF
# https://python-scripts.com/create-pdf-pyfpdf -- источник

pdf = FPDF(orientation='P', unit='mm', format='A4')
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Welcome to Python!", ln=1, align="C")
pdf.output("simple_demo.pdf")
Exemplo n.º 53
0
def print_results(analysed_models):

    create_images(analysed_models)

    # create individual results

    output_file = open("./Results/inidivudal_results.txt", 'w')
    output_file.write(
        "------------------------------Analysis results---------------------------------------"
        + "\n" + "\n")
    output_file.write(
        "############################################################################"
        + "\n")
    output_file.write("Individual Model Samples: " + "\n")
    output_file.write(
        "############################################################################"
        + "\n" + "\n")

    for model in analysed_models:
        output_file.write("\t" + "metadata:" + "\n")
        output_file.write("\t" + "\t" + "Name: " + model.name + "\n" + "\n")

        output_file.write("\t" + "Length metrics:" + "\n")
        output_file.write("\t" + "\t" + "Source Lines of Code (SLOC) = " +
                          str(model.sloc) + "\n" + "\n")

        output_file.write("\t" + "Halstead metrics:" + "\n")
        output_file.write("\t" + "\t" + "Halstead Program Length = " +
                          str(model.h_prog_length) + "\n")
        output_file.write("\t" + "\t" + "Halstead Vocabulary Length = " +
                          str(model.h_vocab_length) + "\n")
        output_file.write("\t" + "\t" + "Halstead Program Volume  = " +
                          str(model.h_prog_vollume) + "\n")
        output_file.write("\t" + "\t" + "Halstead Program Difficulty  = " +
                          str(model.h_prog_diff) + "\n")
        output_file.write("\t" + "\t" + "Halstead Programming Effort  = " +
                          str(model.h_prog_effort) + "\n")
        output_file.write("\t" + "\t" + "Halstead Language Level  = " +
                          str(model.h_lang_lvl) + "\n")
        output_file.write("\t" + "\t" + "Halstead Intelligence Content  = " +
                          str(model.h_int_content) + "\n")
        output_file.write("\t" + "\t" + "Halstead Programming Time  = " +
                          str(model.h_prog_time) + "\n" + "\n")

        output_file.write("\t" + "Control Flow metrics:" + "\n")
        output_file.write("\t" + "\t" + "McCabe's Cyclomatic complexity = " +
                          "TBD" + "\n")
        output_file.write(
            "############################################################################"
            + "\n" + "\n")

    #create PDF with overal image results

    pdf = FPDF()
    pdf.add_page()
    pdf.set_xy(0, 0)
    pdf.set_font('arial', 'B', 30)
    pdf.cell(60)
    pdf.cell(75, 10, "Analysis Results", 0, 2, 'C')
    pdf.cell(-60)
    pdf.set_font('arial', 'B', 20)
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.cell(75, 10, "Full Sample results:", 0, 2, 'C')

    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.set_font('arial', 'B', 15)
    pdf.cell(75, 10, "Size metrics:", 0, 2, 'C')
    pdf.image("./Results/SLOC.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.cell(75, 10, "Halstead metrics:", 0, 2, 'C')

    pdf.image("./Results/prog_length.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.image("./Results/vocab_length.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.image("./Results/prog_vollume.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.image("./Results/prog_diffic.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.image("./Results/prog_effort.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.image("./Results/lang_level.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.image("./Results/i_cont.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')
    pdf.cell(75, 10, "", 0, 2, 'C')
    pdf.image("./Results/p_time.png",
              x=None,
              y=None,
              w=200,
              h=175,
              type='',
              link='')

    pdf.output('./Results/Sample_Results.pdf', 'F')
Exemplo n.º 54
0
def gen_pdf_pages(mol_keys, results):
    sort_pages = [
        mol_keys[i * 3:(i + 1) * 3]
        for i in range((len(mol_keys) + 3 - 1) // 3)
    ]
    counter = 1
    pages = []
    for page in sort_pages:
        pdf = FPDF()
        pdf.add_font("DejaVu", "", ttf_path, uni=True)
        pdf.add_page()
        img_place_y = 10
        txt_place_y = 15
        num_place_y = 98
        for mol_n in page:
            pdf.set_font("DejaVu", "", 10)
            pdf.image(f"{mol_n}.png", 10, img_place_y, 90)
            os.remove(f"{mol_n}.png")
            pdf.rect(10, img_place_y, 190, 90)
            pdf.dashed_line(100, img_place_y, 100, img_place_y + 90)
            pdf.text(12, num_place_y, str(counter))
            counter += 1
            img_place_y += 94
            num_place_y += 94
            txt_space_y = 0
            line_counter = 0
            props_list = list(results[mol_n]["props"].items())
            for tag in props_list:
                entry_length = len(str(tag[0])) + len(str(tag[1])) + 2
                if entry_length <= 45:
                    line_counter += 1
                else:
                    line_counter += 2
            if line_counter <= 17:
                size = 10
                write_props(pdf, props_list, txt_place_y, txt_space_y, size)
            elif 17 < line_counter <= 19:
                size = 9
                write_props(pdf, props_list, txt_place_y, txt_space_y, size)
            elif 19 < line_counter <= 21:
                size = 8
                write_props(pdf, props_list, txt_place_y, txt_space_y, size)
            elif 21 < line_counter <= 23:
                size = 7
                write_props(pdf, props_list, txt_place_y, txt_space_y, size)
            elif 23 < line_counter <= 25:
                size = 6
                write_props(pdf, props_list, txt_place_y, txt_space_y, size)
            elif 25 < line_counter <= 27:
                size = 5
                write_props(pdf, props_list, txt_place_y, txt_space_y, size)
            else:
                size = 5
                write_props_list = props_list[:27]
                write_props(pdf, write_props_list, txt_place_y, txt_space_y,
                            size)
            txt_place_y += 94
        out = f"{counter}.pdf"
        pdf.output(out)
        pages.append(f"{counter}.pdf")
    return pages
Exemplo n.º 55
0
elif organism == "Mus musculus":
    picture = mouse
    red = 160
    green = 160
    blue = 160
    alignment = "C"
else:
    picture = sadness
    red = 255
    green = 0
    blue = 0
    alignment = "L"

pdf = FPDF()  #creating a PDF file
pdf.add_page()  #adding a page to the newly created PDF file
pdf.set_font('Courier', size=24)  #specifying the font and size
pdf.cell(100, 20, txt=query_name, ln=1,
         align="L")  #first line is query name aligned left
pdf.cell(100, 20, txt=query_length, ln=1,
         align="L")  #second line is query length
pdf.cell(100, 20, txt=hit_organism, ln=1,
         align="L")  #third line is hit organism
pdf.cell(100, 20, txt=hit_gene, ln=1, align="L")  #fourth line is hit gene
pdf.cell(100, 20, txt=evalue, ln=1, align="L")  #fifth line is the evalue
pdf.set_text_color(int(red), int(green),
                   int(blue))  #changing the colour of the subsequent text
pdf.multi_cell(
    200, 10, txt=picture, align=alignment
)  #over multiple lines, we are printing out the final organism picture

ts = str(int(time.time()))  #makes a time stamp so we don't write over files
Exemplo n.º 56
0
def makePDF(customerData):
    # declare location of PDFs to use
    overlay_pdf_file_name = 'overlay_PDF.pdf' # textOverSuccess.pdf
    pdf_template_file_name = 'background.pdf' # base_PDF_template


    pdf = FPDF('P', 'mm', 'letter') # paragraph oriented, millimeters measured, letter page sized
    pdf.add_page()
    pdf.set_font('Arial', '', 14) # font, style ('' means normal), 14pt

    ### test dictionary for overlay data
    ### WORKS

    # result_pdf_file_name = "./pdfs/" + customerData['person_name'] + ".pdf"
    
    form_dictionary = \
    {
        'form': 'ACCT',
        'data': [
            { 'x': 13, 'y': 146, 'w': 94, 'h': 5.5, 'value': customerData['person_name'] },
            { 'x': 108, 'y': 146, 'w': 23, 'h': 5.5, 'value': '1450' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
            { 'x': 133, 'y': 146, 'w': 22, 'h': 5.5, 'value': 'iterating make another' },
        ]
    }

    # adds form data to overlay pdf
    for field in range(0, len(form_dictionary['data'])):
        pdf.set_xy(form_dictionary['data'][field]['x'], form_dictionary['data'][field]['y'])
        pdf.cell(form_dictionary['data'][field]['w'], form_dictionary['data'][field]['h'], form_dictionary['data'][field]['value'])

    # ready to overlay to watermark template
    pdf.output('overlay_PDF.pdf')
    pdf.close()


    ### this takes the overlay data and merges it with the watermark template
    ### WORKS
    with open("./polls/background.pdf", 'rb') as pdf_template_file, open(overlay_pdf_file_name, 'rb') as overlay_PDF_file:
        # open watermark template pdf object
        pdf_template = PdfFileReader(pdf_template_file)
        # open overlay data pdf object
        overlay_PDF = PdfFileReader(overlay_PDF_file)

        template_total_pages = pdf_template.getNumPages()
        # iterate through each page to flatten overlay data and watermark template
        for page_number in range(0, template_total_pages):
            # get each page from watermark template
            template_page = pdf_template.getPage(page_number)
            # merge overlay data to watermark template
            template_page.mergePage(overlay_PDF.getPage(page_number))
            # write result to new PDF
            output_pdf = PdfFileWriter()
            output_pdf.addPage(template_page)
        with open(result_pdf_file_name, 'wb') as result_pdf_file:
            output_pdf.write(result_pdf_file)
Exemplo n.º 57
0
def Generate_Report(name, gender, age, mobile, sc, Scale, scan):
    #create pdf object
    pdf = FPDF(
        orientation='P', unit='mm', format='A4'
    )  #orientation = ['P','L'], unit = ['mm','cm'], format = ['A3','A4','A5','letter','legal']

    #add a new page
    pdf.add_page()

    #set font to pdf object
    pdf.set_font("Arial", 'B', size=16)
    pdf.set_text_color(255, 0, 0)

    #add logo as header
    img_path = 'logo.png'
    sp = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
    title = 'Automated Diabetic Retinopathy Severity Identification'

    exs = 'Not Found'
    hms = 'Not Found'
    ma = 'Not Found'

    if (sc == 0):
        dr = 'Negative'
    else:
        dr = 'Positive'

    if Scale == 0:
        scale = 'None'
        ma = 'None'
        exs = 'None'
        hms = 'None'
    elif Scale == 1:
        scale = 'Mild'
        ma = 'Present'
    elif Scale == 2:
        scale = 'Moderate'
        ma = 'Present'
    elif Scale == 3:
        scale = 'Severe'
        ma = 'Present'
        exs = 'Formed'
        hms = 'Found'
    else:
        scale = 'Proliferative'
        ma = 'Present'
        exs = 'Formed'
        hms = 'Found'

    pdf.image(img_path, x=80, y=8, w=60, h=20)
    pdf.ln(20)
    # Add Title
    pdf.cell(20)
    pdf.cell(20, 5, title, ln=1)
    pdf.ln(0.2)
    pdf.set_font("Arial", size=10)
    pdf.set_text_color(0, 0, 0)
    pdf.cell(0, 5, 'Date: %s' % date.today().strftime("%b-%d-%Y"), ln=0)
    pdf.cell(0, 5, "Shaik Nagur Shareef (+91 8309913300)", align="R", ln=1)
    #draw line
    pdf.set_line_width(0.5)
    pdf.line(10, 40, 200, 40)
    pdf.ln(2)

    pdf.set_font("Arial", 'B', size=12)
    pdf.set_text_color(0, 0, 255)

    pdf.cell(0, 5, "Patient Details", align="C", ln=1)

    pdf.set_font("Arial", size=12)
    pdf.set_text_color(0, 0, 0)

    pdf.ln(5)
    pdf.cell(0, 5, "Name    :" + sp + sp + sp + name, align="L", ln=1)
    pdf.ln(2)
    pdf.cell(0, 5, "Gender  :" + sp + sp + sp + gender, align="L", ln=1)
    pdf.ln(2)
    pdf.cell(0,
             5,
             "Age     \t\t:" + sp + sp + sp + str(age) + " years",
             align="L",
             ln=1)
    pdf.ln(2)
    pdf.cell(0,
             5,
             "Mobile \t\t:" + sp + sp + sp + str(mobile),
             align="L",
             ln=1)
    pdf.ln(5)
    pdf.set_font("Arial", 'B', size=12)
    pdf.set_text_color(0, 0, 255)

    pdf.cell(0, 5, "Diagonosis Report", align="C", ln=1)

    pdf.set_font("Arial", size=12)
    pdf.set_text_color(0, 0, 0)

    pdf.ln(5)
    pdf.cell(0, 5, "Diabetic Retinopathy    :" + sp + sp + dr, align="L", ln=1)
    pdf.ln(2)
    pdf.cell(0,
             5,
             "Severity                \t\t\t\t\t\t\t\t:" + sp + sp + scale,
             align="L",
             ln=1)
    pdf.ln(2)
    pdf.cell(0,
             5,
             "Micro Aneurysms		 \t\t\t\t\t\t:" + sp + sp + ma,
             align="L",
             ln=1)
    pdf.ln(2)
    pdf.cell(0,
             5,
             "Hemorrhages             \t\t:" + sp + sp + hms,
             align="L",
             ln=1)
    pdf.ln(2)
    pdf.cell(0,
             5,
             "Exudates                \t\t\t\t\t\t:" + sp + sp + exs,
             align="L",
             ln=1)

    pdf.ln(10)

    #add Scan
    pdf.image(scan, x=40, y=140, w=128, h=128)

    # save file
    pdf.output("static/Reports/" + name + ".pdf")
Exemplo n.º 58
0
def stickers_simple(col = 3, rows = 7, skip = 0, comp = [], store = None, pozice = None):
    page = 0
    page_cols = col
    page_rows = rows
    page_cells = page_cols * page_rows
    cell_w = 210/page_cols
    cell_h = 297/page_rows

    stock_identificator = store

    print ("pozadovany format je 70x42")
    pdf = FPDF('P', 'mm', format='A4')

    pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
    pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
    pdf.set_font('pt_sans-bold', '', 12)

    pdf.set_auto_page_break(False)
    pdf.add_page()

    for i, component in enumerate(comp):
        i += skip
        #   id = component['name'].strip().replace('/', '_')
        id = str(component['_id'])
        barcode = str(int(id, 16))
        code128.image(barcode).save("static/tmp/barcode/%s.png"%(id))

        if i != 0 and i%(page_cells) == 0:
            page += 1
            pdf.add_page()
            print("New PAGE --- ", i, i%page_cells)

        row = int(i/page_cols)-page*page_rows
        column = i%page_cols
        cell_x = column*cell_w
        cell_y = row*cell_h

        pdf.set_xy(cell_x+3, cell_y+6.75)
        if len(component['name'])<23:
            pdf.set_font('pt_sans-bold', '', 14)
        else:
            pdf.set_font('pt_sans-bold', '', 10)
        pdf.cell(cell_w-10, 0, component['name'][:35])
        pdf.set_xy(cell_x+1, cell_y+9)
        pdf.image('static/tmp/barcode/%s.png'%(id), w = cell_w-2, h=6)

        pdf.set_font('pt_sans', '', 9.5)
        pdf.set_xy(cell_x+3, cell_y+22)
        try:
            pdf.multi_cell(cell_w-6, 3.4, component['description'][:190])
        except Exception as e:
            pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))

        #pdf.set_xy(cell_x+3, cell_y+12)
        #pdf.set_font('pt_sans', '', 7.5)
        #pdf.cell(cell_w-10, 10, id + " | " + str(datetime.date.today()) )

        pos = pozice(bson.ObjectId(id), stock = stock_identificator['_id'], primary = True)
        if len(pos) > 0:
            pos = pos[0]['info'][0]['name']
            print("POZ", pos)
        else:
            pos = ""
        pdf.set_font('pt_sans', '', 7.5)
        #pdf.set_xy(cell_x+3, cell_y+15)
        #pdf.cell(cell_w-10, 10, str(stock_identificator['code']) + " | " + str(pos) + " | " + ','.join(component['category']))

        pdf.set_xy(cell_x+3, cell_y+12)
        pdf.cell(cell_w-10, 10, str(datetime.date.today()) + " | " + ','.join(component['category']))

        pdf.set_xy(cell_x+3, cell_y+15)
        pdf.cell(cell_w-10, 10, str(stock_identificator['code']) + " | " + str(pos))

        print("Generovani pozice...")
    return pdf
Exemplo n.º 59
0
# Example of unicode support based on tfPDF
# http://www.fpdf.org/en/script/script92.php

from fpdf import FPDF
import sys

pdf = FPDF()
pdf.add_page()

# Add a Unicode font (uses UTF-8)
pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
pdf.set_font('DejaVu', '', 14)
fn = 'ex.pdf'

# Load a UTF-8 string from a file and print it
txt = open('HelloWorld.txt').read()
pdf.write(8, txt)

# Select a standard font (uses windows-1252)
pdf.set_font('Arial', '', 14)
pdf.ln(10)
pdf.write(5, 'The file size of this PDF is only 12 KB.')

pdf.output(fn, 'F')
import os
try:
    os.startfile(fn)
except:
    os.system("evince %s" % fn)
Exemplo n.º 60
0
"""
Example PDF file generation using PyPDF package.

See documentation at
https://pyfpdf.readthedocs.io/en/latest/index.html

git clone https://github.com/reingart/pyfpdf.git
sudo python3 setup.py install

"""

from fpdf import FPDF

pdf = FPDF()
pdf.add_page(orientation='L', format='A4')
pdf.set_font('Arial', 'B', 16)
pdf.cell(40, 10, 'Hello World!')

pdf.output('pyfpdf_output.pdf', 'F')