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()
예제 #2
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
예제 #3
0
def create_pdf(filepath):
    i = 0  # Index to change the line with every new line of the original file
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    with open(filepath, encoding='utf8') as f:  # Open the file to copy
        for line in f:  # Take a new line of the file
            if line.startswith('#') or line.startswith('    #'):
                pdf.set_font('Arial', 'I', 11)
                pdf.set_text_color(0, 150, 125)
            elif line.startswith('def'):
                pdf.set_font('Arial', 'B', 12)
                pdf.set_text_color(255, 0, 0)
            else:
                pdf.set_font('Arial', '', 10)
                pdf.set_text_color(0, 0, 0)
            pdf.cell(ln=i, h=5.0, align='L', w=0, txt=line,
                     border=0)  # Copy the line to the created PDF file
            i = i + 1
    pdf.output(filepath.split(".")[0] + '.pdf',
               'F')  # Close PDF file with the information
    pdf.close()
예제 #4
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()
예제 #5
0
def ppt2pdf(f):
    if not os.path.exists(f):
        print('Lỗi! Không có file ' + f)
        input('Nhấn Enter để thoát...')
        sys.exit(-1)

    powerpoint = client.CreateObject('Powerpoint.Application')
    powerpoint.Presentations.Open(f)
    f = splitext(f)[0].rstrip(' ') + splitext(f)[1]
    powerpoint.ActivePresentation.Export(splitext(f)[0], 'JPG')
    powerpoint.ActivePresentation.Close()
    powerpoint.Quit()
    pdf = FPDF('L', 'pt', [1440, 1920])
    pdf.set_margins(0, 0, 0)
    for image in sorted(glob(splitext(f)[0] + "\\*.JPG"),
                        key=lambda f: int(''.join(filter(str.isdigit, f)))):
        pdf.add_page()
        pdf.image(image, 0, 0, 1280, 960)

    pdf.output(splitext(f)[0] + '.PDF', 'F')
    pdf.close()
    rmtree(splitext(f)[0])
예제 #6
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
예제 #7
0
def reportegramatica():
    archivo = ""
    for item in reversed(constantes.reporte_gramatical):
        archivo += item + "\n"
    #Aqui ponemos el valor de el diccionario de instruccion dentro de una archivo
    f = open("ReporteGramatical.txt", "w")
    f.write(archivo)
    f.close()

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

    f = open("ReporteGramatical.txt", "r")
    pdf.cell(200, 10, txt="REPORTE GRAMATICAL", ln=1, align='C')
    for x in f:
        pdf.cell(200, 10, txt=x, ln=2, align='L')

    # save the pdf with name .pdf
    pdf.output("ReporteGramatical.pdf")
    f.close()
    pdf.close()
예제 #8
0
def export_to_pdf(header, data, title):
    """
    Create a a table in PDF file from a list of row
        :param title: name of file and title of PDF
        :param header: columns name
        :param data: List of row (a row = a list of cells)
        :param spacing=1:
    """
    pdf = FPDF()  # New  pdf object

    pdf.set_font("Arial", size=12)  # Font style
    epw = pdf.w - 2 * pdf.l_margin  # Width of document
    col_width = pdf.w / 4.5  # Column width in table
    row_height = pdf.font_size * 1.5  # Row height in table
    spacing = 1.3  # Space in each cell

    pdf.add_page()  # add new page

    pdf.cell(epw, 0.0, 'Fornecedor ' + title, align='C')  # create title cell
    pdf.ln(row_height * spacing)  # Define title line style

    # Add header
    for item in header:  # for each column
        pdf.cell(col_width, row_height * spacing, txt=item,
                 border=1)  # Add a new cell

    pdf.ln(row_height * spacing)  # New line after header

    for row in data:  # For each row of the table
        for item in row:  # For each cell in row
            pdf.cell(col_width, row_height * spacing, txt=item,
                     border=1)  # Add cell
        pdf.ln(row_height * spacing)  # New line after row

    my_path = os.path.abspath(os.path.dirname(__file__))
    pdf.output(os.path.join(my_path, '../assets/table/' + title +
                            '.pdf'))  # Create pdf file
    pdf.close()
예제 #9
0
 def generate_custom_pdf(self):
     liste = self.find_students_by_criteria()
     print(liste)
     pdf_file = FPDF()
     pdf_file.add_page()
     pdf_file.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
     pdf_file.set_font('DejaVu', '', 14)
     reshaped_text = arabic_reshaper.reshape(self.all_classes.currentText())  # correct its shape
     bidi_text = get_display(reshaped_text)
     pdf_file.cell(200, 6.3, bidi_text, ln=1, align='C')
     for e in liste:
         # print(u"ذهب الطالب الى المدرسة")
         # s = "ذهب الطالب الى المدرسة"
         reshaped_text = arabic_reshaper.reshape(
             e[1] + "                              " + e[-1])  # correct its shape
         bidi_text = get_display(reshaped_text)
         print(bidi_text)
         pdf_file.cell(200, 6.3, bidi_text, ln=1, align='R', border=1)
         # pdf_file.cell(20, 5, e[1], ln=1, align="C", border=1)
         # pdf_file.write(8, e[0])
         # pdf_file.ln(8)
     pdf_file.output(self.all_classes.currentText() + " " + self.criteria.currentText() + ".pdf", 'F')
     pdf_file.close()
예제 #10
0
def imprimir_etiquetas_cajas(pallobj, articuloobj, usuario):
    ETIQUETA_DIR = '%s/label_files_cajas' % PROJECT_ROOT
    ahora = datetime.datetime.now()
    pdf=FPDF('L','cm',(10, 12.5))
    pdf.add_page()
    pdf.set_font('Arial',style='',size=6)
    pdf.set_y(1)
    pdf.set_x(0.6)
    pdf.cell(1, 0, 'ARTICULO: %s - %s'  % (articuloobj.articulocod, articuloobj.articulo_descripcion), align='L')
    pdf.set_y(1.5)
    pdf.set_x(0.6)
    pdf.cell(1, 0, 'LOTE: %s  UNIDADES: %s'  % (pallobj.articulo_lote, pallobj.articulo_unidades_x_pall), align='L')
    pdf.set_y(1.8)
    pdf.set_x(0.6)
    #linea
    pdf.line(0.5, 2, 11.5, 2)
    #seccion producto
    barra_articulo = Code128Encoder('%s|%s' % (articuloobj.codigo_barra_caja, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d')), options={'height':60, 'label_border': 1, 'bottom_border': 5})
    barra_articulo.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), bar_width=1)
    pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), x=0.8, y=2.1)
    pdf.line(0.5, 4.5, 11.5, 4.5)
    pdf.set_y(4.7)
    pdf.set_x(0.5)
    pdf.cell(1, 0, 'BODEGA: %s  HORA: %s FECHA: %s IMPRESO POR: %s'  % (pallobj.bodega, ahora.strftime('%H:%M:%S'), ahora.strftime('%d/%m/%Y'), usuario), align='L')

    pdf.output('%s/%s_%s.pdf' % (ETIQUETA_DIR, articuloobj.articulocod, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d')))
    pdf.close()

    cups_server = CupsServer(settings.CUPS_ADMIN[0],
                         settings.CUPS_ADMIN[1]
                         )

    cups_server.modo_admin()
    for a in range(4):

        cups_server.imprimir_trabajo('Zebra_TLP2844', "%s/%s_%s.jpg" % (ETIQUETA_DIR, articuloobj.articulocod, pallobj.articulo_fecha_vencimiento.strftime('%Y%m%d')), {})
def makePdf(data):  # data passed in from form
    # declare location of PDFs to use
    overlay_pdf_file_name = 'overlay_PDF.pdf'  # textOverSuccess.pdf
    pdf_template_file_name = 'acct_background.pdf'  # base_PDF_template

    result_pdf_file_name = result_form.pdf
    # result_pdf_file_name = "./pdfs/" + data['person_name'] + ".pdf"

    pdf = FPDF('P', 'mm', 'letter'
               )  # paragraph oriented, millimeters measured, letter page sized
    pdf.set_margins(0, 0, 0)
    pdf.add_page(
        same=True)  # sets page added to FPDF object to same parameters
    pdf.set_font('Arial', '', 12)  # font, style ('' means normal), 12pt

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

    vehicle_vin = data.vin  # customer name ### COORDS BELONG TO VIN
    year = data.year  # vehicle year
    vehicle_make = data.make  # vehicle make
    vehicle_style = data.style  # vehicle body style
    vehicle_model = data.model  # vehicle model

    vehicle_title_no = data.title  # vehicle title/document number
    vehicle_license = data.license  # TX license plate number

    customer_name = data.name  # customer name
    second_customer_name = data.second_name  # additional customer name

    date = ''  # date above, date below

    recipient_first_name = data.recipient_first_name  # receipient first name
    recipient_middle_name = data.recipient_middle_name  # recipient middle name
    recipient_last_name = data.recipient_last_name  # receipient last name
    recipient_suffix = data.recipient_suffix  # receipient name suffix

    address = data.address  # mailing address
    city = data.city  # city
    state = data.state  # state
    zip_code = data.zip_code  # zip

    email = data.email  # email
    phone = data.phone  # phone number
    '''
        vehicle_vin =  '12345678901234567' # customer name ### COORDS BELONG TO VIN
        year = '2000' # vehicle year
        vehicle_make = 'Affordy' # vehicle make
        vehicle_style = 'Stylo' # vehicle body style
        vehicle_model = 'Edsel' # vehicle model
                
        vehicle_title_no = '1234567890' # vehicle title/document number
        vehicle_license = 'DLR-J3L2' # TX license plate number
                
        data['person_name'] = 'Bob' # customer name
        second_customer_name = 'Cat' # additional customer name

        date = 'May 1, 2018' # date above, date below

        recipient_first_name = 'Johnny' # receipient first name
        recipient_middle_name = 'Middle' # recipient middle name
        recipient_last_name = 'Recipient' # receipient last name
        recipient_suffix = '' # receipient name suffix

        address = '123 Fake St.' # mailing address
        city = 'Houston' # city
        state = 'TX' # state
        zip_code = '77777' # zip

        email = '*****@*****.**' # email
        phone = '123-123-1234' # phone number
    '''

    # dictionary for ACCT form

    form_dictionary = {
        'form':
        'ACCT',  # form_type
        'data': [
            {
                'x': 6,
                'y': 140,
                'w': 94,
                'h': 5,
                'value': vehicle_vin
            },  # customer name ### COORDS BELONG TO VIN
            {
                'x': 102,
                'y': 140,
                'w': 23,
                'h': 5,
                'value': year
            },  # vehicle year
            {
                'x': 127,
                'y': 140,
                'w': 22,
                'h': 5,
                'value': vehicle_make
            },  # vehicle make
            {
                'x': 150,
                'y': 140,
                'w': 22,
                'h': 5,
                'value': vehicle_style
            },  # vehicle body style
            {
                'x': 173,
                'y': 140,
                'w': 22,
                'h': 5,
                'value': vehicle_model
            },  # vehicle model
            {
                'x': 6,
                'y': 149,
                'w': 22,
                'h': 5,
                'value': vehicle_title_no
            },  # vehicle title/document number
            {
                'x': 102,
                'y': 149,
                'w': 22,
                'h': 5,
                'value': vehicle_license
            },  # TX license plate number
            {
                'x': 88,
                'y': 175,
                'w': 22,
                'h': 5,
                'value': customer_name
            },  # customer name
            {
                'x': 88,
                'y': 189,
                'w': 22,
                'h': 5,
                'value': second_customer_name
            },  # additional customer name
            {
                'x': 170,
                'y': 175,
                'w': 22,
                'h': 5,
                'value': date
            },  # date above
            {
                'x': 170,
                'y': 189,
                'w': 22,
                'h': 5,
                'value': date
            },  # date below
            {
                'x': 6,
                'y': 209,
                'w': 73,
                'h': 5,
                'value': recipient_first_name
            },  # receipient first name
            {
                'x': 80,
                'y': 209,
                'w': 46,
                'h': 5,
                'value': recipient_middle_name
            },  # recipient middle name
            {
                'x': 127,
                'y': 209,
                'w': 46,
                'h': 5,
                'value': recipient_last_name
            },  # receipient last name
            {
                'x': 174,
                'y': 209,
                'w': 21,
                'h': 5,
                'value': recipient_suffix
            },  # receipient name suffix
            {
                'x': 6,
                'y': 218,
                'w': 73,
                'h': 5,
                'value': address
            },  # mailing address
            {
                'x': 80,
                'y': 218,
                'w': 80,
                'h': 5,
                'value': city
            },  # city
            {
                'x': 127,
                'y': 218,
                'w': 46,
                'h': 5,
                'value': state
            },  # state
            {
                'x': 174,
                'y': 218,
                'w': 22,
                'h': 5,
                'value': zip_code
            },  # zip
            {
                'x': 6,
                'y': 227,
                'w': 22,
                'h': 5,
                'value': email
            },  # email
            {
                'x': 103,
                'y': 227,
                'w': 22,
                'h': 5,
                'value': phone
            },  # phone number
        ]
    }
    '''
    {
        'form': 'ACCT',
        'data': [
            { 'x': 6, 'y': 140, 'w': 94, 'h': 5, 'value': vehicle_vin }, # customer name ### COORDS BELONG TO VIN
            { 'x': 102, 'y': 140, 'w': 23, 'h': 5, 'value': year }, # vehicle year
            { 'x': 127, 'y': 140, 'w': 22, 'h': 5, 'value': vehicle_make }, # vehicle make
            { 'x': 150, 'y': 140, 'w': 22, 'h': 5, 'value': vehicle_style }, # vehicle body style
            { 'x': 173, 'y': 140, 'w': 22, 'h': 5, 'value': vehicle_model }, # vehicle model
            
            { 'x': 6, 'y': 149, 'w': 22, 'h': 5, 'value': vehicle_title_no }, # vehicle title/document number
            { 'x': 102, 'y': 149, 'w': 22, 'h': 5, 'value': vehicle_license }, # TX license plate number
            
            { 'x': 88, 'y': 175, 'w': 22, 'h': 5, 'value': customerData['person_name'] }, # customer name
            { 'x': 88, 'y': 189, 'w': 22, 'h': 5, 'value': second_customer_name }, # additional customer name

            { 'x': 170, 'y': 175, 'w': 22, 'h': 5, 'value': date }, # date above
            { 'x': 170, 'y': 189, 'w': 22, 'h': 5, 'value': date }, # date below

            { 'x': 6, 'y': 209, 'w': 73, 'h': 5, 'value': recipient_first_name }, # receipient first name
            { 'x': 80, 'y': 209, 'w': 46, 'h': 5, 'value': recipient_middle_name }, # recipient middle name
            { 'x': 127, 'y': 209, 'w': 46, 'h': 5, 'value': recipient_last_name }, # receipient last name
            { 'x': 174, 'y': 209, 'w': 21, 'h': 5, 'value': recipient_suffix }, # receipient name suffix

            { 'x': 6, 'y': 218, 'w': 73, 'h': 5, 'value': address }, # mailing address
            { 'x': 80, 'y': 218, 'w': 80, 'h': 5, 'value': city }, # city
            { 'x': 127, 'y': 218, 'w': 46, 'h': 5, 'value': state }, # state
            { 'x': 174, 'y': 218, 'w': 22, 'h': 5, 'value': zip_code }, # zip

            { 'x': 6, 'y': 227, 'w': 22, 'h': 5, 'value': email }, # email
            { 'x': 103, 'y': 227, 'w': 22, 'h': 5, 'value': phone }, # phone number
        ]
    }
    '''
    ''' previous test dictionary
    form_dictionary = {
        'Vehicle Identification Number': 'TEST VIN #',
        'Year': 'TEST 1999',
        'Make': 'TES Cake',
        'Body Style': 'TEST Being There',
        'Model': 'TEST Modal',
        'TitleDocument Number if unknown leave blank': 'TEST 111 111',
        'Texas License Plate Number if unknown leave blank': 'TEST 12AS3F',
        'Printed Name of Applicant Owner': 'TEST FIRSTNAME',
        'Date': 'TEST TODAY',
        'Additional Applicant Owner': 'TEST NONE',
        'Date_2': 'TEST TODAY',
        'First Name or Entity Name Middle Name Last Name Suffix if any': 'TEST ENTITY MIDDLE',
        'Mailing Address City State Zip': 'TEST 123 FAKE ST',

        'Email': 'TEST [email protected]',
        'Phone Number': 'TEST 123-123-1234'
    }
    '''

    # 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("./utils/acct_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)
예제 #12
0
    def runed(self):
        flag1 = False
        if self.ED_length_of_stay_mean != 0 and self.ED_length_of_stay_std != 0 and self.Daily_arrival_rate != [] and self.Hourly_pattern != []:
            flag1 = True

        processbartotallength = flag1 * len(self.Hourly_pattern) * len(
            self.Daily_arrival_rate)

        if flag1 == True:
            mu = log(
                square(self.ED_length_of_stay_mean) / sqrt(
                    square(self.ED_length_of_stay_mean) +
                    square(self.ED_length_of_stay_mean)))
            stddev = sqrt(
                log(1 + square(self.ED_length_of_stay_mean) /
                    square(self.ED_length_of_stay_mean)))

            ArrivalRate = []
            for j in range(len(self.Daily_arrival_rate)):
                for k in range(24):
                    ArrivalRate.append(
                        float(self.Daily_arrival_rate[j]) *
                        float(self.Hourly_pattern[k]))
            ArrivalRate = array(ArrivalRate, dtype=float)
            TotalTimeLength = ArrivalRate.size
            initial_condition = self.ED_initial_condition

            step = 1
            t = 1
            tlist = []
            tlist = range(1, TotalTimeLength + 1)
            mt = []
            mt5 = []
            mt95 = []
            pt10 = []
            pt15 = []
            pt20 = []
            pt25 = []
            pt30 = []
            pt35 = []
            pt40 = []
            error = []
            st = []
            stl = []

            while t <= TotalTimeLength:
                ans, err = quad(f,
                                0,
                                t,
                                args=(t, mu, stddev, ArrivalRate),
                                limit=500)
                total_probability = 0
                probability_still_in_system = 1 - rs(
                    t, mu, stddev, self.ED_length_of_stay_mean)
                # Calculate the mean
                mttemp = initial_condition * probability_still_in_system + ans
                mt.append(mttemp)
                # Calculate the numerical distribution:
                temptotal = 0
                flag = [False, False]
                tempcdf = 0
                while tempcdf <= 0.99:
                    i = 0
                    if t <= self.Maximum_ED_stay:
                        while i <= temptotal and i <= initial_condition:
                            if i <= initial_condition:
                                tempcdf = tempcdf + binom.pmf(
                                    i, initial_condition,
                                    probability_still_in_system) * poisson.pmf(
                                        (temptotal - i), ans)
                            i = i + 1
                    else:
                        tempcdf = poisson.cdf(temptotal, ans)
                    if tempcdf >= 0.05 and flag[0] == False:
                        if temptotal - 1 > 0:
                            tempq = temptotal - 1
                        else:
                            tempq = 0
                        mt5.append(tempq)
                        flag[0] = True
                    if tempcdf >= 0.95 and flag[1] == False:
                        mt95.append(temptotal)
                        flag[1] = True
                    QApplication.processEvents()
                    if temptotal == 10:
                        pt10.append(1 - tempcdf)
                    if temptotal == 15:
                        pt15.append(1 - tempcdf)
                    if temptotal == 20:
                        pt20.append(1 - tempcdf)
                    if temptotal == 25:
                        pt25.append(1 - tempcdf)
                    if temptotal == 30:
                        pt30.append(1 - tempcdf)
                    if temptotal == 35:
                        pt35.append(1 - tempcdf)
                    if temptotal == 40:
                        pt40.append(1 - tempcdf)
                    temptotal = temptotal + 1
                temptotal = temptotal - 1
                if temptotal < 10:
                    pt10.append(float(0))
                if temptotal < 15:
                    pt15.append(float(0))
                if temptotal < 20:
                    pt20.append(float(0))
                if temptotal < 25:
                    pt25.append(float(0))
                if temptotal < 30:
                    pt30.append(float(0))
                if temptotal < 35:
                    pt35.append(float(0))
                if temptotal < 40:
                    pt40.append(float(0))
                t = t + step
                QApplication.processEvents()
                self.ProgressBar.setValue(
                    ceil((t) / processbartotallength * 100))

            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
            ax.plot(tlist, mt)
            ax.set_title('Expected Number and 95% Band')
            ax.fill_between(tlist, mt5, mt95, color='b', alpha=0.1)
            ax.set_ylabel("ED Census")
            ax.set_xlabel("Hours")
            fig.savefig('temp1.png')

            templist = [mt, mt5, mt95]
            tempnames = ["mean", "5 Quantile", "95 Quantile"]
            temptest = pd.DataFrame(data=templist)
            temptest.to_csv("ED.csv", encoding="gbk")

            temp1 = QPixmap("temp1.png")
            self.ED_Graph_Label.setPixmap(temp1.scaled(480, 360))

            TableData = PrettyTable()
            TableData.field_names = [
                "Num Pts", "10 Days", "20 Days", "30 Days", "40 Days",
                "50 Days", "60 Days", "70 Days", "80 Days", "90 Days"
            ]
            TableData.add_row([
                "10 pts",
                maxc(pt10[0:240]),
                maxc(pt10[0:480]),
                maxc(pt10[0:720]),
                maxc(pt10[0:960]),
                maxc(pt10[0:1200]),
                maxc(pt10[0:1440]),
                maxc(pt10[0:1680]),
                maxc(pt10[0:1920]),
                maxc(pt10[0:2160])
            ])
            TableData.add_row([
                "15 pts",
                maxc(pt15[0:240]),
                maxc(pt15[0:480]),
                maxc(pt15[0:720]),
                maxc(pt15[0:960]),
                maxc(pt15[0:1200]),
                maxc(pt15[0:1440]),
                maxc(pt15[0:1680]),
                maxc(pt15[0:1920]),
                maxc(pt15[0:2160])
            ])
            TableData.add_row([
                "20 pts",
                maxc(pt20[0:240]),
                maxc(pt20[0:480]),
                maxc(pt20[0:720]),
                maxc(pt20[0:960]),
                maxc(pt20[0:1200]),
                maxc(pt20[0:1440]),
                maxc(pt20[0:1680]),
                maxc(pt20[0:1920]),
                maxc(pt20[0:2160])
            ])
            TableData.add_row([
                "25 pts",
                maxc(pt25[0:240]),
                maxc(pt25[0:480]),
                maxc(pt25[0:720]),
                maxc(pt25[0:960]),
                maxc(pt25[0:1200]),
                maxc(pt25[0:1440]),
                maxc(pt25[0:1680]),
                maxc(pt25[0:1920]),
                maxc(pt25[0:2160])
            ])
            TableData.add_row([
                "15 pts",
                maxc(pt30[0:240]),
                maxc(pt30[0:480]),
                maxc(pt30[0:720]),
                maxc(pt30[0:960]),
                maxc(pt30[0:1200]),
                maxc(pt30[0:1440]),
                maxc(pt30[0:1680]),
                maxc(pt30[0:1920]),
                maxc(pt30[0:2160])
            ])
            TableData.add_row([
                "35 pts",
                maxc(pt35[0:240]),
                maxc(pt35[0:480]),
                maxc(pt35[0:720]),
                maxc(pt35[0:960]),
                maxc(pt35[0:1200]),
                maxc(pt35[0:1440]),
                maxc(pt35[0:1680]),
                maxc(pt35[0:1920]),
                maxc(pt35[0:2160])
            ])
            TableData.add_row([
                "40 pts",
                maxc(pt40[0:240]),
                maxc(pt40[0:480]),
                maxc(pt40[0:720]),
                maxc(pt40[0:960]),
                maxc(pt40[0:1200]),
                maxc(pt40[0:1440]),
                maxc(pt40[0:1680]),
                maxc(pt40[0:1920]),
                maxc(pt40[0:2160])
            ])

            header, data = get_data_from_prettytable(TableData)

            pdf = FPDF()
            # Font style
            pdf.set_font("Arial", size=9)
            epw = pdf.w - 2 * pdf.l_margin  # Witdh of document
            col_width = pdf.w / 10.5  # Column width in table
            row_height = pdf.font_size * 1.5  # Row height in table
            spacing = 1.3

            pdf.add_page()
            pdf.set_font("Arial", size=20)
            pdf.cell(epw, 0.0, 'COVID-CAT Report for ED',
                     align='C')  # create title cell
            pdf.ln(row_height * spacing)  # Define title line style

            pdf.image("temp1.png", w=epw, h=epw * 0.75)

            pdf.set_font("Arial", size=15)
            pdf.cell(
                epw,
                pdf.font_size * spacing,
                'Probability of exceeding a given number of patients within:',
                0,
                1,
                align='L')

            pdf.set_font("Arial", size=9)
            # Add header
            for item in header:  # for each column
                pdf.cell(
                    col_width,
                    row_height * spacing,  # Add a new cell
                    txt=item,
                    border=1)
            pdf.ln(row_height * spacing)  # New line after header

            for row in data:  # For each row of the table
                for item in row:  # For each cell in row
                    pdf.cell(
                        col_width,
                        row_height * spacing,  # Add cell
                        txt=item,
                        border=1)
                pdf.ln(row_height * spacing)

        if flag1 == True:
            try:
                pdf.output('Report_ED.pdf')  # Create pdf file
                pdf.close()  # Close file
            except:
                QMessageBox.warning(
                    self, "Error",
                    "Couldn't Create PDF. Please close the PDF file of report")
        else:
            QMessageBox.warning(self, "Error", "Not Enough Data")
예제 #13
0
def processKinds(smena_no, date_smena, file_from, file_to, s, po):

    DATE = "D"
    ADDRESS = "K"
    NAME = "C"
    RODITEL = "M"
    MINISTERSTVO = "Q"
    SUMMA = "P"

    with open("position.json") as json_file:
        position = json.load(json_file)

    pdf = FPDF(orientation="L", unit="mm", format="A4")
    pdf.add_font("KEK", '', 'times-new-roman.ttf', uni=True)

    logging.info(file_from)
    logging.info(file_to)
    s_d, s_m, s_g = s
    po_d, po_m, po_g = po

    workbook = load_workbook(filename=file_from)
    sheet = workbook.active
    kinds = []

    i = 10
    while sheet[NAME + str(i)].value:
        kind = {}
        flp = sheet[NAME + str(i)].value.split()
        if len(flp) == 2:
            kind["last_name"], kind["first_name"] = flp
            kind["patronymic"] = ""
        else:
            kind["last_name"], kind["first_name"], kind["patronymic"] = flp
        kind["date"] = sheet[DATE + str(i)].value
        kind["parent"] = re.split("\n|,|  ", sheet[RODITEL + str(i)].value)

        ministerstvo = sheet[MINISTERSTVO + str(i)].value
        if len(ministerstvo) > 50:
            sp = ministerstvo.split(' ')
            kind["ministerstvo"] = [
                " ".join(sp[:(len(sp) // 2) + 2]),
                " ".join(sp[(len(sp) // 2) + 2:])
            ]
        else:
            kind["ministerstvo"] = [ministerstvo]

        address = sheet[ADDRESS + str(i)].value
        if address:
            if len(address) > 40:
                sp = address.split(',')
                kind["address"] = [
                    ",".join(sp[:(len(sp) // 2)]),
                    ",".join(sp[(len(sp) // 2):])
                ]
            else:
                kind["address"] = [address]
        else:
            kind["address"] = [""]
        kind["age"] = kind["date"].strftime("%d.%m.%Y") + " (" + get_age(
            kind["date"], date_smena) + " лет)"
        summa = sheet[SUMMA + str(i)].value
        if summa:
            kind["summa"] = summa
        else:
            kind["summa"] = ""
        kinds.append(kind)
        i += 1

    for kind in kinds:
        printKind(kind, pdf, position, smena_no, s_d, s_m, s_g, po_d, po_m,
                  po_g)
    pdf.output(file_to)
    pdf.close()
    messagebox.showinfo("Ура!", "Путёвки созданы!")
def webtest_pdfmaker(filename):
    print("ssl print started")
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=15)
    f = open(
        '/home/kali/Desktop/Final_Year_Project/cache/' + filename +
        '_ssl_output.txt', 'r')
    pdf.cell(200, 10, txt="WebTesting of " + filename, ln=1, align="C")
    pdf.set_font("Arial", size=8)
    #print(f.read())
    for x in f:
        #print(x)
        #if not x.startswith("|_"):
        pdf.set_text_color(r=255, g=0, b=0)
        pdf.cell(250, 10, txt=x, ln=1)

        #print("----line break------")
    pdf.cell(250, 10, txt="\n\n")
    f.close()
    print("gobuster print started")
    f = open(
        '/home/kali/Desktop/Final_Year_Project/cache/' + filename +
        '_gobuster_report.txt', 'r')

    for x in f:
        #print(x)
        #if not x.startswith("|_"):
        pdf.set_text_color(r=255, g=0, b=0)
        pdf.cell(250, 10, txt=x, ln=1)

        #print("----line break------")
    pdf.cell(250, 10, txt="\n\n")
    f.close()
    print("nikto print started")
    pdf.set_text_color(r=0, g=0, b=0)
    pdf.cell(250, 10, txt="NIKTO SCAN", ln=1)
    ipt = ".".join(filename.split(':'))
    try:
        temp = subprocess.Popen([
            'nikto', '-host', ipt, '-o',
            '/home/kali/Desktop/Final_Year_Project/cache/' + filename +
            '_nikto.txt'
        ],
                                stdout=subprocess.PIPE,
                                universal_newlines=True)
        print(temp.stdout.read())
        #nikto -host 192.168.0.103 -o /home/kali/Desktop/Final_Year_Project/cache/192:168:0:103_nikto.txt
        f = open(
            '/home/kali/Desktop/Final_Year_Project/cache/' + filename +
            '_nikto.txt', 'r')
        for x in f:
            pdf.set_text_color(r=0, g=0, b=0)
            pdf.cell(250, 10, txt=x, ln=1)
        pdf.cell(250, 10, txt="\n\n")
        f.close()
    except FileNotFoundError:
        print("Error in nikto scan")
        pass

    print(filename)
    pdf.output("/home/kali/Desktop/Final_Year_Project/results/" +
               "-".join(filename.split(":")) + "_webreport.pdf")
    pdf.close()
    return "-".join(filename.split(":")) + "_webreport.pdf"
예제 #15
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)
def image_adder(no_of_pages = 0, page_dimension = (0,0), big_frame_dimension = (0, 0), frame_dimension = (0,0), padding_btw_frames = (1,1), image_resize = (0,0), circle_required = False, repetition = 1):

	dimensions_page = (px_to_pt_converter(page_dimension[0]), px_to_pt_converter(page_dimension[1]))
	
	if image_resize[0] == 0 or image_resize[1] == 0:
		image_resize = frame_dimension

	# Creating a directory where all the images will be saved
	directory = BASE_DIR + "/uploader/qrcodes/"
	try:
		mkdir(directory)
	
	except FileExistsError:
		print("Directory already exists! Need to delete it.")
		rmtree(directory)
		mkdir(directory)
	except OSError:
		print("Error creating a directory with name \'qrcodes\'")
		raise OSError
	else:
		print("Successfully created a directory with name \'qrcodes\'")

	try:
		# Extract zip files to a folder
		extractZip(directory)
	except FileNotFoundError:
		print("Error occurred not able to find the directory!")
		raise FileNotFoundError
	except RuntimeError:
		print("Runtime error while processing zipfiles!")
		raise RuntimeError

	try:
		# Directory of the images are required.
		images = resize_images_replicate_and_fetch(directory, image_resize, repetition)
	except IOError:
		print("Either file doesn't exist or image cannot be opened and identified!")
		rmtree(directory)
		raise IOError

	# print(images)
	TOTAL_IMAGES = len(images)
	index_images = 0

	# Incrementing this value for the filename.
	suffix_filename = 1

	while index_images < TOTAL_IMAGES:
		# Initialize pdf variable.
		pdf = FPDF('P', 'pt', dimensions_page)

		# Add a page to the pdf
		pdf.add_page()
		# print(pdf.get_x(), pdf.get_y())
		pdf.set_font('Arial', 'B', 10)
		# Big frame 
		dimensions_bigframe = (px_to_pt_converter(page_dimension[0]-50), px_to_pt_converter(page_dimension[1]-50))
		default_current_pos_x = pdf.get_x()
		default_current_pos_y = pdf.get_y()
		pdf.rect(pdf.get_x(), pdf.get_y(), dimensions_bigframe[0], dimensions_bigframe[1], style = 'D')

		# Frame
		pdf.set_x(default_current_pos_x) 
		pdf.set_y(default_current_pos_y)
		dimensions_frame = (int(px_to_pt_converter(frame_dimension[0])),int(px_to_pt_converter(frame_dimension[1])))

		current_pos_x = default_current_pos_x
		current_pos_y = default_current_pos_y

		
		for row in nm.arange(current_pos_y, dimensions_bigframe[1], dimensions_frame[1]+padding_btw_frames[1]):
			for col in nm.arange(current_pos_x, dimensions_bigframe[0], dimensions_frame[0]+padding_btw_frames[0]):
				if ((col + dimensions_frame[0]) > dimensions_bigframe[0]) or ((row + dimensions_frame[1]) > dimensions_bigframe[1]):
					break
				position_in_x_direction = col+px_to_pt_converter(padding_btw_frames[0])
				position_in_y_direction = row+px_to_pt_converter(padding_btw_frames[1])
				pdf.rect(position_in_x_direction, position_in_y_direction, dimensions_frame[0], dimensions_frame[1], style = 'D')
				if index_images < TOTAL_IMAGES:
					try:
						load_image_to_pdf(pdf, directory + images[index_images], position_in_x_direction, position_in_y_direction, dimensions_frame[0], dimensions_frame[1], circle_required)
					except FileNotFoundError:
						rmtree(directory)
						raise FileNotFoundError
					# processed images are removed
					remove(directory + images[index_images])
					pdf.set_x(col+dimensions_frame[0])
					pdf.set_y(row)
				index_images += 1

			pdf.set_y(row)
			pdf.set_x(current_pos_x)

		# output the pdf to a file. FILENAME = qrcodes(1...n).pdf
		FILE_NAME = BASE_DIR + "/uploader/" + FILE_NAME_PREFIX + str(suffix_filename) + ".pdf"
		pdf.output(FILE_NAME, 'F')
		suffix_filename = suffix_filename + 1
		pdf.close()
		
		
	
	# Removing the directory after processing
	print("Removing the images directory after processing")	
	rmtree(directory)
	print("Removing the zip files after processing")
	rmtree(BASE_DIR + "/uploader/zipfiles")
예제 #17
0
def imprimir_etiquetas(palletsobjs, usuario, reimpresion):
    ETIQUETA_DIR = '%s/label_files' % PROJECT_ROOT
    ahora = datetime.datetime.now()
    for pallobj in palletsobjs:
        pdf=FPDF('P','cm',(10, 12.5))
        pdf.add_page()
        pdf.set_font('Arial',style='',size=55)
        pdf.set_y(1)
        pdf.set_x(0.6)
        if  pallobj.pallet_completo_010:
            pdf.cell(1, 0, '%s-C'  % pallobj.pall_numero, align='L')
        else:
            pdf.cell(1, 0, '%s-I'  % pallobj.pall_numero, align='L')
        # pdf.cell(1, 0, '%s'  % '23423554', align='L')
        pdf.set_font('Arial',style='',size=5)
        pdf.set_y(2.2)
        pdf.set_x(8.5)
        pdf.cell(1, 0, '%s' % ahora.strftime('%d/%m/%Y'), align='R')
        pdf.set_y(2.4)
        pdf.set_x(8.5)
        pdf.cell(1,0, '%s' % ahora.strftime('%H:%M:%S'), align='R')
        pdf.set_y(2.6)
        pdf.set_x(8.5)
        pdf.cell(1,0, usuario, align='R')
        pdf.set_font('Arial',style='',size=8)
        pdf.set_y(2.2)
        pdf.set_x(0.6)
        pdf.cell(1,0, 'PROFORMA: ', align='L')
        pdf.set_x(2.8)
        pdf.cell(1,0, pallobj.pall_proforma, align='L')
        pdf.set_y(2.6)
        pdf.set_x(0.6)
        pdf.cell(1,0, 'LOTE: ', align='L')
        pdf.set_x(2.8)
        pdf.cell(1,0, pallobj.articulo_lote, align='L')
        #vencimiento
        pdf.set_y(3)
        pdf.set_x(0.6)
        pdf.cell(1,0, 'VENCIMIENTO: ', align='L')
        pdf.set_x(2.8)
        pdf.cell(1,0, pallobj.articulo_fecha_vencimiento.strftime('%d/%m/%Y'), align='L')
        #cajas
        pdf.set_y(3.4)
        pdf.set_x(0.6)
        pdf.cell(1,0, 'CAJAS: ', align='L')
        pdf.set_x(2.8)
        pdf.cell(1,0, str(pallobj.pall_articulo_cajas), align='L')
        #unidades
        pdf.set_x(3.5)
        pdf.cell(1,0, 'UNIDADES:', align='L')
        pdf.set_x(5.2)
        pdf.cell(1,0, str(pallobj.pall_articulo_unidades), align='L')
        #totales
        pdf.set_x(5.6)
        pdf.cell(1,0, 'TOTAL:', align='L')
        pdf.set_x(6.7)
        pdf.cell(1,0, str(pallobj.get_pall_cantidad()), align='L')
        #averiados
        pdf.set_y(3.8)
        pdf.set_x(0.6)
        pdf.cell(1,0, 'AVERIADOS: ', align='L')
        pdf.set_x(2.8)
        pdf.cell(1,0, str(pallobj.pall_averiados_cantidad_cajas), align='L')
        #averiados unidades
        pdf.set_x(3.5)
        pdf.cell(1,0, 'UNIDADES:', align='L')
        pdf.set_x(5.2)
        pdf.cell(1,0, str(pallobj.pall_averiados_cantidad_sueltas), align='L')
        #totales averiados
        pdf.set_x(5.6)
        pdf.cell(1,0, 'TOTAL:', align='L')
        pdf.set_x(6.7)
        pdf.cell(1,0, str(pallobj.get_pall_cantidad_averiados()), align='L')
        #linea
        pdf.line(0.5, 4, 9.5, 4)
        #seccion producto

        barra_articulo = Code128Encoder(str(pallobj.articulo_cod),options={'height':60, 'label_border': 1, 'bottom_border': 5})
        barra_articulo.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), bar_width=1)
        pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_cod), x=0.5, y=4.1)
        #linea vertical, separa codigo barra articulo de la descripcion del articulo
        pdf.line(3.1, 4, 3.1, 6.5)
        #descripcion del articulo
        pdf.set_y(4.3)
        pdf.set_x(3.2)
        pdf.cell(1,0, 'ARTICULO:', align='L')
        pdf.set_x(4.8)
        pdf.cell(1,0, str(pallobj.articulo_cod), align='L')
        pdf.set_font('Arial',style='',size=10)
        pdf.set_y(4.5)
        pdf.set_x(3.2)
        pdf.multi_cell(6.5,0.5, pallobj.articulo_descripcion, align='L')
        #linea de cierre
        pdf.line(0.5, 6.5, 9.5, 6.5)
        pdf.set_font('Arial',style='',size=8)
        #vencimiento
        barra_vencimiento = Code128Encoder(str(pallobj.articulo_fecha_vencimiento.strftime('%d/%m/%Y')),options={'height':40, 'label_border': 1, 'bottom_border': 5})
        barra_vencimiento.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_fecha_vencimiento.strftime('%d%m%Y')), bar_width=1)
        pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.articulo_fecha_vencimiento.strftime('%d%m%Y')), x=0.5, y=6.6, type='png')
        pdf.set_y(6.9)
        pdf.set_x(5.6)
        pdf.cell(1,0, 'VENCIMIENTO', align='L')
        #ultima linea de cierre
        pdf.line(0.5, 8.2, 9.5, 8.2)
        #pallet
        barra_pallet = Code128Encoder(str(pallobj.pall_numero),options={'height':65, 'label_border': 1, 'bottom_border': 5, 'show_label': False})
        barra_pallet.save('%s/%s.png' % (ETIQUETA_DIR, pallobj.pall_numero), bar_width=1)
        pdf.image('%s/%s.png' % (ETIQUETA_DIR, pallobj.pall_numero), x=0, y=8.3, type='png', w=10, h=4)


        cups_server = CupsServer(settings.CUPS_ADMIN[0],
                             settings.CUPS_ADMIN[1]
                             )
        cups_server.modo_admin()
        pdf.set_font('Arial',style='',size=7)

        for ib in range(4):
            a = ib + 1
            pdf_temp = copy.deepcopy(pdf)
            pdf_temp.set_y(2.9)
            pdf_temp.set_x(8.5)

            if reimpresion:
                labelinte = 'COPIA %s/4' % a
                pdf_temp.cell(1,0, labelinte, align='R')
            else:
                labelinte = 'ORIGINAL %s/4' % a
                pdf_temp.cell(1,0, labelinte, align='R')

            if not pallobj.pallet_completo_010:
                pdf_temp.set_y(3.2)
                pdf_temp.set_x(8.5)
                pdf_temp.cell(1,0, 'INCOMPLETO', align='R')

            pdf_temp.output('%s/%s_%s.pdf' % (ETIQUETA_DIR, pallobj.pall_numero, a))
            with Image(filename="%s/%s_%s.pdf" % (ETIQUETA_DIR, pallobj.pall_numero, a), resolution=(250,250)) as img:
                img.save(filename="%s/%s_%s.jpg" % (ETIQUETA_DIR, pallobj.pall_numero, a))
            cups_server.imprimir_trabajo('Zebra_TLP2844', "%s/%s_%s.jpg" % (ETIQUETA_DIR, pallobj.pall_numero, a), {})

        pdf.close()
        if reimpresion:
            pallobj.reimpresion_etiquetado_010=True
            pallobj.reimpresion_etiquetado_010_por = usuario
            pallobj.reimpresion_etiquetado_010_fecha = ahora
            pallobj.reimpresion_etiquetado_010_hora = ahora
            pallobj.save()

        pallobj.etiquetado_09=True
        pallobj.etiquetado_09_por = usuario
        pallobj.etiquetado_09_fecha = ahora
        pallobj.etiquetado_09_hora = ahora
        pallobj.save()
예제 #18
0
def report(thandle, gain_tweets, loss_tweets):
    """
    Write report.
    """
    from fpdf import FPDF
    import textwrap

    print('Writing report...')
    pdf = FPDF()

    # Add a page
    pdf.add_page()

    # set style and size of font
    # that you want in the pdf
    pdf.set_font("Arial", size=16)

    # create a cell
    pdf.cell(200,
             10,
             txt='Ads that likely caused some loss of Followers:\n\n',
             ln=1,
             align='L')
    pdf.cell(200, 10, txt='', ln=2, align='L')

    # add another cell
    pdf.set_font("Arial", size=14)
    tweet_string = ''
    fact = 3
    count = 0
    tweets = []
    while count < fact:
        random.shuffle(loss_tweets)
        rand_tweet = loss_tweets[-1]
        tweets.append(rand_tweet)
        mask = [(tweet != rand_tweet) for tweet in loss_tweets]
        loss_tweets = [
            loss_tweets[i] for i in range(len(loss_tweets)) if mask[i]
        ]
        count += 1

    for i, d in enumerate(tweets):
        string_encode = d.encode('ascii', 'ignore')
        string_decode = string_encode.decode()
        d = textwrap.wrap(string_decode, width=65)

        for j in d:
            pdf.cell(200, 10, txt=j, ln=fact, align='L')
            fact += 0.5
        pdf.cell(200, 10, txt='', ln=fact, align='L')
        fact += 1

    pdf.output('{}/lossy_tweets.pdf'.format(thandle))
    pdf.close()

    pdf = FPDF()

    dupes_gain = set(
        [x for n, x in enumerate(gain_tweets) if x in gain_tweets[:n]])

    # Add a page
    pdf.add_page()

    # set style and size of font
    # that you want in the pdf
    pdf.set_font("Arial", size=16)

    # create a cell
    pdf.cell(200,
             10,
             txt='Ads that likely caused some gain in Followers:\n\n',
             ln=1,
             align='L')
    pdf.cell(200, 10, txt='', ln=2, align='L')

    # add another cell
    pdf.set_font("Arial", size=14)
    tweet_string = ''
    fact = 3
    count = 0
    tweets = []
    while count < fact:
        random.shuffle(gain_tweets)
        rand_tweet = gain_tweets[-1]
        tweets.append(rand_tweet)
        mask = [(tweet != rand_tweet) for tweet in gain_tweets]
        gain_tweets = [
            gain_tweets[i] for i in range(len(gain_tweets)) if mask[i]
        ]
        count += 1

    for i, d in enumerate(tweets):
        string_encode = d.encode('ascii', 'ignore')
        string_decode = string_encode.decode()
        d = textwrap.wrap(string_decode, width=65)

        for j in d:
            pdf.cell(200, 10, txt=j, ln=fact, align='L')
            fact += 0.5
        pdf.cell(200, 10, txt='', ln=fact, align='L')
        fact += 1

    pdf.output('{}/gainy_tweets.pdf'.format(thandle))
    pdf.close()

    print('Done!\n')
예제 #19
0
파일: document.py 프로젝트: ftc92/mp-django
    def get_signed_doc(self, pdf, signatures):

        # pth = tempfile.gettempdir()
        # curr_dir = os.path.dirname(__file__)
        # pth = curr_dir.replace('models', 'doc_signs')
        #
        # file = pdf
        # pdf_doc = base64.b64decode(file)
        # # f = base64.decodestring(file)
        #
        # fobj = tempfile.NamedTemporaryFile(delete=False)
        # fname1 = fobj.name
        # fobj.write(pdf_doc)
        # fobj.close()
        pth = MEDIA_ROOT + "/" + pdf.name

        input = PdfFileReader(open(pth, "rb"))
        # Addition of code for orientation correction Asfand
        pageValue = input.getPage(0)
        pageOrientation = pageValue.get('/Rotate')
        page = input.getPage(0).mediaBox
        zAxis = page.getUpperRight_x()
        yAxis = page.getUpperLeft_x()
        width = int(zAxis - yAxis)

        height = int(page.getUpperRight_y() - page.getLowerRight_y())
        solution = [width, height]
        if width > height or pageOrientation == 90:
            if height > width:
                orientation = 'L'
            else:
                orientation = 'P'
        elif pageOrientation == 0 or pageOrientation == 180 or pageOrientation == None:
            if width > height:
                orientation = 'L'
            else:
                orientation = 'P'

        output = PdfFileWriter()
        pdf = FPDF(orientation, 'pt', solution)
        pdf.add_page(orientation=orientation)
        # signatures = signatures.sorted(key=lambda r: r.page)
        current_page = 1
        sign_pages = []
        for s in signatures:
            if s.image:
                pg = s.page
                if pg != current_page:
                    for i in range(pg - current_page):
                        pdf.add_page(orientation=orientation)
                left = (s.left / 100) * width
                top = (s.top / 100) * height

                if s.zoom > width:
                    diff = s.zoom - width
                    perc = (width / s.zoom)
                    w = s.width * perc
                    h = s.height * perc

                if s.zoom < width:
                    diff = width - s.zoom
                    perc = (diff / s.zoom)
                    plus = perc * s.width
                    w = s.width + plus
                    plus = perc * s.height
                    h = s.height + plus
                if s.zoom == width:
                    w = s.width
                    h = s.height

                pdf.image(MEDIA_ROOT + "/" + s.image.name,
                          x=left,
                          y=top,
                          w=w,
                          h=h)
                if self.send_to_all:
                    pdf.set_xy(left + 50, top + h)
                    # pdf.ln(5)
                    pdf.set_font('Arial', 'U', 15)
                    # Special case, we have restricted our users to read super admin
                    try:
                        sign_name = s.user.username
                    except:
                        sign_name = 'Root'
                    pdf.cell(5, 5, sign_name)
                    date = datetime.datetime.today().strftime('%b,%d  %Y')
                    # pdf.ln(20)
                    pdf.set_xy(left + 50, top + h + 20)
                    pdf.cell(5, 5, date)
                    # if ip:
                    #     pdf.ln(25)
                    #     pdf.cell(5, 5, ip)
                current_page = pg
                sign_pages.append(pg)
        signature_only_pdf_path = MEDIA_ROOT + "/files/signature-pdf-" + str(
            randint(1, 99)) + ".pdf"
        pdf.output(signature_only_pdf_path, "F")
        pdf.close()

        signaturepdf = PdfFileReader(open(signature_only_pdf_path, "rb"))
        for page_number in range(input.getNumPages()):
            page = input.getPage(page_number)
            if page_number + 1 in sign_pages:
                sign_page = signaturepdf.getPage(page_number)
                if sign_page:
                    page.mergePage(sign_page)
            output.addPage(input.getPage(page_number))

        output_pdf_path = MEDIA_ROOT + "/files/signed-doc-output-" + str(
            randint(1, 99)) + ".pdf"
        with open(output_pdf_path, "wb") as outputStream:
            output.write(outputStream)
        res = open(output_pdf_path, 'rb')
        return res
예제 #20
0
def pdf_creator(data):
    '''receive some data and create a pdf report with a summary of information'''
    width = 210
    today = date.today()

    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)

    # header display
    pdf.image('../images/germany_flag1.png')
    pdf.image('../images/header_pdf.png', 70, 10)
    #pdf.cell(f'Date: {today}')

    # descriptive text
    pdf.set_font('Arial', 'BU', 18)
    pdf.cell(0.1, 20, 'Data Resume:')
    pdf.set_font('Arial', 'BU', 12)
    pdf.cell(0.1, 40, f'Number of Houses:')
    pdf.set_font('Arial', size=12)
    pdf.cell(0.1, 55, f'{data.shape[0]} houses')

    pdf.set_font('Arial', 'BU', 12)
    pdf.cell(0.1, 70, f'Rent Price:')
    pdf.set_font('Arial', size=12)
    pdf.cell(0.1, 85, f'AVG - {data["montly_rent"].mean():.2f} EUR')
    pdf.cell(0.1, 95, f'MAX - {data["montly_rent"].max():.2f} EUR')
    pdf.cell(70, 105, f'MIN - {data["montly_rent"].min():.2f} EUR')

    pdf.set_font('Arial', 'BU', 12)
    pdf.cell(0.1, 70, 'Size:')
    pdf.set_font('Arial', size=12)
    pdf.cell(0.1, 85, f'AVG - {data["size"].mean():.2f}m²')
    pdf.cell(0.1, 95, f'MAX - {data["size"].max():.2f}m²')
    pdf.cell(60, 105, f'MIN - {data["size"].min():.2f}m²')

    pdf.set_font('Arial', 'BU', 12)
    pdf.cell(0.1, 70, 'Pets:')
    pdf.set_font('Arial', size=12)
    pdf.cell(0.1, 85, f'Not Allowed - {len(data[data["pets"] == "Pets not allowed"])} houses')
    pdf.cell(0.1, 95, f'Negotiable - {len(data[data["pets"] == "Pets negotiable"])} houses')
    pdf.cell(-132, 105, f'Allowed - {len(data[data["pets"] == "Pets allowed"])} houses')

    # histograms
    pdf.set_font('Arial', 'BU', 18)
    pdf.cell(0.1, 126, 'Data Histograms:')

    # first histplot
    hist_plot(data, 'montly_rent', 'MONTLY RENT')
    pdf.image('../images/montly_rent.png', 4, 126, width/2)

    # second histplot
    hist_plot(data, 'size', 'SIZE')
    pdf.image('../images/size.png', width/2, 126, width/2)

    # third histplot
    hist_plot(data, 'm2_value', 'M² VALUE')
    pdf.image('../images/m2_value.png', 4, 200, width/2)

    # fourth histplot
    hist_plot(data, 'pets', 'PETS')
    pdf.image('../images/pets.png', width/2, 200, width/2)

    # second page
    pdf.add_page()
    # header display
    pdf.image('../images/germany_flag1.png')
    pdf.image('../images/header_pdf.png', 70, 10)

    #====================
    # graphs
    #====================
    pdf.set_font('Arial', 'BU', 18)
    pdf.cell(0.1, 20, 'Data Graphs:')

    pdf.ln(20)
    montly_plot(data)
    pdf.image('../images/montly_rent_barplot.png', x=0, h=70)

    pdf.ln(5)
    m2_plot(data)
    pdf.image('../images/m2_barplot.png', x=0, h=70)

    pdf.ln(2)
    pet_plot(data)
    pdf.image('../images/pet_plot.png', x=25, h=55)

    pdf.set_author('Felipe Demenech Vasconcelos')
    pdf.close()
    pdf.output('../reports/rent_houses_germany.pdf', 'F')

    return pdf.output(dest='S')
예제 #21
0
    # Save the figure
    fig.savefig(file1)

    # Saves the result pdf
    pdf.output(file2)

    # Adds the files to the bin list
    pdfDelete.append(file1)
    pdfDelete.append(file2)

    # List of pdfs for merging
    pdfs = [file1, file2]

    plt.close(fig)
    pdf.close()
    file.close()

    # Adds the 2 pdfs together
    for pdf in pdfs:
        merger.append(pdf)

# Saves the merged file with the set save file name
merger.write(saveFile)

merger.close()

# Deletes the pdfs
for pdf in pdfDelete:
    os.remove(pdf)
예제 #22
0
def png_to_pdf(png):
    pdf = FPDF()
    pdf.add_page()
    pdf.image(png, 0, 0, 210, 300)
    pdf.output(png.replace('.png', '_temp_darkmode.pdf'), "F")
    pdf.close()
예제 #23
0
def processKinds(smena_no, date_smena, file_from, file_to, s, po):

    DATE = "D"
    ADDRESS = "K"
    NAME = "C"
    RODITEL = "M"
    MINISTERSTVO = "Q"
    SUMMA = "P"

    with open("pos.json") as json_file:
        position = json.load(json_file)["pos"]

    pdf = FPDF(orientation="L", unit="mm", format="A4")
    pdf.add_font("KEK", '', 'times-new-roman.ttf', uni=True)

    logging.info(file_from)
    logging.info(file_to)

    workbook = load_workbook(filename=file_from)
    sheet = workbook.active
    kinds = []

    i = 10
    while sheet[NAME + str(i)].value:
        kind = {}
        kind["smena_no"] = smena_no
        kind["s_d"], kind["s_m"], kind["s_g"] = s
        kind["po_d"], kind["po_m"], kind["po_g"] = po

        flp = sheet[NAME + str(i)].value.split()
        if len(flp) == 2:
            kind["last_name"], kind["first_name"] = flp
            kind["patronymic"] = ""
        elif len(flp) == 3:
            kind["last_name"], kind["first_name"], kind["patronymic"] = flp
        else:
            messagebox.showerror("С этой фамилией что-то не так: ",
                                 sheet[NAME + str(i)].value)

        kind["date"] = sheet[DATE + str(i)].value

        #new
        try:
            parents = sheet[RODITEL + str(i)].value
            if parents:
                parents = [
                    v
                    for v in re.split("\n|,|  ", sheet[RODITEL + str(i)].value)
                    if v
                ]
                if len(parents) > 1:
                    kind["parent1"], kind["parent2"] = parents
                else:
                    kind["parent1"] = parents[0]
                    kind["parent2"] = ""
            else:
                kind["parent1"] = ""
                kind["parent2"] = ""
        except:
            messagebox.showerror("Что-то не так с родителями:",
                                 sheet[RODITEL + str(i)].value)
            logging.error(re.split("\n|,|  ", sheet[RODITEL + str(i)].value))

        ministerstvo = sheet[MINISTERSTVO + str(i)].value
        if ministerstvo:
            if len(ministerstvo) > 66:
                kind["ministerstvo1"], kind["ministerstvo2"] = splitLineToTwo(
                    ministerstvo, 66, " ")
            else:
                kind["ministerstvo1"] = ministerstvo
                kind["ministerstvo2"] = ""
        else:
            kind["ministerstvo1"] = ""
            kind["ministerstvo2"] = ""
        # Адрес
        address = sheet[ADDRESS + str(i)].value
        if address:
            if len(address) > 40:
                kind["parent_addr1"], kind["parent_addr2"] = splitLineToTwo(
                    address, 40, ",")
            else:
                kind["parent_addr1"] = address
                kind["parent_addr2"] = ""
        else:
            kind["parent_addr1"] = ""
            kind["parent_addr2"] = ""

        kind["age"] = kind["date"].strftime("%d.%m.%Y") + " (" + get_age(
            kind["date"], date_smena) + " лет)"
        summa = sheet[SUMMA + str(i)].value
        if summa:
            kind["summa"] = summa
        else:
            kind["summa"] = ""
        kind["z"] = "Ƶ"
        kinds.append(kind)
        i += 1

    for kind in kinds:
        printKind(kind, pdf, position)
    pdf.output(file_to)
    pdf.close()
    messagebox.showinfo("Ура!", "Путёвки созданы!")
예제 #24
0
    def run(self):
        # See if the data is complete:
        flag2 = False
        flag3 = False

        if self.Hospital_length_of_stay_mean!=0 and self.Hospital_length_of_stay_std!=0 and self.Daily_arrival_rate!=[] and self.Percentage_hospitalized!=0:
            flag2 = True
        if self.Hospital_length_of_stay_mean!=0 and self.Hospital_length_of_stay_std!=0  and self.Daily_arrival_rate!=[] and self.Percentage_icu!=0:
            flag3 = True

        processbartotallength = flag2 * len(
            self.Daily_arrival_rate) + flag3 * len(self.Daily_arrival_rate)

        if flag2 == True:
            mu = log(
                square(self.Hospital_length_of_stay_mean) / sqrt(
                    square(self.Hospital_length_of_stay_mean) +
                    square(self.Hospital_length_of_stay_mean)))
            stddev = sqrt(
                log(1 + square(self.Hospital_length_of_stay_mean) /
                    square(self.Hospital_length_of_stay_mean)))
            ArrivalRate = array(self.Daily_arrival_rate, dtype=float)
            ArrivalRate = ArrivalRate * self.Percentage_hospitalized
            TotalTimeLength = ArrivalRate.size
            initial_condition = self.Hospital_initial_condition

            step = 1
            t = 1
            tlist = []
            tlist = range(1, TotalTimeLength + 1)
            mt = []
            mt5 = []
            mt95 = []
            pt25 = []
            pt50 = []
            pt75 = []
            pt100 = []
            pt125 = []
            pt150 = []
            pt175 = []
            error = []
            st = []
            stl = []

            while t <= TotalTimeLength:
                ans, err = quad(f,
                                0,
                                t,
                                args=(t, mu, stddev, ArrivalRate),
                                limit=400)
                total_probability = 0
                probability_still_in_system = 1 - rs(
                    t, mu, stddev, self.Hospital_length_of_stay_mean)
                # Calculate the mean
                mttemp = initial_condition * probability_still_in_system + ans
                mt.append(mttemp)
                # Calculate the numerical distribution:
                temptotal = 0
                flag = [False, False]
                tempcdf = 0
                while tempcdf <= 0.99:
                    i = 0
                    if t <= self.Maximum_Hospital_stay:
                        while i <= temptotal and i <= initial_condition:
                            if i <= initial_condition:
                                tempcdf = tempcdf + binom.pmf(
                                    i, initial_condition,
                                    probability_still_in_system) * poisson.pmf(
                                        (temptotal - i), ans)
                            i = i + 1
                    else:
                        tempcdf = poisson.cdf(temptotal, ans)
                    if tempcdf >= 0.05 and flag[0] == False:
                        if temptotal - 1 > 0:
                            tempq = temptotal - 1
                        else:
                            tempq = 0
                        mt5.append(tempq)
                        flag[0] = True
                    if tempcdf >= 0.95 and flag[1] == False:
                        mt95.append(temptotal)
                        flag[1] = True
                    QApplication.processEvents()
                    if temptotal == 25:
                        pt25.append(1 - tempcdf)
                    if temptotal == 50:
                        pt50.append(1 - tempcdf)
                    if temptotal == 75:
                        pt75.append(1 - tempcdf)
                    if temptotal == 100:
                        pt100.append(1 - tempcdf)
                    if temptotal == 125:
                        pt125.append(1 - tempcdf)
                    if temptotal == 150:
                        pt150.append(1 - tempcdf)
                    if temptotal == 175:
                        pt175.append(1 - tempcdf)
                    temptotal = temptotal + 1
                temptotal = temptotal - 1
                if temptotal < 25:
                    pt25.append(float(0))
                if temptotal < 50:
                    pt50.append(float(0))
                if temptotal < 75:
                    pt75.append(float(0))
                if temptotal < 100:
                    pt100.append(float(0))
                if temptotal < 125:
                    pt125.append(float(0))
                if temptotal < 150:
                    pt150.append(float(0))
                if temptotal < 175:
                    pt175.append(float(0))
                t = t + step
                QApplication.processEvents()
                self.ProgressBar.setValue(
                    ceil((t) / processbartotallength * 100))

            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
            ax.plot(tlist, mt)
            ax.set_title('Expected Number and 95% Band')
            ax.fill_between(tlist, mt5, mt95, color='b', alpha=0.1)
            ax.set_ylabel("Hospital Census")
            ax.set_xlabel("Days")
            fig.savefig('temp2.png')

            temp2 = QPixmap("temp2.png")
            self.Hospital_Graph_Label.setPixmap(temp2.scaled(480, 360))

            TableData = PrettyTable()
            TableData.field_names = [
                "Num Pts", "10 Days", "20 Days", "30 Days", "40 Days",
                "50 Days", "60 Days", "70 Days", "80 Days", "90 Days"
            ]
            TableData.add_row([
                "25 pts",
                maxc(pt25[0:10]),
                maxc(pt25[0:20]),
                maxc(pt25[0:30]),
                maxc(pt25[0:40]),
                maxc(pt25[0:50]),
                maxc(pt25[0:60]),
                maxc(pt25[0:70]),
                maxc(pt25[0:80]),
                maxc(pt25[0:90])
            ])
            TableData.add_row([
                "50 pts",
                maxc(pt50[0:10]),
                maxc(pt50[0:20]),
                maxc(pt50[0:30]),
                maxc(pt50[0:40]),
                maxc(pt50[0:50]),
                maxc(pt50[0:60]),
                maxc(pt50[0:70]),
                maxc(pt50[0:80]),
                maxc(pt50[0:90])
            ])
            TableData.add_row([
                "75 pts",
                maxc(pt75[0:10]),
                maxc(pt75[0:20]),
                maxc(pt75[0:30]),
                maxc(pt75[0:40]),
                maxc(pt75[0:50]),
                maxc(pt75[0:60]),
                maxc(pt75[0:70]),
                maxc(pt75[0:80]),
                maxc(pt75[0:90])
            ])
            TableData.add_row([
                "100 pts",
                maxc(pt100[0:10]),
                maxc(pt100[0:20]),
                maxc(pt100[0:30]),
                maxc(pt100[0:40]),
                maxc(pt100[0:50]),
                maxc(pt100[0:60]),
                maxc(pt100[0:70]),
                maxc(pt100[0:80]),
                maxc(pt100[0:90])
            ])
            TableData.add_row([
                "125 pts",
                maxc(pt125[0:10]),
                maxc(pt125[0:20]),
                maxc(pt125[0:30]),
                maxc(pt125[0:40]),
                maxc(pt125[0:50]),
                maxc(pt125[0:60]),
                maxc(pt125[0:70]),
                maxc(pt125[0:80]),
                maxc(pt125[0:90])
            ])
            TableData.add_row([
                "150 pts",
                maxc(pt150[0:10]),
                maxc(pt150[0:20]),
                maxc(pt150[0:30]),
                maxc(pt150[0:40]),
                maxc(pt150[0:50]),
                maxc(pt150[0:60]),
                maxc(pt150[0:70]),
                maxc(pt150[0:80]),
                maxc(pt150[0:90])
            ])
            TableData.add_row([
                "175 pts",
                maxc(pt175[0:10]),
                maxc(pt175[0:20]),
                maxc(pt175[0:30]),
                maxc(pt175[0:40]),
                maxc(pt175[0:50]),
                maxc(pt175[0:60]),
                maxc(pt175[0:70]),
                maxc(pt175[0:80]),
                maxc(pt175[0:90])
            ])

            header, data = get_data_from_prettytable(TableData)

            pdf = FPDF()
            # Font style
            pdf.set_font("Arial", size=9)
            epw = pdf.w - 2 * pdf.l_margin  # Witdh of document
            col_width = pdf.w / 10.5  # Column width in table
            row_height = pdf.font_size * 1.5  # Row height in table
            spacing = 1.3

            pdf.add_page()
            pdf.set_font("Arial", size=20)
            pdf.cell(epw, 0.0, 'COVID-CAT Report for Hospital',
                     align='C')  # create title cell
            pdf.ln(row_height * spacing)  # Define title line style

            pdf.image("temp2.png", w=epw, h=epw * 0.75)

            pdf.set_font("Arial", size=15)
            pdf.cell(
                epw,
                pdf.font_size * spacing,
                'Probability of exceeding a given number of patients within:',
                0,
                1,
                align='L')

            pdf.set_font("Arial", size=9)
            # Add header
            for item in header:  # for each column
                pdf.cell(
                    col_width,
                    row_height * spacing,  # Add a new cell
                    txt=item,
                    border=1)
            pdf.ln(row_height * spacing)  # New line after header

            for row in data:  # For each row of the table
                for item in row:  # For each cell in row
                    pdf.cell(
                        col_width,
                        row_height * spacing,  # Add cell
                        txt=item,
                        border=1)
                pdf.ln(row_height * spacing)  # Add line at the end of row

        if flag3 == True:
            mu = log(
                square(self.ICU_length_of_stay_mean) / sqrt(
                    square(self.ICU_length_of_stay_mean) +
                    square(self.ICU_length_of_stay_mean)))
            stddev = sqrt(
                log(1 + square(self.ICU_length_of_stay_mean) /
                    square(self.ICU_length_of_stay_mean)))
            ArrivalRate = array(self.Daily_arrival_rate, dtype=float)
            ArrivalRate = ArrivalRate * self.Percentage_icu
            TotalTimeLength = ArrivalRate.size
            initial_condition = self.ICU_initial_condition

            step = 1
            t = 1
            tlist = []
            tlist = range(1, TotalTimeLength + 1)
            zeros = [0 for i in tlist]
            mt = []
            mt5 = []
            mt95 = []
            pt15 = []
            pt20 = []
            pt25 = []
            pt30 = []
            pt35 = []
            pt40 = []
            pt45 = []
            error = []
            st = []
            stl = []

            while t <= TotalTimeLength:
                ans, err = quad(f,
                                0,
                                t,
                                args=(t, mu, stddev, ArrivalRate),
                                limit=500)
                total_probability = 0
                probability_still_in_system = 1 - rs(
                    t, mu, stddev, self.ICU_length_of_stay_mean)
                # Calculate the mean
                mttemp = initial_condition * probability_still_in_system + ans
                mt.append(mttemp)
                # Calculate the numerical distribution:
                temptotal = 0
                flag = [False, False]
                tempcdf = 0
                while tempcdf <= 0.99:
                    i = 0
                    if t <= self.Maximum_ICU_stay:
                        while i <= temptotal and i <= initial_condition:
                            if i <= initial_condition:
                                tempcdf = tempcdf + binom.pmf(
                                    i, initial_condition,
                                    probability_still_in_system) * poisson.pmf(
                                        (temptotal - i), ans)
                            i = i + 1
                    else:
                        tempcdf = poisson.cdf(temptotal, ans)
                    if tempcdf >= 0.05 and flag[0] == False:
                        if temptotal - 1 > 0:
                            tempq = temptotal - 1
                        else:
                            tempq = 0
                        mt5.append(tempq)
                        flag[0] = True
                    if tempcdf >= 0.95 and flag[1] == False:
                        mt95.append(temptotal)
                        flag[1] = True
                    QApplication.processEvents()
                    if temptotal == 15:
                        pt15.append(1 - tempcdf)
                    if temptotal == 20:
                        pt20.append(1 - tempcdf)
                    if temptotal == 25:
                        pt25.append(1 - tempcdf)
                    if temptotal == 30:
                        pt30.append(1 - tempcdf)
                    if temptotal == 35:
                        pt35.append(1 - tempcdf)
                    if temptotal == 40:
                        pt40.append(1 - tempcdf)
                    if temptotal == 45:
                        pt45.append(1 - tempcdf)
                    temptotal = temptotal + 1
                temptotal = temptotal - 1
                if temptotal < 15:
                    pt15.append(float(0))
                if temptotal < 20:
                    pt20.append(float(0))
                if temptotal < 25:
                    pt25.append(float(0))
                if temptotal < 30:
                    pt30.append(float(0))
                if temptotal < 35:
                    pt35.append(float(0))
                if temptotal < 40:
                    pt40.append(float(0))
                if temptotal < 45:
                    pt45.append(float(0))
                t = t + step
                QApplication.processEvents()
                self.ProgressBar.setValue(
                    ceil((t + flag2 * len(self.Daily_arrival_rate)) /
                         processbartotallength * 100))

            fig = plt.figure()
            ax = fig.add_subplot(1, 1, 1)
            ax.plot(tlist, mt)
            ax.set_title('Expected Number and 95% Band')
            ax.fill_between(tlist, mt5, mt95, color='b', alpha=0.1)
            ax.set_ylabel("ICU Census")
            ax.set_xlabel("Days")
            fig.savefig('temp3.png')

            temp3 = QPixmap("temp3.png")
            self.ICU_Graph_Label.setPixmap(temp3.scaled(480, 360))

            TableData = PrettyTable()
            TableData.field_names = [
                "Num Pts", "10 Days", "20 Days", "30 Days", "40 Days",
                "50 Days", "60 Days", "70 Days", "80 Days", "90 Days"
            ]
            TableData.add_row([
                "15 pts",
                maxc(pt15[0:10]),
                maxc(pt15[0:20]),
                maxc(pt15[0:30]),
                maxc(pt15[0:40]),
                maxc(pt15[0:50]),
                maxc(pt15[0:60]),
                maxc(pt15[0:70]),
                maxc(pt15[0:80]),
                maxc(pt15[0:90])
            ])
            TableData.add_row([
                "20 pts",
                maxc(pt20[0:10]),
                maxc(pt20[0:20]),
                maxc(pt20[0:30]),
                maxc(pt20[0:40]),
                maxc(pt20[0:50]),
                maxc(pt20[0:60]),
                maxc(pt20[0:70]),
                maxc(pt20[0:80]),
                maxc(pt20[0:90])
            ])
            TableData.add_row([
                "25 pts",
                maxc(pt25[0:10]),
                maxc(pt25[0:20]),
                maxc(pt25[0:30]),
                maxc(pt25[0:40]),
                maxc(pt25[0:50]),
                maxc(pt25[0:60]),
                maxc(pt25[0:70]),
                maxc(pt25[0:80]),
                maxc(pt25[0:90])
            ])
            TableData.add_row([
                "30 pts",
                maxc(pt30[0:10]),
                maxc(pt30[0:20]),
                maxc(pt30[0:30]),
                maxc(pt30[0:40]),
                maxc(pt30[0:50]),
                maxc(pt30[0:60]),
                maxc(pt30[0:70]),
                maxc(pt30[0:80]),
                maxc(pt30[0:90])
            ])
            TableData.add_row([
                "35 pts",
                maxc(pt35[0:10]),
                maxc(pt35[0:20]),
                maxc(pt35[0:30]),
                maxc(pt35[0:40]),
                maxc(pt35[0:50]),
                maxc(pt35[0:60]),
                maxc(pt35[0:70]),
                maxc(pt35[0:80]),
                maxc(pt35[0:90])
            ])
            TableData.add_row([
                "40 pts",
                maxc(pt40[0:10]),
                maxc(pt40[0:20]),
                maxc(pt40[0:30]),
                maxc(pt40[0:40]),
                maxc(pt40[0:50]),
                maxc(pt40[0:60]),
                maxc(pt40[0:70]),
                maxc(pt40[0:80]),
                maxc(pt40[0:90])
            ])
            TableData.add_row([
                "45 pts",
                maxc(pt45[0:10]),
                maxc(pt45[0:20]),
                maxc(pt45[0:30]),
                maxc(pt45[0:40]),
                maxc(pt45[0:50]),
                maxc(pt45[0:60]),
                maxc(pt45[0:70]),
                maxc(pt45[0:80]),
                maxc(pt45[0:90])
            ])
            header, data = get_data_from_prettytable(TableData)

            # Font style
            pdf.set_font("Arial", size=9)
            epw = pdf.w - 2 * pdf.l_margin  # Witdh of document
            col_width = pdf.w / 10.5  # Column width in table
            row_height = pdf.font_size * 1.5  # Row height in table
            spacing = 1.3

            pdf.add_page()
            pdf.set_font("Arial", size=20)
            pdf.cell(epw, 0.0, 'COVID-CAT Report for ICU',
                     align='C')  # create title cell
            pdf.ln(row_height * spacing)  # Define title line style

            pdf.image("temp3.png", w=epw, h=epw * 0.75)

            pdf.set_font("Arial", size=15)
            pdf.cell(
                epw,
                pdf.font_size * spacing,
                'Probability of exceeding a given number of patients within:',
                0,
                1,
                align='L')

            pdf.set_font("Arial", size=9)
            # Add header
            for item in header:  # for each column
                pdf.cell(
                    col_width,
                    row_height * spacing,  # Add a new cell
                    txt=item,
                    border=1)
            pdf.ln(row_height * spacing)  # New line after header

            for row in data:  # For each row of the table
                for item in row:  # For each cell in row
                    pdf.cell(
                        col_width,
                        row_height * spacing,  # Add cell
                        txt=item,
                        border=1)
                pdf.ln(row_height * spacing)  # Add line at the end of row

        if flag2 == True or flag3 == True:
            try:
                pdf.output('Report_Hospital_and_ICU.pdf')  # Create pdf file
                pdf.close()  # Close file
            except:
                QMessageBox.warning(
                    self, "Error",
                    "Couldn't Create PDF. Please close the PDF file of report")
        else:
            QMessageBox.warning(self, "Error", "Not Enough Data")