Example #1
0
def pruning(dictLD):
	pdf = FPDF() # create new PDF
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "LD Pruning", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)
	pdf.set_font('Arial', '', 12)
	pdf.multi_cell(0, 5, 'Pruning SNPs based upon linkage equilibrium is senstive to race/ethnicity.  Therefore, LD-pruning is performed \
		independently on each ethnic group in the data set.', 0, 1, 'J')
	pdf.multi_cell(0, 5, '\n', 0, 1, 'J')
	pdf.set_font('Arial', 'B', 16)
	pdf.set_fill_color(200)
	
	# iterate through all ethnic groups for LD pruning stats
	for key, value in dictLD.iteritems():
		pdf.multi_cell(0, 8, str(key), 1, 'L', True)
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs analyzed:  ' +  str(value[0]), 1, 1, 'L')
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs Passing:  ' +  str(value[1]) + ' (' + str("%.2f" % round((float(value[1])/float(value[0]))*100, 2)) + '%)', 1, 1, 'L')
		pdf.multi_cell(0, 8, '\n\n', 0, 1, 'J')


	return pdf
Example #2
0
def write_to_pdf(data: dict, filename: str):
    pdf = FPDF()
    effective_page_width = pdf.w - 2 * pdf.l_margin
    pdf.compress = False
    pdf.add_page()
    pdf.add_font("TimesNewRoman", '', 'TimesNewRoman.ttf', uni=True)
    pdf.set_font("TimesNewRoman", size=30)
    pdf.cell(w=0, txt=data['title'])
    pdf.ln(30)
    pdf.set_line_width(1)
    pdf.set_draw_color(255, 0, 0)
    for index_news, news_dict in enumerate(data['items']):
        pdf.set_font("TimesNewRoman", size=20)
        pdf.line(20, pdf.get_y() - 10, effective_page_width, pdf.get_y() - 10)
        pdf.multi_cell(effective_page_width, 10, news_dict['title'])
        if news_dict['contain_image']:
            download_image_and_paste_in_pdf(pdf, news_dict, index_news)
        pdf.multi_cell(effective_page_width, 10, news_dict['published'])
        pdf.multi_cell(effective_page_width, 10, news_dict['summary'][news_dict['summary'].rfind(']') + 1:])
        pdf.set_font("TimesNewRoman", size=15)
        pdf.ln(5)
        pdf.multi_cell(effective_page_width, 10, 'Link on news:\n' + news_dict['link'])
        if news_dict['contain_image']:
            pdf.multi_cell(effective_page_width, 10, 'Link on image:\n' + news_dict['link_on_image'])
        pdf.ln(40)
    try:
        pdf.output(filename, 'F')
    except PermissionError:
        raise RssReaderException.FileException(f'close file:\n{filename}')
Example #3
0
class PDFGridGenerator():
    """A pdf grid generator.

    To use:
    >>> g = PDFGridGenerator()
    >>> g.generate('filename.pdf')
    """
    def __init__(self):
        self.pdf = FPDF()
        self.pdf.add_page()
        self.pdf.set_auto_page_break(False)
        self.pdf.set_margins(0, 0)

        self.pdf.set_draw_color(191, 187, 187)
        self.pdf.set_line_width(0.35)

    def save(self, filename):
        self.pdf.output(filename)

    def generate_grid(self):
        # Fonts must be set before writing text
        self.pdf.set_font('Arial', 'B', 8)
        self.pdf.set_text_color(0, 0, 0)

        self.generate_vertical_lines(5)
        self.generate_horizontal_lines(5)

        self.left_numbers(5)
        self.top_numbers(5)

    def generate_vertical_lines(self, spacing):
        lines = 42
        for i in range(1, lines):
            x = i * 5
            self.pdf.line(x, 5, x, 290)

    def generate_horizontal_lines(self, spacing):
        lines = 59
        for j in range(1, lines):
            y = j * 5
            self.pdf.line(5, y, 205, y)

    def left_numbers(self, spacing):
        lines = 58
        for i in range(0, lines):
            self.pdf.set_xy(0, i * 5 + 3)
            self.pdf.write(5, str(i))

    def top_numbers(self, spacing):
        lines = 41
        for i in range(0, lines):
            self.pdf.set_xy(i * 5 + 3, 1)
            self.pdf.write(5, str(i))

    def text(self, x, y, txt, font_size=13):
        self.pdf.set_font('Arial', '', font_size)
        self.pdf.set_text_color(0, 0, 0)
        self.pdf.set_xy(x * 5 + 4, y * 5 + 5)
        self.pdf.write(5, txt)
Example #4
0
def draw_lines():
    pdf = FPDF()
    pdf.add_page()
    pdf.line(10, 10, 10, 100)
    pdf.set_line_width(1)
    pdf.set_draw_color(255, 0, 0)
    pdf.line(20, 20, 100, 20)
    pdf.output('draw_lines.pdf')
Example #5
0
def hwe(dictHWE, thresh, outDir):
	pdf = FPDF() # create new PDF
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "Hardy-Weinberg Equilibrium", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)
	pdf.set_x(20)
	pdf.set_font('Arial', '', 12)
	pdf.multi_cell(0, 5, 'Hardy-Weinberg equilibrium is only used to remove SNPs with extreme p-values are that are likely \
		to occur due to sequencing, genotyping, or study-design errors.  This calculation is sensitive to different ethinic groups \
		and races.  Therefore, it is independently calculated for each ethnic group.  The current p-value threshold that was used to determine \
		whether a SNP was removed was  ' + str(thresh) + '.  This calculation will only consider founders; nonfounders are ignored.' , 0, 1, 'J')
	pdf.multi_cell(0, 5, '\n', 0, 1, 'J')
	pdf.set_font('Arial', 'B', 16)
	pdf.set_fill_color(200)
	
	# iterate through all ethnic groups for HWE stats
	for key, value in dictHWE.iteritems():
		pdf.multi_cell(0, 8, str(key), 1, 'L', True)
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs analyzed:  ' +  str(value[0]), 1, 1, 'L')
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs Passing:  ' +  str(value[1]) + ' (' + str("%.2f" % round((float(value[1])/float(value[0]))*100, 2)) + '%)', 1, 1, 'L')
		pdf.multi_cell(0, 8, '\n\n', 0, 1, 'J')

	
	# NOTE hweFile is before filtering by HWE threshold and prior to removal of SNPs failing threshold
	# these plot the observed vs expected from pre-filter HWE and the associated p-values
	# red fail threhold
	for key, value in dictHWE.iteritems():
		hweFile_dataframe = pd.read_table(value[2], delim_whitespace=True)	
		figure = plt.figure(1)
		num_phenos = len(list(set(list(hweFile_dataframe['TEST'])))) # for use in automating number of subplots to include in figure
		for phenotypes in list(set(list(hweFile_dataframe['TEST']))):
			pheno_subset = hweFile_dataframe.loc[hweFile_dataframe['TEST'] == phenotypes]
			colors = np.where(pheno_subset.P < float(thresh), 'r', 'k')
			plt.subplot(220 + num_phenos)
			plt.scatter(pheno_subset['E(HET)'], pheno_subset['O(HET)'], c=colors, s=8)
			plt.xlabel('expected(het)', fontsize=8)
			plt.ylabel('observed(het)', fontsize=8)
			plt.title(phenotypes + ':  observed(het) vs expected(het) of HWE', fontsize=8)
			num_phenos = num_phenos - 1
		plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
		plt.savefig(outDir+'/'+'hwe_'+str(key)+'.png')
		plt.close()
		pdf.add_page()
		pdf.set_margins(20, 10, 20)
		pdf.set_font('Arial', 'B', 14)
		pdf.set_x(20)
		pdf.multi_cell(0, 10, "HWE Plots for "+str(key) +" population", 0, 1, 'L')
		pdf.line(20, 32, 190, 32)
		pdf.set_x(20)
		pdf.image(outDir+'/'+'hwe_'+str(key)+'.png', x=10, y=50, w=190, h=150)
			
	
	return pdf
Example #6
0
def draw_lines(request):
    pdf = FPDF()
    pdf.add_page()
    pdf.line(10, 10, 10, 100)
    pdf.set_line_width(1)
    pdf.set_draw_color(255, 0, 0)
    pdf.line(20, 20, 100, 20)
    pdf.output('draw_lines.pdf')
    return render(request, "index.html")
Example #7
0
def relatedness(ibd_dataframe, population, outDir):
	
	dups_text = open(outDir + '/' + 'duplicate_pairs.txt', 'w') # outputs pairs with Z0, Z1, Z2	score
	remove_dups = open(outDir + '/remove_all_duplicate_pairs.txt', 'w') # outputs duplicate samples for PLINK formalt removal
	
	pdf = FPDF() # create new PDF
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "Relatedness", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)


	pdf.set_font('Arial', 'B', 16)
	pdf.set_fill_color(200)
	pdf.multi_cell(0, 8, str(population), 1, 'L', True)
	pdf.multi_cell(0, 10, 'Total Number of Sample Pairs Analyzed:  ' +  str(len(ibd_dataframe.index)), 1, 'L', True)

	
	duplicates = ibd_dataframe.loc[ibd_dataframe['Z2'] > 0.97]
	parent_offspring = ibd_dataframe.loc[(ibd_dataframe['Z1'] > 0.97) & (ibd_dataframe['Z0'] < 0.05) & (ibd_dataframe['Z2'] < 0.05)]
	full_sibs = ibd_dataframe.loc[(ibd_dataframe['Z0'] < 0.40) & (ibd_dataframe['Z2'] > 0.16)]
	second_degree = ibd_dataframe.loc[(ibd_dataframe['Z0'] < 0.60) & (ibd_dataframe['Z1'] < 0.58) & (ibd_dataframe['Z2'] < 0.05)]
	unrelated = ibd_dataframe.loc[ibd_dataframe['Z0'] > 0.78]
	
	# format data so it can be put into usable format by PLINK --remove
	first_in_pair = duplicates[['FID1', 'IID1']]
	second_in_pair = duplicates[['FID2', 'IID2']]
	first_in_pair.columns = ['FID', 'IID']
	second_in_pair.columns = ['FID', 'IID']
	merged_removals = first_in_pair.merge(second_in_pair, how='outer', on=['FID', 'IID'])
	merged_removals[['FID', 'IID']].to_csv(remove_dups.name, sep='\t', index=False, header=False) # output file created to PLINK --remove


	pdf.set_font('Arial', '', 16)
	pdf.set_x(30)
	pdf.multi_cell(0, 10, '# of duplicate pairs:  '+str(len(duplicates.index)), 1, 1, 'L')
	pdf.set_x(30)
	pdf.multi_cell(0, 10, '# of parent-offspring pairs:  '+str(len(parent_offspring.index)), 1, 1, 'L')
	pdf.set_x(30)
	pdf.multi_cell(0, 10, '# of full siblings pairs:  '+str(len(full_sibs.index)), 1, 1, 'L')
	pdf.set_x(30)
	pdf.multi_cell(0, 10, '# of 2nd degree pairs:  '+str(len(second_degree.index)), 1, 1, 'L')
	pdf.set_x(30)
	pdf.multi_cell(0, 10, '# of unrelated pairs:  '+str(len(unrelated.index)), 1, 1, 'L')


	dups_text.flush()
	dups_text.close()

	remove_dups.flush()
	remove_dups.close()

	return pdf, remove_dups.name
Example #8
0
def draw_title(pdf: FPDF, **kwargs):
    pdf.set_font("DejaVuBold", size=13)
    pdf.set_y(kwargs['height'] + 4)
    pdf.cell(10)
    pdf.cell(MAX_WIDTH - PAD, 9,
             f'Счет на оплату № {kwargs["number"]} от 20{kwargs["year"]} г.')
    pdf.set_line_width(0.6)
    pdf.line(PAD, kwargs['height'] + 13.5, MAX_WIDTH - PAD,
             kwargs['height'] + 13.5)

    return kwargs['height'] + 14.1
Example #9
0
def schreibe_pdf(bestellung):
    bestell_liste = bestellung.liste
    datum = bestellung.datum.get_datum_string()
    pdf = FPDF(orientation='P', unit='mm', format='A4')

    pdf.add_page()
    try:
        pdf.image('logo-fcn.jpg', x=160, y=8, w=30)
    except:
        print("Logo nicht gefunden")

    pdf.set_font("Times", size=14)
    pdf.cell(180, 20, txt="Terrabestellung vom " + datum, ln=1, align="C")
    # pdf.line(10, 10, 10, 100)
    pdf.set_line_width(.5)
    # pdf.set_draw_color(255, 0, 0)

    pdf.line(10, 37, 190, 37)
    pdf.ln(20)  # move 20 down

    pdf.set_font("Times", size=12)
    pdf.cell(45, 8, txt="Bezeichnung", align="C")
    pdf.cell(20, 8, txt="Grundpreis", align="C")
    pdf.cell(20, 8, txt=f"{Mwst.erm*100} %", align="C")
    pdf.cell(20, 8, txt=f"{Mwst.norm*100} %", ln=1, align="C")

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

    for artikel in bestell_liste:
        # zeile = 0
        pdf.cell(40, 8, txt=artikel.bezeichnung, align="L")
        pdf.cell(20,
                 8,
                 txt=f"{artikel.grundpreis:.2f}".replace('.', ','),
                 align="R")
        pdf.cell(20,
                 8,
                 txt=f"{artikel.mwstErm:.2f}".replace('.', ','),
                 align="R")
        pdf.cell(20,
                 8,
                 txt=f"{artikel.mwstNorm:.2f}".replace('.', ','),
                 ln=1,
                 align="R")
        # zeile += 10

    try:
        tag = datum.split(".")[0]
        monat = datum.split(".")[1]
        jahr = datum.split(".")[2]
        pdf.output(jahr + "-" + monat + "-" + tag + "-Terrabestellung.pdf")
    except:
        pdf.output("Terrabestellung.pdf")
Example #10
0
def parameters_and_thresholds(params):
	
	pdf = FPDF()
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "Parameters and Thresholds", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)
	pdf.set_font('Arial', '', 16)
	for key in params:
		if key not in ['inputPLINK', 'phenoFile', 'outDir', 'projectName', 'config']:
			pdf.multi_cell(0, 8, str(key)+':     '+str(params[key]), 0, 1, 'L')

	return pdf
Example #11
0
class Writer:
    def __init__(self, classes):
        self.classes = classes
        self.pdf = FPDF(orientation="L")

    # create pdf
    def write_to_pdf(self):
        self.pdf.add_page()
        self.pdf.set_font("Arial", size=12)
        self.create_class_rects()
        self.pdf.output("uml.pdf")

    # Create rectangles + content for UML-Diagram
    def create_class_rects(self):
        # iterate over classes dictionary
        for class_index, class_item in enumerate(self.classes):
            offset_x = 110 * (0 if class_index == 0 else class_index % 2)
            offset_y = floor(100 * (class_index // 2))
            print(offset_y)
            self.create_single_class_rect(offset_x, offset_y, class_item)

    def create_single_class_rect(self, offset_x, offset_y, class_item):
        self.pdf.text(55 + offset_x, 20 + offset_y, txt=class_item)
        self.pdf.line(10 + offset_x, 25 + offset_y, 110 + offset_x,
                      25 + offset_y)
        # value for start of line separating variables and methods
        separator_y = 0
        # iterate over variable-names in current class
        for variable_index, variable_name in enumerate(
                self.classes[class_item]["variables"]):
            separator_y = 35 + 5 * variable_index
            self.pdf.text(20 + offset_x,
                          separator_y + offset_y,
                          txt=variable_name)
        # generate sepator line if there are variables
        if separator_y != 0:
            self.pdf.line(10 + offset_x, separator_y + 5 + offset_y,
                          110 + offset_x, separator_y + 5 + offset_y)
        rectangle_end_y = separator_y
        # iterate over method-names in current class
        for method_index, method_name in enumerate(
                self.classes[class_item]["methods"]):
            rectangle_end_y = (separator_y + 15) + 5 * method_index
            self.pdf.text(20 + offset_x,
                          rectangle_end_y + offset_y,
                          txt=method_name)
        # create rectangle for class in specific size
        self.pdf.rect(10 + offset_x, 10 + offset_y, 100, rectangle_end_y - 5)
Example #12
0
    def createPDF(self):
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font('Arial', 'B', 18)
        # header
        pdf.image("images/ImagLogo.GIF", 170, 3, 25)
        pdf.cell(0, 10, "Report", border=False, ln=1, align="C")
        pdf.ln()
        #####General Information
        pdf.set_font('Arial', 'B', 12)
        pdf.set_fill_color(213, 201, 239)
        pdf.cell(0, 9, 'General Information', 0, 1, 'L', 1)
        pdf.ln(3)
        pdf.line(8, 20, 150, 20)
        pdf.set_font('Arial', 'IB', 13)
        pdf.cell(
            130,
            10,
            txt="Paitant ID :  " + self.P_ID + " ",
            ln=1,
            align='E',
        )
        pdf.set_font('Arial', 'B', 12)
        pdf.cell(130, 10, txt="Check up No:", align="W")
        pdf.cell(100,
                 10,
                 txt=" Test Result Data: " +
                 datetime.date.today().strftime("%d-%m-%y"),
                 ln=1,
                 align="E")
        ##Result
        pdf.ln()
        pdf.set_font('Arial', 'B', 12)
        pdf.set_fill_color(213, 201, 239)
        pdf.cell(0, 9, ' Result Infromation', 0, 1, 'L', 1)
        pdf.image(self.imagePa, 90, 100, 100)
        pdf.ln()
        pdf.set_font('Arial', 'B', 16)
        pdf.cell(0, 10, txt=" The disease is " + self.result + "", align="W")

        # footer
        pdf.set_font('Arial', '', 13)
        pdf.set_auto_page_break(auto=True, margin=15)
        pdf.set_y(270)
        pdf.cell(0, 10, f'Page {pdf.page_no()}/nb', align="C")
        pdf.alias_nb_pages(alias='nb')
        # add another cell
        pdf.output("results/" + self.P_ID + ".pdf")
Example #13
0
def conditions(pdf: FPDF, **kwargs):
    def add_text(text, height):
        MAXIMUM_PAGE_WIDTH = 210
        PADDING = 20
        pdf.cell(10)
        height += 4 * len(
            pdf.multi_cell(
                MAXIMUM_PAGE_WIDTH - 2 * PADDING, 4, text, split_only=True))
        pdf.multi_cell(MAXIMUM_PAGE_WIDTH - 2 * PADDING, 4, text)
        return height

    height = kwargs['height'] + 10
    pdf.set_font("TimesNewRoman", size=8)
    pdf.set_y(height)
    height = add_text('Внимание!', height)
    height = add_text(
        'Оплата данного счета означает согласие с условиями поставки товара.',
        height)
    height = add_text(
        'Уведомление об оплате обязательно, в противном случае не гарантируется наличие товара на складе.',
        height)
    height = add_text(
        'Товар отпускается по факту прихода денег на р/с Поставщика, самовывозом, при наличии доверенности и паспорта.',
        height)

    MAXIMUM_PAGE_WIDTH = 210
    PADDING = 20
    pdf.set_y(height)
    pdf.set_font("TimesNewRomanB", size=9)
    pdf.cell(10)
    pdf.cell(30, 5, 'Руководитель')
    pdf.set_font("TimesNewRoman", size=9)
    pdf.cell(60, 5, kwargs['supervisor'], align='R')
    pdf.set_font("TimesNewRomanB", size=9)
    pdf.cell(30, 5, 'Бухгалтер', align='C')
    pdf.set_font("TimesNewRoman", size=9)
    pdf.cell(MAXIMUM_PAGE_WIDTH - 2 * PADDING - 120,
             5,
             kwargs['accountant'],
             align='R')

    pdf.set_line_width(0.2)
    pdf.line(PADDING + 35, height + 5, PADDING + 90, height + 5)
    pdf.line(PADDING + 120, height + 5, MAXIMUM_PAGE_WIDTH - PADDING,
             height + 5)

    return height
Example #14
0
def gen_PDF(events):
    pdf = FPDF('L', 'in', 'Letter')
    for event in events:
        pdf.add_page()
        pdf.set_draw_color(r=0, g=0, b=255)
        pdf.set_line_width(.05)
        pdf.rect(.15, .15, 10.7, 8.2)
        pdf.image('images/3IDcav3.png', x=.14, y=.22, h=1)
        pdf.image('images/3IDLogo.png', x=9.8, y=.22, h=1)
        pdf.set_draw_color(r=0, g=0, b=0)
        pdf.line(5.5, 1.5, 5.5, 8)
        pdf.line(.5, 4.25, 10.5, 4.25)

        pdf.set_font('Arial', 'B', 24)
        pdf.set_xy(0, .75)
        pdf.cell(w=0, txt=events[event].title, align='C')
        pdf.set_xy(1, 1.5)
        pdf.set_font('Arial', '', 14)
        pdf.multi_cell(
            4.5, .22,
            'Purpose: {}\n\nFrequency: {}\n\nTime: {}\n\nLocation: {}'.format(
                events[event].purpose, events[event].frequency,
                events[event].time, events[event].location), 0, 'L')
        pdf.set_xy(1, 4.5)
        pdf.multi_cell(
            4.5, .22, 'Inputs: \n{}\nOutputs: \n{}'.format(
                '  - ' + str(events[event].inputs)[1:-1].replace(
                    "'", "").replace(',', '\n  -'),
                '  - ' + str(events[event].outputs)[1:-1].replace(
                    "'", "").replace(',', '\n  -'), 0, 'L'))
        pdf.set_xy(6.5, 1.5)
        pdf.multi_cell(
            4.5, .22, 'Chair: {}\n\nMembers: \n{}'.format(
                events[event].chair,
                '  - ' + str(events[event].members)[1:-1].replace(
                    "'", "").replace(',', '\n  -'), 0, 'L'))
        pdf.set_xy(6.5, 4.5)
        pdf.multi_cell(
            4.5, .22, 'Agenda: \n{}'.format(
                '  - ' + str(events[event].agenda)[1:-1].replace(
                    "'", "").replace(',', '\n  -'), 0, 'L'))

    try:
        pdf.output('exports/test.pdf')
    except FileNotFoundError:
        os.mkdir('exports')
        pdf.output('exports/test.pdf')
Example #15
0
def generatePDF(userid, maxportfolioid):
    sql_statement = "SELECT symbol, purchase_price, lot_size from portfolio where userid = %s and portfolioid = %s"
    data = (userid, maxportfolioid)
    connection = DBconnection(sql_statement, data)
    Symbol = [i[0] for i in connection]
    PurchasePrice = [i[1] for i in connection]
    Lot_Size = [i[2] for i in connection]

    pdf = FPDF()

    #header of the pdf file
    header = 'Specifically curated for ' + str(userid)
    pdf.add_page()
    pdf.set_font('Arial', 'B', 16)
    w = pdf.get_string_width(header) + 6
    pdf.set_x((210 - w) / 2)
    pdf.cell(w, 9, header, 0, 0, 'C')
    pdf.line(20, 18, 210 - 20, 18)

    pdf.ln(10)
    pdf.set_font('Times', '', 12)
    pdf.multi_cell(
        0, 5,
        'Here is a list of suggested financial instruments for your peruse.')

    for i in range(len(Symbol)):
        pdf.ln()
        pdf.set_font('Arial', '', 12)
        pdf.set_fill_color(200, 220, 255)
        pdf.cell(
            0, 6, 'Financial Instrument ' + str(i + 1) + ": " +
            str(Symbol[i]) + " Unit Price " + str(PurchasePrice[i]) +
            " Lot Size " + str(Lot_Size[i]), 0, 1, 'L', 1)

        pdf.ln()
        pdf.set_font('Courier', 'B', 12)
        pdf.multi_cell(
            0, 5, 'A detailed analysis on ' + Symbol[i] + '---------------')

    #pdf.set_y(0) #on top of the page
    pdf.set_y(-30)  #30 CM from the bottom of the page
    pdf.set_font('Arial', '', 8)
    pdf.set_text_color(0)
    pdf.cell(0, 5, 'Page ' + str(pdf.page_no()), 0, 0, 'C')

    pdf.output(str(userid) + '.pdf', 'F')
    return pdf
Example #16
0
def createPDF():
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font('Times', 'BI', 11)
    #   write file...
    contact = open("./user.txt", "r")

    for a in contact:
        pdf.multi_cell(200, 5, txt=a, align='C')
    contact.close()

    education = open('./education.txt', 'r')
    pdf.cell(200, 5, txt="Education", align='L')
    y = pdf.get_y()
    pdf.line(200, y + 5, 5, y + 5)
    pdf.set_font('Times', '', 10)
    for b in education:
        pdf.multi_cell(200, 5, txt=b, align='L')
    education.close()

    pdf.set_font('Times', 'BI', 11)
    pdf.cell(200, 5, txt="Selected Independent Projects", align='L')
    y = pdf.get_y()
    pdf.line(200, y + 5, 5, y + 5)
    projects = open('./project.txt', 'r')
    pdf.set_font('Times', '', 10)
    for c in projects:
        pdf.multi_cell(200, 5, txt=c, align='L')
    projects.close()

    pdf.set_font('Times', 'BI', 11)
    pdf.cell(200, 5, txt="Experience", align='L')
    y = pdf.get_y()
    pdf.line(200, y + 5, 5, y + 5)
    experience = open('./work.txt', 'r')
    pdf.set_font('Times', '', 10)
    for d in experience:
        pdf.multi_cell(200, 5, txt=d, align='L')
    experience.close()

    pdf.set_font('Times', 'BI', 11)
    pdf.cell(200, 5, txt="Skills", align='L')
    y = pdf.get_y()
    pdf.line(200, y + 5, 5, y + 5)
    skills = open('./skill.txt', "r")
    pdf.set_font('Times', '', 10)
    for e in skills:
        pdf.multi_cell(200, 5, txt=e, align='L')
    skills.close()

    try:
        pdf.output("resume.pdf", "F")
        return "Success"
    except:
        return "Error"
Example #17
0
	def build_pdf(self,done):
		pdf = FPDF()
		pdf.add_page()
		pdf.set_font("Arial", size=12)

		pdf.line(115, 20, 115, 4000) # splitting line
		pdf.cell(10, 10, txt="Patient Name: ", ln=1, align="L")
		pdf.line(40, 17, 65, 17)
		pdf.text(40, 15, self.patient_name)
		pdf.image('symrx_logo.png', x=175, y=2, w=30)

		pdf.image('thing_1.png', x=10, y=35 ,w=15)


	
		num = 0
		if self.quantity == 'One':
			num = 1
		elif self.quantity == 'Two':
			num = 2
		elif self.quantity == 'Three':
			num = 3
		elif self.quantity == 'Four':
			num = 4
		elif self.quantity == 'Five':
				num = 5
		else:
			num = 1

		room = (100 // num) -5

		for i in range(num):
			pdf.image((done[0] + '.png'), x= (i * room) + 20, y=50, w=(room//1.5))

		x = 2
		y = 120
		for element in done[2:4]:
			pdf.image((element + '.png'), x=20, y=y ,w=80)
			pdf.image('thing_' + str(x) + '.png', x=10, y=y-10 ,w=15)
			
			y += 120
			x += 1
		pdf.output("finished_picto.pdf")
Example #18
0
def restes_vertical(file, pages, min, max, disable_total_operacions):
    pdf = FPDF(orientation='P', unit='mm', format='A4')
    for pagina in range(0, pages):
        pdf.add_page()
        pdf.set_font('helvetica', '', 15.0)
        pdf.set_xy(5.0, 18)
        pdf.cell(
            w=0,
            h=0,
            txt=
            'Nom: ........................................................................... Data: ...................................',
            ln=0)
        if not disable_total_operacions:
            pdf.set_xy(5.0, 276)
            pdf.set_font('helvetica', '', 25.0)
            pdf.cell(
                w=0,
                h=0,
                txt='Operacions fetes en 2 minuts .......................',
                ln=0)
        pdf.set_font('helvetica', '', 20.0)
        anterior_operacio = ''
        operacio = ''
        for columna in range(0, 3):
            for linea in range(0, 5):
                primer_numero = randrange(int(max / 4), max)
                segon_numero = randrange(min, primer_numero)
                pdf.set_xy(30.0 + (columna * 65),
                           47.5 + (((linea * 2) - 0.4) * 25))
                pdf.cell(w=0, h=0, txt=str(primer_numero), ln=0)
                pdf.set_xy(30.0 + ((columna * 65) - 5),
                           47.5 + ((linea * 2) * 25))
                pdf.set_font('helvetica', '', 30.0)
                pdf.cell(w=0, h=0, txt="-", ln=0)
                pdf.set_font('helvetica', '', 20.0)
                pdf.set_xy(30.0 + (columna * 65), 47.5 + ((linea * 2) * 25))
                pdf.cell(w=0, h=0, txt=str(segon_numero), ln=0)
                pdf.set_line_width(0.5)
                pdf.line(20.0 + (columna * 65), 52.5 + ((linea * 2) * 25),
                         45.0 + (columna * 65), 52.5 + ((linea * 2) * 25))
        if pagina % 4 == 0:
            max += 1
    pdf.output(file, 'F')
Example #19
0
def make_pdf(data, spacing=1):
    """Génère le pdf de l'etiquette lettre suivie

    Parameters
    ----------
    data : dict
        Dict avec les info pour generer l'etiquette
    spacing : int
        Taille entre chaque ligne
    """
    dimension = [4, 6]
    pdf = FPDF("P", "in", dimension)
    pdf.add_page()
    pdf.set_font("Arial", size=10)

    data = [
        "Expediteur", f"          {data['Expe_Ad1']}",
        f"          {data['Expe_Ad2']}",
        f"          {data['Expe_CP']} {data['Expe_Ville']}",
        f"          {data['Expe_Pays']}", f"          {data['Expe_Tel1']}", "",
        'Destinataire', f"          {data['Dest_Ad1'].upper()}",
        f"          {data['Dest_Ad2'].upper()}",
        f"          {data['Dest_Ad3'].upper()}",
        f"          {data['Dest_CP']} {data['Dest_Ville']}",
        f"          {data['Dest_Pays']}", f"          {data['Dest_Tel1']}", "",
        f"Ref Client : {data['Id_Cmd']}                     Poids : {data['Poids']}"
    ]

    col_width = pdf.w
    row_height = pdf.font_size

    for item in data:
        if item == "Expediteur":
            pdf.set_font("Arial", size=6)
        elif item == "Destinataire":
            pdf.set_font("Arial", size=10)
        pdf.cell(col_width, row_height * spacing, txt=item)
        pdf.ln(row_height * spacing)

    pdf.line(0.4, 0.4, 1.6, 1.2)
    pdf.line(0.4, 1.2, 1.6, 0.4)

    pdf.output(app.utilities.get_path("docs/etiquette_lettre_suivie.pdf"))
    def build_chart(self, output_name, mins):
        length = len(protein_seq(self))
        chunks = Chart.get_bits(self)

        pdf = FPDF('L')
        pdf.add_page()

        height = (125 / len(self.struct_sequences[1:])) / len(chunks[0][0][0])
        mult = height - 1
        for i in range(len(chunks)):
            for m in range(len(chunks[i])):
                for z in range(len(chunks[i][m])):
                    r, g, b = float(chunks[i][m][z][0]), float(
                        chunks[i][m][z][1]), float(chunks[i][m][z][2])
                    pdf.set_fill_color(r, g, b)
                    pdf.rect((z + (z * .9)) + 2,
                             ((m + (mult * m) + (i * 60) + 5)),
                             1.9,
                             height,
                             style='F')
            pdf.line((0 + (0 * .9)) + 2, (m + (mult * m) + (i * 60) + 5),
                     (z + (z * .9)) + 3.9, (m + (mult * m) + (i * 60) + 5))
        pdf.set_font("Arial", style='B', size=5.5)

        pieces = get_chunks(self)
        for Y in range(len(chunks)):
            for B in range(len(pieces[Y])):
                pdf.text((B + (B * .9)) + 2.2, ((Y * 60) + 4.5), pieces[Y][B])

        option_list = ['Helix', 'Coil', 'Strand']
        for q in range(3):
            red = float(mins[q][0])
            green = float(mins[q][1])
            blue = float(mins[q][2])

            pdf.set_font("Arial", style='B', size=18)

            pdf.set_fill_color(red, green, blue)
            pdf.rect(230, (q * 7) + q + 185, 15, 7, style='F')
            pdf.text(247, (q * 7) + q + 190, option_list[q])

        pdf.output(output_name)
Example #21
0
def output_pdf(logger, all_news, about_website=None, file_name=None):
    """Function which create or overwrites PDF-file with selected fresh or cached news"""
    logger.info('Convert to PDF-format')
    pdf = FPDF()
    pdf.add_page()
    if about_website is not None:
        pdf.set_font("Arial", "B", size=14)
        pdf.set_fill_color(200, 220, 255)
        for value in about_website.values():
            line = 1
            pdf.cell(190, 8, txt=value, ln=line, align="C")
            line += 1
    pdf.set_font("Arial", size=10)
    pdf.set_line_width(1)
    pdf.set_draw_color(35, 41, 153)
    for news in all_news:
        link = news['Source of image']
        for key, value in news.items():
            if key != 'Summary':
                pdf.multi_cell(190, 6, txt=f'{key}: {value}', align="L")
            else:
                position_y = pdf.get_y()
                try:
                    filename, _ = urllib.request.urlretrieve(link)
                    pdf.image(filename, 80, position_y, h=30, type='jpeg', link=link)
                    pdf.ln(31)
                    os.remove(filename)
                except Exception as ex:
                    logger.warning("Error finding image: {}, {}.".format(type(ex), ex))
                pdf.multi_cell(190, 6, txt=f'{key}: {value}', align="L")
        position_y = pdf.get_y()
        pdf.set_line_width(1)
        pdf.set_draw_color(35, 41, 153)
        pdf.line(10, position_y, 200, position_y)
    logger.info('Creating of PDF-file')
    try:
        pdf.output(file_name)
        logger.info('Converted successfully!')
    except Exception as ex:
        logger.error("PDF file writing error : {}, {}.".format(type(ex), ex))
Example #22
0
 def test_Paragraph(self):
     self.do_for_each_DocItem_class(Paragraph())
     
     pdf = FPDF()
     initPDF(pdf)
     pdf.set_line_width(2)
     pdf.line(0, 20, 300, 20)
     
     par = Paragraph()
     par.addItems(*[w('Hello'),w('world!')])
     par.addItems(w('Formula:'),b(v('x'),si('+'),f(sy('alpha'),n('2'))))
     par.resizePDF(pdf)
     par.cellPDF(pdf)
     par.showRect(pdf)
     
     par = Paragraph(100)
     par.addItems(w('I'),w('have'),w('my'),w('width'),w('set.'))
     par.resizePDF(pdf)
     par.cellPDF(pdf)
     par.showRect(pdf)
     
     pdf.output('out/document/test_Paragraph.pdf', 'F')
Example #23
0
File: suppdf.py Project: VUIIS/dax
def make_overpdf(overfile, info, pagenum, pagecount):
    # Assessor name top left of header
    # processor name and version left of footer
    # Date and Page numbers in right footer

    # Initialize the pdf
    pdf = FPDF(orientation="P", unit='in', format='letter')
    pdf.set_margins(left=0, top=0, right=0)
    pdf.add_page()
    pdf.set_font('courier', size=9)

    # Draw lines in header and footer
    pdf.set_draw_color(r=155, g=155, b=155)
    pdf.set_line_width(0.01)
    pdf.line(x1=0.2, y1=0.2, x2=8.3, y2=0.2)
    pdf.line(x1=0.2, y1=10.7, x2=8.3, y2=10.7)

    # Write the assessor label in the header
    pdf.set_xy(0.3, 0.1)
    pdf.cell(0, 0.05, '{}'.format(info['assessor']))

    # Prevent footer from falling off page
    pdf.set_auto_page_break(False)

    # Write proc version in left of footer
    pdf.set_xy(0.3, -0.2)
    pdf.cell(0, 0, '{}'.format(info['proctype']))

    # Write date in right of footer
    pdf.set_xy(-2.1, -0.2)
    pdf.cell(0, 0, '{}'.format(info['procdate']))

    # Write page numbers right of footer
    pdf.set_xy(-0.6, -0.2)
    pdf.cell(0, 0, '{}/{}'.format(pagenum, pagecount))

    # Write the pdf to file
    pdf.output(overfile)
Example #24
0
def generate_pdf_of_playing_field(puzzle, solution):
    """Generate a pdf of the playing field for visualisation"""
    # A4 dimensions are 210 mm x 297 mm
    pdf = FPDF('P', 'mm', 'A4')
    width = 210
    pdf.set_font('Arial', '', 26)
    square_side_size = 20
    offset_x = (width - (square_side_size * 9)) / 2
    offset_y = 15

    for page in [puzzle, solution]:
        pdf.add_page()

        line_width = 0.2
        pdf.set_line_width(line_width)

        for row in range(0, 9):
            pdf.set_y(offset_y + (square_side_size * (row)))
            pdf.set_x(offset_x)
            for column in range(0, 9):
                pdf.cell(square_side_size, square_side_size,
                         str(page[row][column]), 1, 0, 'C')

        line_width = 1.5
        pdf.set_line_width(line_width)

        for horizontal in range(0, 2):
            x_coord = offset_x + line_width / 2
            y_coord = offset_y + ((horizontal + 1) * square_side_size * 3)
            pdf.line(x_coord, y_coord, width - x_coord, y_coord)

        for vertical in range(0, 2):
            x_coord = offset_y + ((vertical + 1) * square_side_size * 3)
            y_coord = offset_x + line_width / 2
            pdf.line(x_coord, y_coord, x_coord, width - y_coord)

    pdf.output('sudoku.pdf', 'F')
Example #25
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')), {})
Example #26
0
def minor_allele_freq(dictMAF, thresh):
	pdf = FPDF() # create new PDF
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "Minor Allele Frequency", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)
	pdf.set_font('Arial', 'B', 16)
	pdf.set_fill_color(200)

	# iterate through all ethnic groups for LD pruning stats
	for key, value in dictMAF.iteritems():
		pdf.multi_cell(0, 8, str(key), 1, 'L', True)
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs analyzed:  ' +  str(value[0]), 1, 1, 'L')
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs MAF >= ' + str(thresh) + ': ' +  str(value[1]) + ' (' + str("%.2f" % round((float(value[1])/float(value[0]))*100, 2)) + '%)', 1, 1, 'L')
		pdf.set_x(30)
		pdf.multi_cell(0, 8, 'Total Number of SNPs MAF <= ' + str(thresh) + ': ' +  str(value[2]) + ' (' + str("%.2f" % round((float(value[2])/float(value[0]))*100, 2)) + '%)', 1, 1, 'L')
		pdf.multi_cell(0, 8, '\n\n', 0, 1, 'J')


	return pdf
def heterozygosity(het_dataframe, thresh, minThresh, outDir):
	pdf = FPDF() # create new PDF
	pdf.add_page()
	pdf.set_margins(20, 10, 20)
	pdf.set_font('Arial', 'B', 24)
	pdf.set_x(20)
	pdf.multi_cell(0, 30, "Heterozygosity", 0, 1, 'L')
	pdf.line(20, 32, 190, 32)

	sample_fails = open(outDir + '/samples_failing_heterozygosity.txt', 'w')
	fail_het = het_dataframe.loc[((het_dataframe['F'] > thresh) | (het_dataframe['F'] < minThresh))]
	fail_het[['FID', 'IID']].to_csv(sample_fails.name, sep='\t', index=False, header=False) # format it FID <tab> IID <new line>


	# sorts inbreeing coeffiecient score to rank for ploting
	het_dataframe.sort_values(by='F', ascending=True, axis=0, inplace=True)
	het_dataframe = het_dataframe.reset_index()
	het_dataframe['rank'] = het_dataframe.index
	
	pdf.set_font('Arial', '', 12)
	pdf.multi_cell(0, 5, 'Heterozygosity is calculated on the merged sample space.  Samples with extreme levels of heterozygosity as measured by \
		the F inbreeding coefficient, may be indicative of a sample exhibiting poor quality.  The current inbreeding coefficient threshold is set \
		to ' + str(thresh) + '.  Any F value above this threshold is filtered out.', 0, 1, 'J')
	pdf.multi_cell(0, 5, '\n', 0, 1, 'J')
	pdf.set_font('Arial', 'B', 16)
	pdf.set_fill_color(200)
	pdf.multi_cell(0, 8, 'Total Number Samples Analyed: '+ str(len(het_dataframe.index)), 1, 'L', True)
	pdf.set_x(30)
	pdf.multi_cell(0, 8, 'Total Number Samples Failing: '+ str(len(fail_het.index)), 1, 1, 'L')

	het_dataframe.plot(kind='scatter', x='rank', y='F', title='Ranked Inbreeding Coefficient scores', s=7)
	plt.tight_layout(pad=2, w_pad=2, h_pad=2)
	plt.savefig(outDir+'/'+'heterozygosity_plot.png')
	plt.close()
	pdf.image(outDir+'/'+'heterozygosity_plot.png', x=10, y=130, w=190, h=150)
	return sample_fails.name, pdf
Example #28
0
def create_mandate(member_id, name, address, bank, branch_code, account_number,
                   account_type, price, phone, charge_day):
    f = FPDF('P', 'mm', 'A4')
    f.add_page()
    pth = os.path.join(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        'mandate3.png')
    f.image(pth, 0, 0, MAX_X, MAX_Y)
    f.set_font('Courier', '', 12)
    f.text(85, 68, name)
    f.text(33, 75, address)
    f.text(27, 81, bank)
    f.text(43, 88, branch_code)
    f.text(133, 88, account_number)
    if account_type != "1":
        f.line(45, 94.5, 80, 94.5)
    if account_type != "2":
        f.line(83, 94.5, 100, 94.5)
    if account_type != "3":
        f.line(101, 94.5, 125, 94.5)
    now = datetime.now()
    f.text(31, 101, "R" + str(price))
    f.text(86, 101, now.strftime("%d/%b/%Y"))
    f.text(164, 101, phone)
    f.text(140, 122, now.strftime("%d/%b/%Y"))

    # calculate detailed charges
    days_in_month = calendar.monthrange(now.year, now.month)[1]
    #price_per_day = price / days_in_month
    first_charge = price  # price_per_day * (days_in_month - now.day)
    first_charge_day = datetime.now().replace(minute=0,
                                              hour=0,
                                              second=0,
                                              day=charge_day)
    if charge_day < datetime.now().day + 5:
        # should be always true
        # first_charge += price
        first_charge_day = add_month(first_charge_day)

    f.text(74, 146, "R%.2f" % first_charge)
    f.text(123, 146, first_charge_day.strftime("%d/%b/%Y"))

    f.text(84, 151, "R%.2f" % price)
    f.text(122, 151, add_ending(charge_day))
    f.text(30, 160.5, add_ending(charge_day))

    f.text(30, 257, "Cape Town")
    f.text(75, 257, add_ending(now.day))
    f.text(100, 257, now.strftime("%B"))
    f.text(60, 278.6, "B11-" + str(member_id))
    #    f.set_font('Arial', '', 6)
    #    f.text()

    return f.output(dest='S')
Example #29
0
def draw_footer(pdf: FPDF, **kwargs):
    def add_text(text, height):
        pdf.cell(10)
        height += 4 * len(
            pdf.multi_cell(MAX_WIDTH - 2 * PAD, 4, text, split_only=True))
        pdf.multi_cell(MAX_WIDTH - 2 * PAD, 4, text)
        return height

    height = kwargs['height'] + 10
    pdf.set_font("DejaVu", size=8)
    pdf.set_y(height)
    height = add_text('Внимание!', height)
    height = add_text(
        'Оплата данного счета означает согласие с условиями поставки товара.',
        height)
    height = add_text(
        'Уведомление об оплате обязательно, в противном случае не гарантируется наличие товара на складе.',
        height)
    height = add_text(
        'Товар отпускается по факту прихода денег на р/с Поставщика, самовывозом, при наличии доверенности и паспорта.',
        height)

    pdf.set_line_width(0.5)
    pdf.line(PAD, height + 4, MAX_WIDTH - PAD, height + 4)
    height += 10

    pdf.set_y(height)
    pdf.set_font("DejaVuBold", size=9)
    pdf.cell(10)
    pdf.cell(30, 5, 'Руководитель')
    pdf.set_font("DejaVu", size=9)
    pdf.cell(60, 5, kwargs['director'], align='R')
    pdf.set_font("DejaVuBold", size=9)
    pdf.cell(30, 5, 'Бухгалтер', align='C')
    pdf.set_font("DejaVu", size=9)
    pdf.cell(MAX_WIDTH - 2 * PAD - 120, 5, kwargs['accountant'], align='R')

    pdf.set_line_width(0.2)
    pdf.line(PAD + 35, height + 5, PAD + 90, height + 5)
    pdf.line(PAD + 120, height + 5, MAX_WIDTH - PAD, height + 5)

    return height
Example #30
0
 def test_pdf_cell(self):
     pdf=FPDF()
     pdf.c_margin = 0.0
     pdf.add_font('symbol','','font/DejaVuSans.ttf',uni=True)
     pdf.add_page()
     f = 0.81
     font_name = 'times'
     
     text = 'small text'
     pdf.set_font(font_name,'',12)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w, h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     text = 'Large text'
     pdf.set_font(font_name,'',24)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w,h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     text = 'Larger text'
     pdf.set_font(font_name,'',48)
     x,y = pdf.get_x(), pdf.get_y()
     w = pdf.get_string_width(text)
     h = pdf.font_size_pt / pdf.k
     pdf.cell(w,h, text)
     pdf.rect(x, y, w, h, '')
     pdf.line(x, y + f * h, x + w, y + f * h)
     
     pdf.output('out/fpdf/test_pdf_cell.pdf', 'F')
Example #31
0
	def print_pdf(self, path = "c:/base.pdf", font_size = 12):
		xm=[] # определим нулевые массивы координат
		ym=[]
		msize=[] # здесь будем хранить размеры фундаментов
		l = len(self.fund_list)
		for i in range(l):
		    size = self.sizefn(self.fund_list[i][1]); x = self.fund_list[i][2]; y = self.fund_list[i][3];
		    xm.append(x - size/2); xm.append(x + size/2) 
		    ym.append(y - size/2); ym.append(y + size/2); msize.append(size)
		
		xmin=min(xm);xmax=max(xm);
		ymin=min(ym);ymax=max(ym);
		max_size = max(msize)
		
		dx = xmax - xmin; dy = ymax - ymin;
		
		if dx>dy:
		    orientation = 'L'
		else:
		    orientation = 'P'
		print "orientation = ", orientation, '\n'
		
		# необходимо вычислить коэффициенты отображения расстояний
		field_size = 10  # в мм
		if orientation == 'L':
		    dxl = 297 - field_size*2; dyl = 210 - field_size*2
		else:
		    dxl = 210 - field_size*2; dyl = 297 - field_size*2
		dxk = dx/dxl; dyk = dy/dyl  # 
		
		k = max(dxk, dyk) # нашли общий коэффициент уменьшения
		##### вычислим поправку на вторую сторону -- TODO
		
		xm=[]; ym=[]  # очистим массивы и занесем туда координаты ц.т. фундаментов, а не их границы
		for i in range(l):
		    size = self.fund_list[i][1]; x = self.fund_list[i][2]; y = self.fund_list[i][3];
		    xm.append(x); 
		    ym.append(y);
		
		# найдем центр тяжести изображения
		
		xc = sum(xm)/l; yc = sum(ym)/l
		print "центр тяжести фундаментов xc/yc: ", xc, "/",yc, "\n"
		
		# приведем игреки так, чтобы цент тяжести прошел через ось
		ym = map(lambda y: y - yc, ym)
		# инвертируем игреки
		ym = map(lambda y: -y, ym)
		
		# отодвинем игреки на половину dy + половина размера фундамента
		ym = map(lambda y: y + dy/2 + max_size/2, ym)
		
		# приведем иксы к началу координат + половина размера фундамента
		xm = map(lambda x: x - xmin + max_size/2, xm)
		
		# смаштабируем координаты
		xm = map(lambda x: x/k, xm)
		ym = map(lambda y: y/k, ym)
		
		# отодвинем на величину поля
		xm = map(lambda x: x + field_size*2, xm)
		ym = map(lambda y: y + field_size*2, ym)
		
		title = ""
		heading = ""
		pdf = FPDF()
		pdf.add_page(orientation = orientation)
		pdf.set_font('Times', 'B', font_size)
		for i in range(l):
		    x = xm[i]; y = ym[i]
		    #fpdf.set_xy(x, x)
		    string1 = str(self.fund_list[i][0])
		    string2 = "size=" +str(self.fund_list[i][1]) + " m"
		    pdf.text(x, y, string1)  # выведем марку фундамента
		    pdf.text(x, y+font_size/2, string2)
		    size_x, size_y = self.sizefn_xy(self.fund_list[i][1])
		    pdf.line(x - size_x/2/k, y - size_y/2/k, x - size_x/2/k, y + size_y/2/k) # вверх из нижнего левого угла
		    pdf.line(x - size_x/2/k, y + size_y/2/k, x + size_x/2/k, y + size_y/2/k)  # вправо
		    pdf.line(x + size_x/2/k, y + size_y/2/k, x + size_x/2/k, y - size_y/2/k) # вниз
		    pdf.line(x + size_x/2/k, y - size_y/2/k, x - size_x/2/k, y - size_y/2/k)  # влево
		    
		pdf.output(name = path)
Example #32
0
    def ImrimirPDF(self, saleId):
	# Obtener los datos de la base de datos (datos de la venta y los elementos)
	datos = db.Salerecord(saleId)
	# guardar los datos de la venta en datos_sale
	datos_sale  = datos[0]
	#Guardar los datos de los elementos de la venta en datos_items 
	datos_items = datos[1]
	# Formatear el numero de la venta (ej: 0000000023)
	facturaNumero = str(("0"*(10-len(str(saleId))))+str(saleId))
	# Obtener los datos de la tienda/empresa desde la base de datos
	Datos = db.SelectConfigNS()
	
	logo = self.ResourcePath('logo.png')
	pdf = FPDF()
	pdf.add_page()
#	pdf.add_font('courier', '', 'cour.ttf', uni=True)
#	pdf.add_font('courier', '', 'cour.ttf', uni=True)
	pdf.set_font('courier', '', 13.0)
	pdf.set_xy(105.0, 16.0)
	pdf.cell(ln=0, h=22.0, align='L', w=75.0, txt='', border=0)
	pdf.set_line_width(0.0)
	pdf.rect(15.0, 45.0, 180.0, 90.0) # Marco Principal
	pdf.set_line_width(0.0)
	#pdf.rect(95.0, 15.0, 10.0, 10.0) # cuadrito 
    # LOGOTIPO
	pdf.image(logo, 27.0, 10.0, link='', type='', w=0, h=20)
	pdf.set_font('courier', 'B', 16.0)
	pdf.set_xy(95.0, 18.0)
	#pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt='Hola 1', border=0)
    # DATOS DE LA EMPRESA
	pdf.set_font('courier', '', 8.0)
	pdf.set_xy(115.0, 25.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Tel:              "+str(Datos[3]), border=0)
	pdf.set_xy(115.0, 28.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Web:              "+str(Datos[4]), border=0)
	pdf.set_xy(115.0, 31.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="E-mail:           "+Datos[7], border=0)
	pdf.set_xy(115.0, 34.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="NIT:              "+str(Datos[8]), border=0)
	pdf.set_font('courier', '', 7.0)

	pdf.set_xy(115.0, 35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=60.0, txt='Fecha:', border=0)
	pdf.set_xy(145.0, 35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=40.0, txt=datos_sale[1], border=0)

	pdf.rect(15.0, 9.0, 180.0, 35.8) # header datos principales

	pdf.set_xy(95.0, 21.5)
	pdf.set_line_width(0.0)
	pdf.set_font('arial', 'B', 13.0)
	pdf.set_xy(15.0, 10.5)
	pdf.cell(ln=0, h=5.5, align='C', w=180.0, txt='Comprobante de venta', border=0)
#	pdf.line(100.0, 25.0, 100.0, 57.0) #linea vertical header
	pdf.set_font('arial', 'B', 14.0)
	pdf.set_xy(143.0, 15.5)
	pdf.cell(ln=0, h=9.5, align='L', w=60.0, txt=facturaNumero, border=0)
	pdf.set_xy(115.0, 17.5)
	pdf.cell(ln=0, h=5.5, align='L', w=10.0, txt='N\xba: ', border=0)
	pdf.set_font('courier', 'B', 12.0)
	pdf.set_xy(17.0, 30.5)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt=Datos[1], border=0)#Datos[1] nombre
	pdf.set_font('courier', '', 12.0)
	pdf.set_xy(17.0, 26.5)
	pdf.set_font('courier', '', 8.0)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt="", border=0) #Datos[2] slogan
	pdf.set_xy(17.0, 34.5)
	pdf.set_font('courier', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=Datos[5], border=0, )
	pdf.set_xy(115.0, 39.5)
	pdf.set_font('courier', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt="Atendido por: ", border=0, )
	pdf.set_xy(145.0, 39.5)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=db.SelectUser(datos_items[0][7])[0][1], border=0, )
	
    #Datos del cliente
	nombre = ""
	for i in datos_sale[3].split(" "): nombre = nombre+i.capitalize()+" "

	
	if(str(datos[0][4])=="1"):
		pdf.set_fill_color(244, 244,244 )
	else:
		pdf.set_fill_color(255, 255,204 )

	pdf.set_xy(15.0, 45.0)
	pdf.cell(ln=0, h=5.0, align='L', w=180.0, txt='', fill=1)

	pdf.set_line_width(0.0)
	pdf.line(15.0, 50.0, 185.0, 50.0) #Linea de cabecera
	pdf.set_font('courier', '', 10.0)

	pdf.set_xy(17.0, 44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=13.0, txt='Cliente: '+nombre, border=0)

	pdf.set_xy(110.0, 44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Nit: '+datos_sale[5].upper(), border=0)

	pdf.set_xy(163.0, 44.3)
	if(str(datos[0][4])=="1"):
		est = "CREDITO"
	else:
		est = "PAGADO"
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt=est, border=0)


	pdf.set_xy(133.0, 69.0)
	#pdf.cell(ln=0, h=6.0, align='L', w=42.0, txt='Springfield', border=0)
	pdf.set_line_width(0.0)
	pdf.line(15.0, 50.0, 195.0, 50.0) #linea header de productos
	pdf.set_line_width(0.0)
	pdf.line(35.0, 50.0, 35.0, 130.0) #Separador 3
	pdf.line(50.0, 50.0, 50.0,   130.0) #Separador 2
	pdf.line(150.0, 50.0, 150.0, 130.0) #Separador 4
	pdf.line(172.0, 50.0, 172.0, 135.0) #Separador 5
	pdf.set_font('courier', '', 8.0)
	pdf.set_xy(14.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt='Codigo', border=0)
	pdf.set_xy(35.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Cantidad', border=0)
	pdf.set_xy(50.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Producto', border=0)
	pdf.set_xy(150.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Precio', border=0)
	pdf.set_xy(173.0, 50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt='Total', border=0)

	pdf.set_line_width(0.0)
	pdf.line(15.0, 55.0, 195.0, 55.0)

	lineaN = 55.0
	contador = 0
	for elemento in datos_items:
		contador = contador+1
		pdf.set_xy(15.0, lineaN)
		pdf.set_font('courier', '', 8.0)
		if len(elemento[6]) > 10:
			elemento[6] = elemento[6][:10]
		pdf.cell(ln=0, h=5.0, align='L', w=15.0, txt=elemento[6].upper(), border=0) # CODIGO

		pdf.set_xy(35.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt=str(elemento[4]), border=0)  # CANTIDAD


		pdf.set_xy(35.0+15, lineaN)
		if len(elemento[5]) > 57:
			pdf.cell( h=5.0, align='L', w=100.0, txt=elemento[5][:57], border=0) # NOMBRE
		else:
			pdf.cell(ln=0, h=5.0, align='L', w=100.0, txt=elemento[5], border=0) # NOMBRE

		pdf.set_xy(150.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.TSep(self.formatCant(elemento[3])), border=0) # PRECIO

		pdf.set_xy(173.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=self.TSep(self.formatCant(elemento[3]*elemento[4])), border=0) # TOTAL
		lineaN = lineaN+4

	pdf.set_line_width(0.0)
	pdf.line(15.0, 130.0, 195.0, 130.0)

	pdf.set_xy(70.0, 130.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Total', border=0)

	pdf.set_xy(173.0, 130.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.TSep(self.formatCant(datos_sale[2])), border=0)


	
#------------ SEGUNDA PARTE ---------------#

	ln2 = 141
	pdf.set_line_width(0.0)
	pdf.rect(15.0, ln2+45.0, 180.0, 90.0) # Marco Principal

	pdf.rect(15.0, ln2+9.0, 180.0, 35.8) # header datos principales
	pdf.set_font('arial', 'B', 13.0)
	pdf.set_xy(15.0, ln2+10.5)
	pdf.cell(ln=0, h=5.5, align='C', w=180.0, txt='Comprobante de venta', border=0)
 # LOGOTIPO
	pdf.image(logo, 27.0, ln2+10.0, link='', type='', w=0, h=20)
	pdf.set_font('courier', 'B', 16.0)
	pdf.set_xy(ln2+95.0, 18.0)
	#pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt='Hola 1', border=0)
    # DATOS DE LA EMPRESA
	pdf.set_font('courier', '', 8.0)
	pdf.set_xy(115.0, ln2+25.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Tel:              "+str(Datos[3]), border=0)
	pdf.set_xy(115.0, ln2+28.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Web:              "+str(Datos[4]), border=0)
	pdf.set_xy(115.0, ln2+31.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="E-mail:           "+Datos[7], border=0)
	pdf.set_xy(115.0, ln2+34.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="NIT:              "+str(Datos[8]), border=0)

	pdf.set_font('courier', '', 7.0)
	pdf.set_xy(115.0, ln2+35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=60.0, txt='Fecha:', border=0)
	pdf.set_xy(145.0, ln2+35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=40.0, txt=datos_sale[1], border=0)

	pdf.set_xy(95.0, ln2+21.5)
	pdf.set_line_width(0.0)
#	pdf.line(100.0, 25.0, 100.0, 57.0) #linea vertical header
	pdf.set_font('arial', 'B', 14.0)
	pdf.set_xy(143.0, ln2+15.5)
	pdf.cell(ln=0, h=9.5, align='L', w=60.0, txt=facturaNumero, border=0)
	pdf.set_xy(115.0, ln2+17.5)
	pdf.cell(ln=0, h=5.5, align='L', w=10.0, txt='N\xba: ', border=0)
	pdf.set_font('courier', 'B', 12.0)
	pdf.set_xy(17.0, ln2+30.5)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt=Datos[1], border=0)#Datos[1] nombre
	pdf.set_font('courier', '', 12.0)
	pdf.set_xy(17.0, ln2+26.5)
	pdf.set_font('courier', '', 8.0)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt="", border=0) #Datos[2] slogan
	pdf.set_xy(17.0, ln2+34.5)
	pdf.set_font('courier', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=Datos[5], border=0, )

	pdf.set_xy(115.0, ln2+39.5)
	pdf.set_font('courier', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt="Atendido por: ", border=0, )
	pdf.set_xy(145.0, ln2+39.5)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=db.SelectUser(datos_items[0][7])[0][1], border=0, )



    #Datos del cliente
	nombre = ""
	for i in datos_sale[3].split(" "): nombre = nombre+i.capitalize()+" "

	if(str(datos[0][4])=="1"):
		pdf.set_fill_color(244, 244,244 )
	else:
		pdf.set_fill_color(255, 255,204 )


	pdf.set_xy(15.0, ln2+45.0)
	pdf.cell(ln=0, h=5.0, align='L', w=180.0, txt='', fill=1)

	pdf.set_line_width(0.0)
	pdf.line(15.0, ln2+50.0, 195.0, ln2+50.0) #Linea de cabecera
	pdf.set_font('courier', '', 10.0)

	pdf.set_xy(17.0, ln2+44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=13.0, txt='Cliente: '+nombre, border=0)

	pdf.set_xy(110.0, ln2+44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Nit: '+datos_sale[5].upper(), border=0)

	pdf.set_xy(163.0, ln2+44.3)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt=est, border=0)


	pdf.set_xy(133.0, ln2+69.0)
	#pdf.cell(ln=0, h=6.0, align='L', w=42.0, txt='Springfield', border=0)
	pdf.set_line_width(0.0)
	pdf.line(15.0, ln2+50.0, 195.0, ln2+50.0) #linea header de productos
	pdf.set_line_width(0.0)
	pdf.line(35.0, ln2+50.0, 35.0, ln2+130.0) #Separador 3
	pdf.line(50.0, ln2+50.0, 50.0,   ln2+130.0) #Separador 2
	pdf.line(150.0, ln2+50.0, 150.0, ln2+130.0) #Separador 4
	pdf.line(172.0, ln2+50.0, 172.0, ln2+135.0) #Separador 5
	pdf.set_font('courier', '', 8.0)

	pdf.set_xy(14.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt='Codigo', border=0)

	pdf.set_xy(35.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Cantidad', border=0)

	pdf.set_xy(50.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Producto', border=0)

	pdf.set_xy(150.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Precio', border=0)

	pdf.set_xy(173.0, ln2+50.0)
	pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt='Total', border=0)

	pdf.set_line_width(0.0)
	pdf.line(15.0, ln2+55.0, 195.0, ln2+55.0)

	lineaN = ln2+55.0
	contador = 0
	for elemento in datos_items:
		contador = contador+1
		pdf.set_xy(15.0, lineaN)
		pdf.set_font('courier', '', 8.0)
		if len(elemento[6]) > 10:
			elemento[6] = elemento[6][:10]
		pdf.cell(ln=0, h=5.0, align='L', w=15.0, txt=elemento[6].upper(), border=0) # CODIGO

		pdf.set_xy(35.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt=str(elemento[4]), border=0)  # CANTIDAD


		pdf.set_xy(35.0+15, lineaN)
		if len(elemento[5]) > 57:
			pdf.cell( h=5.0, align='L', w=100.0, txt=elemento[5][:57], border=0) # NOMBRE
		else:
			pdf.cell(ln=0, h=5.0, align='L', w=100.0, txt=elemento[5], border=0) # NOMBRE

		pdf.set_xy(150.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.TSep(self.formatCant(elemento[3])), border=0) # PRECIO

		pdf.set_xy(173.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=self.TSep(self.formatCant(elemento[3]*elemento[4])), border=0) # TOTAL
		lineaN = lineaN+4

	pdf.set_line_width(0.0)
	pdf.line(15.0, ln2+130.0, 195.0, ln2+130.0)

	pdf.set_xy(70.0, ln2+130.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Total', border=0)

	pdf.set_xy(173.0, ln2+130.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.TSep(self.formatCant(datos_sale[2])), border=0)




	pdf.output('invoice.pdf', 'F')
	if sys.platform.startswith("linux"):
		os.system("evince ./invoice.pdf")
	else:
		#os.system("invoice.pdf")
		import subprocess
		subprocess.Popen("invoice.pdf", shell=True, bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Example #33
0
    def ImrimirPDF(self, prod_table,SubTotal,TAX,Total,stDate,endDate):
	# Obtener los datos de la tienda/empresa desde la base de datos
	Datos = db.SelectConfigNS()
	if hasattr(sys, 'frozen'):
		logo = os.path.join('resources', 'logo.png')
	else:
		logo = os.path.join(os.path.split(__file__)[0],  'resources', 'logo.png')

	pdf = FPDF()
	pdf.add_page()
	pdf.set_font('times', '', 13.0)
	pdf.set_xy(105.0, 16.0)
	pdf.cell(ln=0, h=22.0, align='L', w=75.0, txt='', border=0)
	pdf.set_line_width(0.0)
	pdf.rect(15.0, 15.0, 170.0, 61.0)
	pdf.set_line_width(0.0)
	#pdf.rect(95.0, 15.0, 10.0, 10.0)
	pdf.image(logo, 20.0, 16.0, link='', type='', w=0, h=17)
	pdf.set_font('times', 'B', 16.0)
	pdf.set_xy(95.0, 18.0)
	#pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt='Hola 1', border=0)
	pdf.set_font('times', '', 8.0)
	pdf.set_xy(115.0, 40.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Tel:               "+str(Datos[3]), border=0)
	pdf.set_xy(115.0, 43.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Web:              "+str(Datos[4]), border=0)
	pdf.set_xy(115.0, 46.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="E-mail:           "+Datos[7], border=0)
	pdf.set_xy(115.0, 49.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="NIT:               "+str(Datos[8]), border=0)
	pdf.set_font('times', 'B', 7.0)
	pdf.set_xy(95.0, 21.5)
	#pdf.cell(ln=0, h=4.5, align='C', w=10.0, txt='Hola 3', border=0)
	pdf.set_line_width(0.0)
	pdf.line(100.0, 15.0, 100.0, 57.0)
	pdf.set_font('arial', 'B', 18.0)
	pdf.set_xy(137.0, 30.5)
	pdf.cell(ln=0, h=9.5, align='L', w=60.0, txt='', border=0)
	pdf.set_xy(113.0, 25.5)
	pdf.cell(ln=0, h=5.5, align='C', w=60.0, txt='Reporte de Ventas ', border=0)
	pdf.set_font('times', 'B', 12.0)
	pdf.set_xy(17.0, 32.5)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt=Datos[1], border=0)
	pdf.set_font('times', '', 12.0)
	pdf.set_xy(17.0, 36.5)
	pdf.set_font('times', '', 8.0)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt=Datos[2], border=0)
	pdf.set_xy(17.0, 43.5)
	pdf.set_font('times', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=Datos[5], border=0, )
	pdf.set_xy(115.0, 35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=60.0, txt='Fecha:', border=0)
	pdf.set_xy(130.0, 35.0)
	date = time.localtime()[:5]
	date = (date[2], date[1], date[0], date[3], date[4],)
	date = "%d/%d/%d %d:%02d" % date
	pdf.cell(ln=0, h=7.0, align='L', w=40.0, txt=date, border=0)
	pdf.set_line_width(0.0)
	pdf.line(15.0, 57.0, 185.0, 57.0)
	# Mostrar SubTotal, Iva y total de las ventas
	pdf.set_font('times', '', 10.0)
	pdf.set_xy(17.0, 59.0)
	pdf.cell(ln=0, h=6.0, align='L', w=13.0, txt='Sub-total:  ', border=0)
	pdf.set_xy(35.0, 59.0)
	pdf.cell(ln=0, h=6.0, align='L', w=140.0, txt=SubTotal, border=0)
	pdf.set_xy(17.0, 64.0)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='IVA:        ', border=0)
	pdf.set_xy(35.0, 64.0)
	pdf.cell(ln=0, h=6.0, align='L', w=125.0, txt=TAX, border=0)
	pdf.set_xy(17.0, 69.0)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Total:       ', border=0)
	pdf.set_xy(35.0, 69.0)
	pdf.cell(ln=0, h=6.0, align='L', w=80.0, txt=Total, border=0)
	
	
	
	# Mostrar fecha de inicio y de finalizacion
	pdf.set_xy(115.0, 58.0)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Fecha de inicio:', border=0)
	pdf.set_xy(135.0, 62.0)
	pdf.cell(ln=0, h=6.0, align='L', w=42.0, txt=stDate, border=0)
	pdf.set_xy(115.0, 66.0)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Fecha de finalizacion:', border=0)
	pdf.set_xy(135.0, 70.0)
	pdf.cell(ln=0, h=6.0, align='L', w=42.0, txt=endDate, border=0)
	
	# Imprimir listado de productos vendidos
	lineaN = 80-7
	for sale in prod_table:
		lineaN = lineaN+7
		PreLineas = 0
		for prod in sale[1]:
			## Precalcular las lineas que se usaran en la tabla
			if len(prod[5]) >67:
				PreLineas = PreLineas+10
			else:
				PreLineas = PreLineas+10
			PreLineas = PreLineas+5
		if (lineaN+PreLineas+5) > 275:
			pdf.add_page()
			lineaN = 10
			#PreLineas = PreLineas- 10
		#Imprimir los datos del cliente
		pdf.set_line_width(0.0)
		pdf.line(15.0, lineaN, 15.0, lineaN+7) # linea vertical de borde iz
		pdf.line(185.0, lineaN, 185.0, lineaN+7) # linea vertical de borde de
		pdf.line(15.0, lineaN, 185.0, lineaN) # linea horizontal
		pdf.set_line_width(0.0)
		pdf.line(80.0, lineaN, 80.0, lineaN+7) # linea verticals
		pdf.line(120.0, lineaN, 120.0, lineaN+7) # linea vertical 
		pdf.line(150.0, lineaN, 150.0, lineaN+7) # linea vertical 
		pdf.set_font('times', '', 8.0)
		pdf.set_xy(15.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Cliente: '+sale[0][3], border=0)
		pdf.set_xy(81.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=15.0, txt='Nit: '+sale[0][4], border=0)
		pdf.set_xy(121.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Fecha: '+sale[0][1], border=0)
		pdf.set_xy(151.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Total: '+self.TSep(sale[0][2]), border=0)
		lineaN = lineaN+7
		#imprimir las lineas para formar el cuadro
		pdf.line(15.0, lineaN, 15.0, lineaN+7) # linea vertical de borde iz
		pdf.line(185.0, lineaN, 185.0, lineaN+7) # linea vertical de borde de
		pdf.line(15.0, lineaN, 185.0, lineaN) # linea horizontal
		pdf.set_line_width(0.0)
		pdf.line(20.0, lineaN, 20.0, lineaN+7) # linea vertical
		pdf.line(37.0, lineaN, 37.0, lineaN+7) # linea vertical
		pdf.line(130.0, lineaN, 130.0, lineaN+7) # linea vertical
		pdf.line(150.0, lineaN, 150.0, lineaN+7) # linea vertical
		pdf.line(165.0, lineaN, 165.0, lineaN+7) # linea verticalpdf.line(15.0, lineaN, 185.0, lineaN) # linea horizontal

		
		
		#Imprimir los pre-datos de los productos
		pdf.set_font('times', '', 8.0)
		pdf.set_xy(14.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=' No.', border=0)
		pdf.set_xy(20.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt='Codigo', border=0)
		pdf.set_xy(37.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Producto', border=0)
		pdf.set_xy(135.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Precio', border=0)
		pdf.set_xy(150.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Cantidad', border=0)
		pdf.set_xy(165.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt='Total', border=0)
		pdf.set_line_width(0.0)
		pdf.line(15.0, lineaN+7, 185.0, lineaN+7)
		#Imprimir los productos comprados por el cliente
		contador = 0
		lineaN = lineaN+7
		for prod in sale[1]:
			contador = contador+1
			
			#Imprimir los pre-datos de los productos
			pdf.set_font('times', '', 8.0)
			pdf.set_xy(14.0, lineaN)
			pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=str(contador), border=0)
			pdf.set_xy(20.0, lineaN)
			pdf.set_font('times', '', 5.0)
			pdf.cell(ln=0, h=5.0, align='C', w=15.0, txt=prod[6], border=0)
			pdf.set_xy(37.0, lineaN)
			pdf.set_font('times', '', 8.0)
			if len(prod[5]) >67:
				pdf.multi_cell( h=5.0, align='L', w=93.0, txt=prod[5]+"  Linea:"+str(lineaN), border=0)
				pdf.line(15.0, lineaN, 15.0, lineaN+10) # linea vertical de borde iz
				pdf.line(185.0, lineaN, 185.0, lineaN+10) # linea vertical de borde de
			else:
				pdf.cell(ln=0, h=5.0, align='L', w=93.0, txt=prod[5]+"  Linea:"+str(lineaN), border=0)
				pdf.line(15.0, lineaN, 15.0, lineaN+5) # linea vertical de borde iz
				pdf.line(185.0, lineaN, 185.0, lineaN+5) # linea vertical de borde de
			pdf.set_xy(135.0, lineaN)
			pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=self.formatCant(prod[3]), border=0)
			pdf.set_xy(150.0, lineaN)
			pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=str(prod[4]), border=0)
			pdf.set_xy(165.0, lineaN)
			pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=self.TSep(prod[3]*prod[4]), border=0)
			pdf.set_line_width(0.0)
			
			if len(prod[5]) >67:
				# Imprimir lineas separadoras de los datos
				pdf.set_line_width(0.0)
				pdf.line(20.0, lineaN, 20.0, lineaN+10) # linea vertical
				pdf.line(37.0, lineaN, 37.0, lineaN+10) # linea vertical
				pdf.line(130.0, lineaN, 130.0, lineaN+10) # linea vertical
				pdf.line(150.0, lineaN, 150.0, lineaN+10) # linea vertical
				pdf.line(165.0, lineaN, 165.0, lineaN+10) # linea vertical
				lineaN = lineaN+10
			
			else:
				# Imprimir lineas separadoras de los datos
				pdf.set_line_width(0.0)
				pdf.line(20.0, lineaN, 20.0, lineaN+5) # linea vertical
				pdf.line(37.0, lineaN, 37.0, lineaN+5) # linea vertical
				pdf.line(130.0, lineaN, 130.0, lineaN+5) # linea vertical
				pdf.line(150.0, lineaN, 150.0, lineaN+5) # linea vertical
				pdf.line(165.0, lineaN, 165.0, lineaN+5) # linea vertical
				lineaN = lineaN+5
		pdf.line(15.0, lineaN, 185.0, lineaN)
		
			
			
			
	
	lineaN = 89.0
	contador = 0
	datos_items = []
	for elemento in datos_items:
		contador = contador+1
		pdf.set_xy(15.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='C', w=5.0, txt=str(contador), border=0)
		pdf.set_xy(20.0, lineaN)
		pdf.set_font('times', '', 5.0)
		pdf.cell(ln=0, h=5.0, align='C', w=10.0, txt=elemento[6], border=0)
		pdf.set_font('times', '', 8.0)
		pdf.set_xy(30.0, lineaN)
		if len(elemento[5]) > 74:
			pdf.multi_cell( h=5.0, align='L', w=100.0, txt=elemento[5], border=0)
		else:
			pdf.cell(ln=0, h=5.0, align='L', w=100.0, txt=elemento[5], border=0)
		pdf.set_xy(130.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=str(self.formatCant(elemento[3])), border=0)
		pdf.set_xy(154.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=str(elemento[4]), border=0)
		pdf.set_xy(165.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=str(self.formatCant(elemento[3]*elemento[4])), border=0)
		if len(elemento[5]) > 74:
			lineaN = lineaN+10
		else:
			lineaN = lineaN+5
	pdf.output('report.pdf', 'F')
	if sys.platform.startswith("linux"):
		os.system("evince ./report.pdf")
	else:
		os.system("report.pdf")
		
Example #34
0
    def ImrimirPDF(self, saleId,IMPRIMIRr):
	# Obtener los datos de la base de datos (datos de la venta y los elementos)
	datos = db.Salerecord(saleId)
	# guardar los datos de la venta en datos_sale
	datos_sale  = datos[0]
	#Guardar los datos de los elementos de la venta en datos_items 
	datos_items = datos[1]
	# Formatear el numero de la venta (ej: 0000000023)
	facturaNumero = str(("0"*(10-len(str(saleId))))+str(saleId))
	# Obtener los datos de la tienda/empresa desde la base de datos
	Datos = db.SelectConfigNS()
	pdf = FPDF()
	pdf.add_page()
	MargL = 70
	if IMPRIMIRr:
            MargT = 20
        else:
            MargT = 5
#	pdf.add_font('FangSong',"")
	pdf.set_font('Courier', 'B', 8.5)
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=5.0, align='C', w=60.0, txt=Datos[1], border=0)
	pdf.set_font('Courier', '', 8.5)
	MargT = MargT+2.5
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=5.0, align='C', w=60.0, txt=Datos[2], border=0)
	MargT = MargT+4
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=4.0, align='C', w=60.0, txt="NIT: "+str(Datos[8]), border=0)
	MargT = MargT+3
	pdf.set_xy(MargL, MargT)
	pdf.multi_cell(h=3, align='C', w=60.0, txt=Datos[5], border=0, )
	MargT = MargT+5
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=4.0, align='C', w=60.0, txt="E-mail: "+Datos[7], border=0)
	MargT = MargT+3
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=4.0, align='C', w=60.0, txt="Tel: "+str(Datos[3]), border=0)
	MargT = MargT+3 #25.5
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=4.0, align='C', w=60.0, txt="Web: "+str(Datos[4]), border=0)
	MargT = MargT+1 #26.5
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=7.4, align='C', w=60.0, txt='Fecha: '+str(datos_sale[1]), border=0)
	nombre = ""
	for i in datos_sale[3].split(" "): nombre = nombre+i.capitalize()+" "
	MargT = MargT+2 #28.5
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=9.5, align='C', w=60.0, txt='Comprobante N\xba: '+str(facturaNumero), border=0)
	MargT = MargT+6 #34.5
	pdf.set_xy(MargL, MargT)
	pdf.set_font('Arial', '', 9.0)
	pdf.cell(ln=0, h=6.0, align='L', w=60.0, txt='Cliente: '+nombre.decode("utf8"), border=0)
	MargT = MargT+2.5 #35.0
	pdf.set_xy(MargL, MargT)
	pdf.set_font('Courier', '', 9.0)
	pdf.cell(ln=0, h=6.0, align='L', w=60.0, txt='Nit: '+str(datos_sale[5].upper()), border=0)

	#Titulos para los productos
	pdf.set_font('Courier', 'B', 9.0)
	MargT = MargT+6.5 #41.5
	pdf.set_xy(MargL, MargT)
	pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt='Codigo', border=0)
	pdf.set_xy(MargL+20, MargT)
	pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt='Producto', border=0)
	pdf.set_xy(MargL+41, MargT)
	pdf.cell(ln=0, h=5.0, align='L', w=13.0, txt='Cant.', border=0)
	pdf.set_xy(MargL+50.5, MargT)
	pdf.cell(ln=0, h=5.0, align='R', w=14.0, txt=' Total', border=0)
	pdf.set_font('Courier', '', 9.0)
	MargT = MargT+4 #45.5
	pdf.line(MargL, MargT, MargL+68, MargT)

	# TOTAL DE LA VENTA
	#pdf.cell(ln=0, h=6.0, align='C', w=18.0, txt='Total:', border=0)
	#pdf.set_xy(MargL, 69.0)
	#pdf.cell(ln=0, h=6.0, align='C', w=80.0, txt=self.formatCant(datos_sale[2]), border=0)

	#Productos
	lineaN = MargT-1 #44.5
	for elemento in datos_items:
		pdf.set_xy(MargL, lineaN)
		if len(elemento[6]) > 10:
                    pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=elemento[6][0:10], border=0)
                else:
                    pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=elemento[6], border=0)
		pdf.set_xy(MargL+20, lineaN)
		if len(elemento[5]) > 12:
			pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=elemento[5][0:12], border=0)
		else:
			pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=elemento[5], border=0)
		pdf.set_xy(MargL+45, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=10.0, txt=str(elemento[4]), border=0)
		pdf.set_xy(MargL+50.5, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=5.0, txt="Q ", border=0)
		pdf.set_font('Courier', '', 6.0)
		pdf.cell(ln=0, h=5.0, align='R', w=14.0, txt=str(self.formatCant(elemento[3]*elemento[4])), border=0)
		pdf.set_font('Courier', '', 9.0)
		lineaN = lineaN+3
	pdf.line(MargL, lineaN+1, MargL+68, lineaN+1)

	
        #Subtotal, IVA y Total
	pdf.set_xy(MargL, lineaN)
	pdf.cell(ln=0, h=9.0, align='L', w=60.0, txt='Subtotal: Q ', border=0)
	pdf.set_xy(MargL, lineaN+2.5)
	pdf.cell(ln=0, h=9.0, align='L', w=60.0, txt='IVA:      Q ', border=0)
	pdf.set_xy(MargL, lineaN+5)
	pdf.cell(ln=0, h=9.0, align='L', w=60.0, txt='Total:    Q ', border=0)

	pdf.set_xy(MargL+20.5, lineaN)
	pdf.cell(ln=0, h=9.0, align='R', w=22.0, txt=str(self.TSep(self.formatCant((datos_sale[2]-datos_sale[6])))), border=0)
	pdf.set_xy(MargL+20.5, lineaN+2.5)
	pdf.cell(ln=0, h=9.0, align='R', w=22.0, txt=str(self.TSep(self.formatCant(datos_sale[6]))), border=0)
	pdf.set_xy(MargL+20.5, lineaN+5)
	pdf.cell(ln=0, h=9.0, align='R', w=22.0, txt=str(self.TSep(self.formatCant(datos_sale[2]))), border=0)
	
	pdf.output('invoice.pdf', 'F')
	print
	print
	print
	print
	print "Imprimir?  "+str(IMPRIMIRr)
	print
	print
	print
	if IMPRIMIRr:
            pc = os.name
            filename = "invoice.pdf"
            if pc == 'posix' :
                os.system ('lp -q100 ' + filename)
            elif pc == 'nt' :
                import win32api
                win32api.ShellExecute(0, 'print', filename, None, '.', 0)
            else:
                print "El sistema operativo no es NT ni POSIX"
        else:
            if sys.platform.startswith("linux"):
                    os.system("evince ./invoice.pdf")
            else:
                    #os.system("invoice.pdf")
                    import subprocess
                    p = subprocess.Popen("invoice.pdf", shell=True, bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    def create_pdf(self):
        """Build the PDF file from user-supplied information"""
        
        # Dictionary of variables collected from gui, to be passed to method_graf()
        self.variabledic = {"methodofservice": self.methodText.get(),
            "documents": self.docsservedText.get().upper(),
            "target": self.targetText.get(),
            "dateandtime": self.monthText.get() + " " + self.dayText.get() + 
                ", " + self.yearText.get() + ", at " + self.hourText.get() + 
                ":" + self.minuteText.get() + " " + self.ampmText.get(),
            "location": self.locationText.get(),
            "subperson": self.subpersonText.get(),
            "subrelation": self.subrelationText.get(), 
            "parentname": self.parentText.get(), 
            "tempguard": self.tempText.get(), 
            "committed": self.committedBool.get(), 
            "adminname": self.adminText.get(), 
            "agentname": self.agentText.get(),
            "sex": self.sexText.get()
            }        
        
        pdf=FPDF("P", "pt", "Letter")
        pdf.set_margins(36,36)
        pdf.alias_nb_pages()
        pdf.add_page()
                
        # State, County & Court        
        pdf.set_font("Times", "", 12)
        pdf.multi_cell(h = 18, w = 540, align = "L", txt = (
            "IN THE "+self.courtText.get().upper()+" COURT OF\n"+
            self.countyText.get().upper()+" COUNTY, "+self.stateText.get().upper()))
        pdf.ln(30)
        
        # Plaintiff
        pcursor = pdf.get_y()
        pdf.multi_cell(h=18, w=400, align = "L", txt=self.plaintiffEntry.get(0.0,'end').upper())
        newpcursor = pdf.get_y()
        pdf.set_xy(400, pcursor)
        pdf.cell(w = 0, align = "R", txt = "PLAINTIFF")
        pdf.set_xy(0, newpcursor)
        pdf.ln(18)
        
        # Case Number
        pdf.cell(h = 18, w = 20, align = "L", txt = "V.")
        pdf.cell(h = 18, w = 500, align = "C", txt = "CASE NO. "+self.caseNoText.get().upper())
        pdf.ln(30)
        
        # Defendant
        pcursor = pdf.get_y()
        pdf.multi_cell(h=18, w=400, align = "L", txt=self.defendantEntry.get(0.0,'end').upper())
        newpcursor = pdf.get_y()
        pdf.set_xy(400, pcursor)
        pdf.cell(h = 18, w = 0, align = "R", txt = "DEFENDANT")
        pdf.set_xy(0, newpcursor)
        pdf.ln(18)

        # Title
        pdf.set_font("Times", "U", 12)
        pdf.cell(h = 24, w = 0, align = "C", txt = "AFFIDAVIT OF SERVICE")
        pdf.ln(36)
        
        # Commencement
        pdf.set_font("Times", "", 12)
        pdf.multi_cell(h = 30, w = 540, align = "L", txt = (
            "     Comes now " + self.serverText.get() + ", who, being duly "
            "sworn, deposes and says:"))

        # Paragraph with details of service (multi-line), called from method_graf() function
        pdf.multi_cell(h = 30, w = 540, align = "L", txt = self.method_graf(**self.variabledic))
        
        # Comments
        if len(self.commentsText.get()) > 0:
            pdf.multi_cell(h = 30, w = 540, align = "L", txt = "     " + self.commentsText.get())
        
        # Not a party/No interest/Further affiant sayeth not, etc.
        pdf.multi_cell(h = 30, w = 540, align = "L", txt = (
            "     I am not a party to this action, and I have no interest in it. \n"
            "     Further affiant sayeth not."))
        pdf.ln(40)
        
        # Signature/Notary section
        pdf.line(270,pdf.get_y(),540,pdf.get_y())
        pdf.set_x(270)
        pdf.cell(h = 24, w = 0, align = "L", txt = self.serverText.get())
        pdf.ln(24)
        pdf.set_x(270)
        pdf.multi_cell(h = 18, w = 0, align = "L", txt = self.servaddrEntry.get(0.0,"end"))
        pdf.ln(24)
        pdf.set_x(36)
        pdf.cell(h = 18, w = 270, align = "L", txt = "Subscribed and sworn to before me this date:")
        pdf.line(270,pdf.get_y()+18,540,pdf.get_y()+18)
        pdf.ln(40)
        pdf.line(270,pdf.get_y()+18,540,pdf.get_y()+18)
        pdf.ln(24)
        pdf.set_x(270)
        pdf.cell(h = 18, w = 270, align = "L", txt = "Notary Public")
        pdf.ln(36)
        pdf.set_x(270)
        pdf.cell(h = 18, w = 270, align = "L", txt = "My commission expires:")
        pdf.line(400,pdf.get_y()+18,540,pdf.get_y()+18)
        
        # write PDF
        pdf.output(self.filenameText.get()+".pdf", "F")
        return None
Example #36
0
    def to_pdf(self, **kwargs):
        from fpdf import FPDF
        import random
        paper_format = kwargs.get('paper_format', 'a4')
        paper = self.PAPER_SIZES[string.lower(paper_format)]
        font_scale = kwargs.get('font_scale', 1)
        font_name = kwargs.get('font_name')
        colorize = kwargs.get('colorize', False)
        if font_name is not None and not colorize:
            self.generate_luminosity_mapping(font_name)
        orientation = kwargs.get('orientation')
        if self.im.width > self.im.height:
            orientation = 'l'
        else:
            orientation = 'p'
        if orientation == 'l':
            paper.width, paper.height = paper.height, paper.width

        inner = Size(ceil(paper.width - self.margins.left - self.margins.right),
                     ceil(paper.height - self.margins.top - self.margins.bottom))
        imgpixels = Size(self.im.width, self.im.height)
        scale = min(inner.width, inner.height) / max(imgpixels.width, imgpixels.height)
        offset = Point(self.margins.left + (inner.width - imgpixels.width * scale) / 2,
                       self.margins.bottom + (inner.height - imgpixels.height * scale) / 2)

        pdf = FPDF(unit='mm', format=paper_format.upper(), orientation=orientation.upper())
        pdf.set_compression(True)
        pdf.set_title('ASCII Art')
        pdf.set_author('Oliver Lau <*****@*****.**> - Heise Medien GmbH & Co. KG')
        pdf.set_creator('asciifier')
        pdf.set_keywords('retro computing art fun')
        pdf.add_page()

        if font_name is not None:
            pdf.add_font(font_name, fname=font_name, uni=True)
        else:
            font_name = 'Courier'
        pdf.set_font(font_name, '', mm2pt(scale * font_scale))

        for y in range(0, self.im.height):
            yy = offset.y + scale * y
            for x in range(0, self.im.width):
                c = self.result[x][y]
                if c != ' ':
                    if colorize is True:
                        r, g, b = self.im.getpixel((x, y))
                        pdf.set_text_color(r, g, b)
                        pdf.text(offset.x + x * scale, yy, random.choice(Asciifier.COLOR_CHARS))
                    else:
                        pdf.text(offset.x + x * scale, yy, c)

        crop_area = Margin(offset.y - scale,
                           offset.x + (self.im.width - 1 + font_scale) * scale,
                           offset.y + (self.im.height - 2 + font_scale) * scale,
                           offset.x)

        if kwargs.get('cropmarks', False):
            pdf.set_draw_color(0, 0, 0)
            pdf.set_line_width(pt2mm(0.1))
            for p in [Point(crop_area.left, crop_area.top),
                      Point(crop_area.right, crop_area.top),
                      Point(crop_area.right, crop_area.bottom),
                      Point(crop_area.left, crop_area.bottom)]:
                pdf.line(p.x - 6, p.y, p.x - 2, p.y)
                pdf.line(p.x + 2, p.y, p.x + 6, p.y)
                pdf.line(p.x, p.y - 6, p.x, p.y - 2)
                pdf.line(p.x, p.y + 2, p.x, p.y + 6)

        if kwargs.get('logo'):
            logo_width = 20
            pdf.image(kwargs.get('logo'),
                      x=(crop_area.right - crop_area.left - logo_width / 2) / 2,
                      y=crop_area.bottom + 10,
                      w=logo_width)

        return pdf.output(dest='S')
Example #37
0
def genpdf(request, profID):
    teachObj = Teach.objects.get(pk= int(profID)) 
    pdf = FPDF('P', 'mm', 'A4')
    pdf.add_page()
    
    pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)
    pdf.set_font('DejaVu', '', 14)
    
    pdf.image('group3/trarachakarn.png',20,20,20)
    pdf.ln(25)
    
    proID = ''
    firstname = ''
    lastname = ''
    shortname = ''
    department = ''
    faculty = ''
    sahakornAccount = ''
    tell = ''
    email = ''
    
    try:
        proID = teachObj.prof.profID
    except:
        proID = 'None'

    try:
        firstname = teachObj.prof.firstName
    except:
        firstname = 'None'
 
    try:
        lastname = teachObj.prof.lastName
    except:
        lastname = 'None'

    try:
        shortname  = teachObj.prof.shortName
    except:
        shortname = 'None'

    try:
        department = teachObj.prof.department
    except:
        department = 'None'
    
    try:
        faculty = teachObj.prof.faculty
    except:
        faculty = 'None'

    try:
        sahakornAccount = teachObj.prof.sahakornAccount
    except:
        sahakornAccount = 'None'

    try:
        tell = teachObj.prof.tell
    except:
        tell = 'None'

    try:
        email = teachObj.prof.email
    except:
        email = 'None'
        
    pdf.add_font('Kinnari-Bold', '', 'Kinnari-Bold.ttf', uni=True)
    pdf.set_font('Kinnari-Bold', '', 18)
    pdf.cell(0, 10, u'                         บันทึกข้อความ')
    pdf.ln(10)
    pdf.add_font('Kinnari', '', 'Kinnari.ttf', uni=True)
    pdf.set_font('Kinnari', '', 12)
    pdf.cell(0, 10, u'         ส่วนราชการ ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์ คณะวิศวกรรมศาสตร์  โทร. ๘๕๑๘')
    pdf.line(46,52,180,52)
    pdf.ln(8)
    pdf.cell(0, 10, u'         ที่  วฟ     /๒๕๕๘                                        วันที่  ')
    pdf.line(30,60,180,60)
    pdf.ln(8)
    pdf.cell(0, 10, u'         เรื่อง การจัดการเรียนการสอนสำหรับนักศึกษาโครงการพิเศษ(สองภาษา) ')
    pdf.line(30,68,180,68)
    pdf.ln(8)
    pdf.cell(0, 10, u'         เรียน หัวหน้าภาควิชา ')
    pdf.ln(8)
    pdf.cell(0, 10, u'                     ตามที่ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  ได้ขอรับบริการจัดการเรียนการ')
    pdf.ln(8)
    pdf.cell(0, 10, u'         สอนจากท่านในรายวิชา                                                      สำหรับนักศึกษา')
    pdf.ln(8)
    pdf.cell(0, 10, u'         โครงการพิเศษ (สองภาษา)  ภาคเรียนที่            นั้น')
    pdf.ln(8)
    pdf.cell(0, 10, u'                    ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  ขอให้ท่านยืนยันการจัดการเรียนการสอนใน')
    pdf.ln(8)
    pdf.cell(0, 10, u'         รายวิชาดังกล่าว ตามแบบฟอร์มด้านล่าง พร้อมตารางสอนและใบเบิกค่าสอนของอาจารย์ผู้สอนและ')
    pdf.ln(8)
    pdf.cell(0, 10, u'         ส่งคืนกลับภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  เพื่อจะได้ดำเนินการในส่วนที่เกี่ยวข้องต่อไป')
    pdf.ln(8)
    pdf.cell(0, 10, u'                        จึงเรียนมาเพื่อโปรดทราบ')
    pdf.ln(20)
    pdf.cell(0, 10, u'                                                  (ดร.นภดล   วิวัชรโกเศศ)')
    pdf.ln(8)
    pdf.cell(0, 10, u'                                              หัวหน้าภาควิศวกรรมไฟฟ้าและคอมพิวเตอร์')
    pdf.ln(14)
    pdf.cell(0, 10, u'            ..................................................................................................................................................')
    pdf.ln(8)
    pdf.cell(0, 10, u'         ชื่อผู้สอน.................................................................... รหัสผู้สอน.................................ภาควิชา ')
    pdf.ln(8)
    pdf.cell(0, 10, u'         คณะ.......................................................................รหัสวิชา...........................................ชื่อวิชา ')
    pdf.ln(8)
    pdf.cell(0, 10, u'                        ตอนเรียน           วัน              เวลา  ')
    pdf.ln(8)
    pdf.cell(0, 10, u'         ได้จัดการเรียนการสอนเป็น ')
    pdf.ln(8)
    pdf.cell(0, 10, u'                    ภาษาอังกฤษ  ')
    pdf.rect(37, 210, 3, 3)
    pdf.ln(8)
    pdf.cell(0, 10, u'                    ภาษาไทย')
    pdf.rect(37, 218, 3, 3)
    pdf.ln(8)
    pdf.cell(0, 10, u'                                            ลงชื่อ......................................อาจารย์ผู้สอน ')
    pdf.ln(8)
    pdf.cell(0, 10, u'                                            (..............................................) ')
    pdf.ln(8)
    pdf.cell(0, 10, u'                                            ลงชื่อ......................................')
    pdf.ln(8)
    pdf.cell(0, 10, u'                                            (..............................................) ')
    pdf.ln(8)   
    pdf.cell(0, 10, u'                                            หัวหน้าภาควิชา............................................')
    pdf.ln(8)

    pdf.cell(0, 10, u'' + proID)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + firstname + '   '+ lastname)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + shortname)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + department)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + faculty)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + sahakornAccount)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + tell)
    pdf.ln(8)
    pdf.cell(0, 10, u'' + email)          
    pdf.ln(20)
    pdf.cell(0, 10, u'' + teachObj.subject.subjectID)          
    pdf.ln(20)
    pdf.cell(0, 10, u'' + teachObj.subject.subjectName)          
    pdf.ln(20)
    pdf.cell(0, 10, u'' + teachObj.section.section)          
    pdf.ln(20)
    pdf.cell(0, 10, u'' + str(teachObj.section.startTime))          
    pdf.ln(20)
    pdf.cell(0, 10, u'' + teachObj.section.date)          
    pdf.ln(20)
    pdf.output("group3/uni.pdf", 'F')
    
    # next path will open pdf file in new tab on browser.
    with open('group3/uni.pdf', 'rb') as pdf: # path to pdf in directory views.
        response = HttpResponse(pdf.read(),content_type='application/pdf')
        response['Content-Disposition'] = 'filename=uni.pdf'
        return response
    pdf.closed
Example #38
0
def genpdf(request, profID): # use to generate pdf file for lend another teacher.
    teachObj = Teach.objects.get(pk= int(profID))   # get all objects teacher.
    pdf = FPDF('P', 'mm', 'A4')    # start pdf file
    pdf.add_page()                   # begin first page.
    
    pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True)  # add font
    pdf.set_font('DejaVu', '', 14)              # set font and font size
    
    pdf.image('group3/trarachakarn.png',30,25,15)   # insert image
    pdf.ln(25)    # new line
    
    proID = ''
    firstname = ''
    lastname = ''
    shortname = ''
    department = ''
    faculty = ''
    sahakornAccount = ''
    tell = ''
    email = ''
    
    subjectID = ''
    subjectName = ''
    sec = ''
    time = ''
    day = ''
    
    try: # prefix_name and academic_name
        academicPosition = teachObj.prof.academic_position
        if (academicPosition == '0'):
            academicPosition = u''
            short_academicPosition = u''
            try:
                pre_name = teachObj.prof.prefix_name
                if (pre_name == '3'):
                    pre_name = u'ดร.'
                else:
                    pre_name = u'อ.'
            except:
                pre_name = u'อ. '
        elif academicPosition == '1':
            academicPosition = u'ผู้ช่วยศาสตราจารย์ '
            short_academicPosition = u'ผศ.'
            try:
                pre_name = teachObj.prof.prefix_name
                if pre_name == '3':
                    pre_name = u'ดร.'
                else:
                    pre_name = ''
            except:
                pre_name =''
        elif academicPosition == '2':
            academicPosition =  u'รองศาสตราจารย์ '
            short_academicPosition =  u'รศ.'
            try:
                pre_name = teachObj.prof.prefix_name
                if pre_name == '3':
                    pre_name = u'ดร.'
                else:
                    pre_name = ''
            except:
                pre_name =''
        else:
            academicPosition = u'ศาสตราจารย์ '
            short_academicPosition = u'ศ.'
            try:
                pre_name = teachObj.prof.prefix_name
                if pre_name == '3':
                    pre_name = u'ดร.'
                else:
                    pre_name = ''
            except:
                pre_name =''
    except:
        academicPosition = ''
    
    try: # check all data for beware blank data.
        proID = teachObj.prof.shortName
    except:
        proID = 'None'

    try:
        firstname = teachObj.prof.firstName
    except:
        firstname = 'None'
 
    try:
        lastname = teachObj.prof.lastName
    except:
        lastname = 'None'

    try:
        shortname  = teachObj.prof.shortName
    except:
        shortname = 'None'

    try:
        department = teachObj.prof.department
    except:
        department = 'None'
    
    try:
        faculty = teachObj.prof.faculty
    except:
        faculty = 'None'

    try:
        sahakornAccount = teachObj.prof.sahakornAccount
    except:
        sahakornAccount = 'None'

    try:
        tell = teachObj.prof.tell
    except:
        tell = 'None'

    try:
        email = teachObj.prof.email
    except:
        email = 'None'
    
    try:
        subjectID = teachObj.subject.subjectID
    except:
        subjectID = 'None'
        
    try:
        subjectName = teachObj.subject.subjectName
    except:
        subjectName = 'None'
        
    try:
        sec = teachObj.section.section
    except:
        sec = 'None'
    
    try:
        time = str(teachObj.section.startTime)
    except:
        time = 'None'
        
    try:
        day = teachObj.section.date
        if day == 'M':
            day = u'จันทร์'
        elif day == 'T':
            day = u'อังคาร'
        elif day == 'W':
            day = u'พุธ'
        elif day == 'H':
            day = u'พฤหัสบดี'
        elif day == 'F':
            day = u'ศุกร์'
        elif day == 'S':
            day = u'เสาร์'
        else:
            day = u'อาทิตย์'
    except:
        day = 'None'
        
    pdf.add_font('THSarabun Bold', '', 'THSarabun Bold.ttf', uni=True)  # thai font bold
    pdf.set_font('THSarabun Bold', '', 29)
    pdf.cell(72, 10, u'')
    pdf.cell(0, 10, u' บันทึกข้อความ')
    pdf.ln(10)
    pdf.add_font('THSarabun Bold', '', 'THSarabun Bold.ttf', uni=True)  # thai font
    pdf.set_font('THSarabun Bold', '', 20)
    pdf.cell(19, 10, u'')
    pdf.cell(22, 10, u'ส่วนราชการ')
    pdf.add_font('THSarabun', '', 'THSarabun.ttf', uni=True)
    pdf.set_font('THSarabun', '', 16)
    pdf.cell(0, 11, u'  ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์ คณะวิศวกรรมศาสตร์  โทร. ๘๕๑๘')
    pdf.line(55,52.5,180,52.5)
    pdf.ln(8)
    pdf.add_font('THSarabun Bold', '', 'THSarabun Bold.ttf', uni=True)
    pdf.set_font('THSarabun Bold','', 20)
    pdf.cell(19, 10, u'')
    pdf.cell(5, 10, u'ที่')
    pdf.add_font('THSarabun', '', 'THSarabun.ttf', uni=True)
    pdf.set_font('THSarabun', '', 16)
    pdf.cell(70, 10, u'   วฟ')
    pdf.add_font('THSarabun Bold', '', 'THSarabun Bold.ttf', uni=True)
    pdf.set_font('THSarabun Bold','', 20)
    pdf.cell(0, 10, u'วันที่')
    pdf.line(34,60.5,180,60.5)
    pdf.ln(8)
    pdf.cell(19, 10, u'')
    pdf.cell(11, 10, u'เรื่อง')
    pdf.add_font('THSarabun', '', 'THSarabun.ttf', uni=True)
    pdf.set_font('THSarabun', '', 16)
    pdf.cell(0, 11, u'การจัดการเรียนการสอนสำหรับนักศึกษาโครงการพิเศษ(สองภาษา)')
    pdf.line(40,68.5,180,68.5)
    pdf.ln(8)
    pdf.add_font('THSarabun Bold', '', 'THSarabun Bold.ttf', uni=True)
    pdf.set_font('THSarabun Bold','', 20)
    pdf.cell(19, 10, u'')
    pdf.cell(10, 10, u'เรียน')
    pdf.add_font('THSarabun', '', 'THSarabun.ttf', uni=True)
    pdf.set_font('THSarabun', '', 16)
    pdf.cell(24, 11, u'หัวหน้าภาควิชา' + department)
    pdf.ln(8)
    pdf.cell(45, 10, u'')
    pdf.cell(0, 10, u'ตามที่ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  ได้ขอรับบริการจัดการเรียนการสอนจาก')
    pdf.ln(8)
    pdf.cell(19, 10, u'')
    pdf.cell(23, 10, u'ท่านในรายวิชา                                                              สำหรับนักศึกษาโครงการพิเศษ (สองภาษา) ')
    pdf.cell(20, 10, u'' + subjectName + '  '  + subjectID) 
    pdf.ln(8)
    pdf.cell(19, 10, u'')
    pdf.cell(0, 10, u'ภาคเรียนที่ .........  นั้น')
    pdf.ln(8)
    pdf.cell(45, 10, u'')
    pdf.cell(0, 10, u'ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  ขอให้ท่านยืนยันการจัดการเรียนการสอนในราย')
    pdf.ln(8)
    pdf.cell(19, 0, u'')
    pdf.cell(0, 10, u'วิชาดังกล่าว  ตามแบบฟอร์มด้านล่าง พร้อมตารางสอนและใบเบิกค่าสอนของอาจารย์ผู้สอน  และส่งคืนกลับ ')
    pdf.ln(8)
    pdf.cell(19, 0, u'')
    pdf.cell(0, 10, u'ภาควิชาวิศวกรรมไฟฟ้าและคอมพิวเตอร์  เพื่อจะได้ดำเนินการในส่วนที่เกี่ยวข้องต่อไป')
    pdf.ln(8)
    pdf.cell(45, 10, u'')
    pdf.cell(0, 10, u'จึงเรียนมาเพื่อโปรดทราบ')
    pdf.ln(20)
    pdf.cell(94, 10, u'')
    pdf.cell(100, 10, u'(ผู้ช่วยศาสตราจารย์ ดร.นภดล   วิวัชรโกเศศ)')
    pdf.ln(8)
    pdf.cell(94, 10, u'')
    pdf.cell(90, 10, u'หัวหน้าภาควิศวกรรมไฟฟ้าและคอมพิวเตอร์')
    pdf.ln(14)
    pdf.cell(21, 10, u'')
    pdf.cell(0, 10, u'.........................................................................................................................................................................')
    pdf.ln(8)
    pdf.cell(8, 10,u'')
    pdf.cell(30, 10, u'         ชื่อผู้สอน ' + academicPosition + pre_name + firstname + '   '+ lastname + u'            รหัสผู้สอน ' + proID )
    #pdf.cell(80, 10, u'' + academicPosition +pre_name+ firstname + '   '+ lastname)
    #pdf.cell(80, 10, u'' + proID)
    pdf.ln(8)
    pdf.cell(8, 10,u'')
    pdf.cell(30, 10, u'         ภาควิชา')
    pdf.cell(60, 10, u'' + department)
    pdf.cell(20, 10, u'คณะ')
    pdf.cell(20, 10, u'' + faculty)
    pdf.ln(8)
    pdf.cell(8, 10,u'')
    pdf.cell(30, 10, u'         รหัสวิชา')
    pdf.cell(60, 10, u'' +subjectID)
    pdf.cell(20, 10, u'ชื่อวิชา')
    pdf.cell(20, 10, u'' + subjectName) 
    pdf.ln(8)
    pdf.cell(8, 10,u'')
    pdf.cell(30, 10, u'         ตอนเรียน')
    pdf.cell(40, 10, u'' + sec)
    pdf.cell(10, 10, u'วัน')
    pdf.cell(40, 10, u'' + day)
    pdf.cell(15, 10, u'เวลา')
    pdf.cell(20, 10, u'' + str(time)[:5] + u' น.')
    pdf.ln(8)
    pdf.cell(8, 10,u'')
    pdf.cell(0, 10, u'         ได้ดำเนินการจัดการเรียนการสอนเป็น ')
    pdf.ln(8)
    pdf.cell(0, 10, u'                                      ภาษาอังกฤษ  ')
    
    pdf.rect(52, 219, 3, 3)
    pdf.ln(8)
    pdf.cell(0, 10, u'                                      ภาษาไทย')
    pdf.rect(52, 227, 3, 3)
    
    pdf.ln(8)
    pdf.cell(94, 10, u'')
    pdf.cell(100, 10, u'ลงชื่อ................................................อาจารย์ผู้สอน ')
    pdf.ln(8)
    pdf.cell(100, 10, u'')
    pdf.cell(110, 10, u''+u'( ' +short_academicPosition + pre_name + firstname +'   '+ lastname+u' )' )
    pdf.ln(8)
    pdf.cell(94, 10, u'')
    pdf.cell(100, 10, u'ลงชื่อ................................................')
    pdf.ln(8)
    pdf.cell(100, 10, u'')
    pdf.cell(110, 10, u'(..............................................) ')
    pdf.ln(8)
    pdf.cell(94, 10, u'')
    pdf.cell(100, 10, u'หัวหน้าภาควิชา' + department)
    pdf.ln(8)

    pdf.output("group3/uni.pdf", 'F')
    
    # next path will open pdf file in new tab on browser.
    with open('group3/uni.pdf', 'rb') as pdf: # path to pdf in directory views.
        response = HttpResponse(pdf.read(),content_type='application/pdf')
        response['Content-Disposition'] = 'filename=uni.pdf'
        return response
    pdf.closed
Example #39
0
def create_pdf(**kwargs):
    """Build the PDF file from user-supplied information"""

    # Dictionary of variables collected from gui, to be passed to method_graf()
    variabledic = {"methodofservice": kwargs['servicemethod'],
        "documents": kwargs['docserved'].upper(),
        "target": kwargs['personserved'],
        "dateandtime": kwargs['dateserved'] + ", at " + kwargs['timeserved'],
        "location": kwargs['servelocation'],
        "subperson": kwargs['subname'],
        "subrelation": kwargs['subrelation'],
        "parentname": kwargs['parentname'],
        "tempguard": kwargs['guardname'],
        "committed": kwargs['committed'],
        "adminname": kwargs['adminname'],
        "agentname": kwargs['agentname'],
        }

    pdf=FPDF("P", "pt", "Letter")
    pdf.set_margins(36,36)
    pdf.alias_nb_pages()
    pdf.add_page()

    # State, County & Court
    pdf.set_font("Times", "", 12)
    pdf.multi_cell(h = 18, w = 540, align = "L", txt = (
        "IN THE "+kwargs['court'].upper()+" COURT OF\n"+
        kwargs['county'].upper()+" COUNTY, "+kwargs['state'].upper()))
    pdf.ln(30)

    # Plaintiff
    pcursor = pdf.get_y()
    pdf.multi_cell(h=18, w=400, align = "L", txt=kwargs['plaintiff'].upper())
    newpcursor = pdf.get_y()
    pdf.set_xy(400, pcursor)
    pdf.cell(w = 0, align = "R", txt = "PLAINTIFF")
    pdf.set_xy(0, newpcursor)
    pdf.ln(18)

    # Case Number
    pdf.cell(h = 18, w = 20, align = "L", txt = "V.")
    pdf.cell(h = 18, w = 500, align = "C", txt = "CASE NO. "+kwargs['caseno'].upper())
    pdf.ln(30)

    # Defendant
    pcursor = pdf.get_y()
    pdf.multi_cell(h=18, w=400, align = "L", txt=kwargs['defendant'].upper())
    newpcursor = pdf.get_y()
    pdf.set_xy(400, pcursor)
    pdf.cell(h = 18, w = 0, align = "R", txt = "DEFENDANT")
    pdf.set_xy(0, newpcursor)
    pdf.ln(18)

    # Title
    pdf.set_font("Times", "U", 12)
    pdf.cell(h = 24, w = 0, align = "C", txt = "AFFIDAVIT OF SERVICE")
    pdf.ln(36)

    # Commencement
    pdf.set_font("Times", "", 12)
    pdf.multi_cell(h = 30, w = 540, align = "L", txt = (
        "          Comes now " + kwargs['servername'] + ", who, being duly "
        "sworn, deposes and says:"))

    # Paragraph with details of service (multi-line), called from method_graf() function
    pdf.multi_cell(h = 30, w = 540, align = "L", txt = method_graf(**variabledic))

    # Comments
    if len(kwargs['comments']) > 0:
        pdf.multi_cell(h = 30, w = 540, align = "L", txt = "     " + kwargs['comments'])

    # Not a party/No interest/Further affiant sayeth not, etc.
    pdf.multi_cell(h = 30, w = 540, align = "L", txt = (
        "          I am not a party to this action, and I have no interest in it. \n"
        "          Further affiant sayeth not."))
    pdf.ln(40)

    # Signature/Notary section
    pdf.line(270,pdf.get_y(),540,pdf.get_y())
    pdf.set_x(270)
    pdf.cell(h = 24, w = 0, align = "L", txt = kwargs['servername'])
    pdf.ln(24)
    pdf.set_x(270)
    pdf.multi_cell(h = 18, w = 0, align = "L", txt = kwargs['serveraddress'])
    pdf.ln(24)
    pdf.set_x(36)
    pdf.cell(h = 18, w = 270, align = "L", txt = "Subscribed and sworn to before me this date:")
    pdf.line(270,pdf.get_y()+18,540,pdf.get_y()+18)
    pdf.ln(40)
    pdf.line(270,pdf.get_y()+18,540,pdf.get_y()+18)
    pdf.ln(24)
    pdf.set_x(270)
    pdf.cell(h = 18, w = 270, align = "L", txt = "Notary Public")
    pdf.ln(36)
    pdf.set_x(270)
    pdf.cell(h = 18, w = 270, align = "L", txt = "My commission expires:")
    pdf.line(400,pdf.get_y()+18,540,pdf.get_y()+18)

    # write PDF
    pdf.output("app/static/pdfs/your.pdf", "F")
Example #40
0
    def ImrimirPDF(self, saleId):
	# Obtener los datos de la base de datos (datos de la venta y los elementos)
	datos = db.Salerecord(saleId)
	# guardar los datos de la venta en datos_sale
	datos_sale  = datos[0]
	#Guardar los datos de los elementos de la venta en datos_items 
	datos_items = datos[1]
	# Formatear el numero de la venta (ej: 0000000023)
	facturaNumero = str(("0"*(10-len(str(saleId))))+str(saleId))
	# Obtener los datos de la tienda/empresa desde la base de datos
	Datos = db.SelectConfigNS()
	import sys
	if hasattr(sys, 'frozen'):
		logo = os.path.join('resources', 'logo.png')
	else:
		logo = os.path.join(os.path.split(__file__)[0], 'resources', 'logo.png')
	if hasattr(sys, 'frozen'):
		fuente = os.path.join('resources', 'DejaVuSans.ttf')
	else:
		fuente = os.path.join(os.path.split(__file__)[0], 'resources', 'DejaVuSans.ttf')
	pdf = FPDF()
	pdf.add_page()
	pdf.add_font('DejaVu', '', fuente, uni=True)
	pdf.add_font('DejaVu', 'B', fuente, uni=True)
	pdf.add_font('arial', '', fuente, uni=True)
	pdf.set_font('DejaVu', '', 14)
	pdf.set_font('DejaVu', '', 13.0)
	pdf.set_xy(105.0, 16.0)
	pdf.cell(ln=0, h=22.0, align='L', w=75.0, txt='', border=0)
	pdf.set_line_width(0.0)
	pdf.rect(15.0, 15.0, 170.0, 245.0)
	pdf.set_line_width(0.0)
	pdf.rect(95.0, 15.0, 10.0, 10.0)
	pdf.image(logo, 20.0, 17.0, link='', type='', w=13.0, h=13.0)
	pdf.set_font('DejaVu', 'B', 16.0)
	pdf.set_xy(95.0, 18.0)
	#pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt='Hola 1', border=0)
	pdf.set_font('DejaVu', '', 8.0)
	pdf.set_xy(115.0, 40.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Tel:                "+str(Datos[3]), border=0)
	pdf.set_xy(115.0, 43.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="Web:               "+str(Datos[4]), border=0)
	pdf.set_xy(115.0, 46.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="E-mail:            "+Datos[7], border=0)
	pdf.set_xy(115.0, 49.0)
	pdf.cell(ln=0, h=4.0, align='L', w=75.0, txt="NIT:                 "+str(Datos[8]), border=0)
	pdf.set_font('DejaVu', 'B', 7.0)
	pdf.set_xy(95.0, 21.5)
	#pdf.cell(ln=0, h=4.5, align='C', w=10.0, txt='Hola 3', border=0)
	pdf.set_line_width(0.0)
	pdf.line(100.0, 25.0, 100.0, 57.0)
	pdf.set_font('arial', 'B', 14.0)
	pdf.set_xy(137.0, 25.5)
	pdf.cell(ln=0, h=9.5, align='L', w=60.0, txt=facturaNumero, border=0)
	pdf.set_xy(110.0, 20.5)
	pdf.cell(ln=0, h=5.5, align='L', w=10.0, txt='Factura N\xba: ', border=0)
	pdf.set_font('DejaVu', 'B', 12.0)
	pdf.set_xy(17.0, 32.5)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt=Datos[1], border=0)
	pdf.set_font('DejaVu', '', 12.0)
	pdf.set_xy(17.0, 36.5)
	pdf.set_font('DejaVu', '', 8.0)
	pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt=Datos[2], border=0)
	pdf.set_xy(17.0, 43.5)
	pdf.set_font('DejaVu', '', 8.0)
	pdf.multi_cell( h=4.0, align='L', w=80.0, txt=Datos[5], border=0, )
	
	
	pdf.set_xy(115.0, 35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=60.0, txt='Fecha:', border=0)
	pdf.set_xy(135.0, 35.0)
	pdf.cell(ln=0, h=7.0, align='L', w=40.0, txt=datos_sale[1], border=0)
	pdf.set_line_width(0.0)
	pdf.line(15.0, 57.0, 185.0, 57.0)
	pdf.set_font('times', '', 10.0)
	pdf.set_xy(17.0, 59.0)
	pdf.cell(ln=0, h=6.0, align='L', w=13.0, txt='Cliente:', border=0)
	pdf.set_xy(35.0, 59.0)
	pdf.cell(ln=0, h=6.0, align='L', w=140.0, txt=datos_sale[3].capitalize(), border=0)
	pdf.set_xy(17.0, 64.0)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Nit:', border=0)
	pdf.set_xy(35.0, 64.0)
	pdf.cell(ln=0, h=6.0, align='L', w=125.0, txt=datos_sale[5].upper(), border=0)
	pdf.set_xy(17.0, 69.0)
	pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='Total:', border=0)
	pdf.set_xy(35.0, 69.0)
	pdf.cell(ln=0, h=6.0, align='L', w=80.0, txt=formatCant(datos_sale[2]), border=0)
	pdf.set_xy(115.0, 69.0)
	#pdf.cell(ln=0, h=6.0, align='L', w=18.0, txt='City:', border=0)
	pdf.set_xy(133.0, 69.0)
	#pdf.cell(ln=0, h=6.0, align='L', w=42.0, txt='Springfield', border=0)
	pdf.set_line_width(0.0)
	pdf.line(15.0, 80.0, 185.0, 80.0)
	pdf.set_line_width(0.0)
	pdf.line(30.0, 80.0, 30.0, 230.0)
	pdf.line(130.0, 80.0, 130.0, 230.0)
	pdf.line(150.0, 80.0, 150.0, 230.0)
	pdf.line(165.0, 80.0, 165.0, 230.0)
	
	
	pdf.set_xy(20.0, 81.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='No.', border=0)
	pdf.set_xy(30.0, 81.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Producto', border=0)
	pdf.set_xy(135.0, 81.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Precio', border=0)
	pdf.set_xy(150.0, 81.0)
	pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt='Cantidad', border=0)
	pdf.set_xy(165.0, 81.0)
	pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt='Total', border=0)
	
	lineaN = 89.0
	contador = 0
	for elemento in datos_items:
		contador = contador+1
		pdf.set_xy(20.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=str(contador), border=0)
		pdf.set_xy(30.0, lineaN)
		if len(elemento[5]) > 62:
			pdf.multi_cell( h=5.0, align='L', w=100.0, txt=elemento[5], border=0)
		else:
			pdf.cell(ln=0, h=5.0, align='L', w=100.0, txt=elemento[5], border=0)
		pdf.set_xy(130.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=str(formatCant(elemento[3]/elemento[4])), border=0)
		pdf.set_xy(154.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=125.0, txt=str(elemento[4]), border=0)
		pdf.set_xy(165.0, lineaN)
		pdf.cell(ln=0, h=5.0, align='L', w=20.0, txt=str(formatCant(elemento[3])), border=0)
		if len(elemento[5]) > 62:
			lineaN = lineaN+10
		else:
			lineaN = lineaN+5
	
	
	
	
	pdf.set_line_width(0.0)
	pdf.line(15.0, 87.0, 185.0, 87.0)
	pdf.set_line_width(0.0)
	pdf.line(15.0, 230.0, 185.0, 230.0)
	pdf.set_xy(20.0, 233.0)
	#pdf.cell(ln=0, h=5.0, align='L', w=95.0, txt='CAE N\xba', border=0)
	pdf.set_xy(45.0, 233.0)
	#pdf.cell(ln=0, h=5.0, align='L', w=30.0, txt='01234567890', border=0)
	pdf.set_font('DejaVu', '', 12.0)
	pdf.set_xy(105.0, 234.0)
	pdf.cell(ln=0, h=9.0, align='R', w=45.0, txt='Subtotal:', border=0)
	pdf.set_font('DejaVu', 'B', 12.0)
	pdf.set_xy(145.0, 234.0)
	pdf.cell(ln=0, h=9.0, align='R', w=33.0, txt=str(formatCant((datos_sale[2]-datos_sale[6]))), border=0)
	pdf.set_font('DejaVu', '', 10.0)
	pdf.set_xy(20.0, 238.0)
	#pdf.cell(ln=0, h=5.0, align='L', w=95.0, txt='Fecha Vto. CAE:', border=0)
	pdf.set_xy(55.0, 238.0)
	#pdf.cell(ln=0, h=5.0, align='L', w=30.0, txt='19/02/2009', border=0)
	pdf.set_font('DejaVu', '', 12.0)
	pdf.set_xy(125.0, 241.0)
	pdf.cell(ln=0, h=9.0, align='R', w=25.0, txt='IVA:', border=0)
	pdf.set_font('DejaVu', 'B', 12.0)
	pdf.set_xy(145.0, 241.0)
	pdf.cell(ln=0, h=9.0, align='R', w=33.0, txt=str(formatCant(datos_sale[6])), border=0)
	#pdf.interleaved2of5('012345678905', 20.0, 243.5, w=0.75)
	pdf.set_font('DejaVu', 'B', 12.0)
	pdf.set_xy(105.0, 251.0)
	pdf.cell(ln=0, h=9.0, align='R', w=73.0, txt=str(formatCant(datos_sale[2])), border=0)
	pdf.set_font('DejaVu', '', 12.0)
	pdf.set_xy(125.0, 251.0)
	pdf.cell(ln=0, h=9.0, align='R', w=25.0, txt='Total:', border=0)
	pdf.set_line_width(0.0)
	pdf.rect(155.0, 252.0, 25.0, 7.0)
	pdf.set_font('DejaVu', '', 10.0)
	pdf.set_xy(20.0, 253.0)
	#pdf.cell(ln=0, h=7.0, align='L', w=120.0, txt='012345678905', border=0)
	pdf.output('./invoice.pdf', 'F')
	if sys.platform.startswith("linux"):
		os.system("evince ./invoice.pdf")
	else:
		os.system("./invoice.pdf")
	def formatCant( cant):
		import config
		config = config.Configuration()
		c_symbol = config.cCurrency()[0]
		c_dec = config.cCurrency()[1]
		thous_sep = config.ThousandsSep()
		try:
			ins = '%s %.'+str(c_dec)+'f'
			cant = ins % (c_symbol, cant)
		except:
			cant = str(c_dec),cant
		return str(cant)
Example #41
0
def createCertificate(
	workshop_name,
	workshop_day,
	workshop_month,
	workshop_year,
	workshop_speaker,
	student_name,
	student_mail,
	chair_IEEE
	):
	
	l_name = unicode( student_name, "utf-8" )
	w_name = unicode( workshop_name, "utf-8" )
	c_name = unicode( chair_IEEE, "utf-8" )
	s_name = unicode( workshop_speaker, "utf-8" )

	# PDF File Properties
	pdf=FPDF('L','mm','A4')
	pdf.set_margins(left=0,top=0,right=0)
	pdf.set_auto_page_break(False,margin=0)
	pdf.add_page()
	# ISEPinIEEE Logo
	pdf.set_font('Arial','',30)
	pdf.cell(297,40,'',0,1,'C')#fill=True
	pdf.image('logos/isepinieee_logo.jpg',190,5, 0,35,'','')
	# Workshop Title
	pdf.set_text_color(0,102,153)
	pdf.cell(293,20,w_name,0,1,'R')
	# Cetificate Bar
	pdf.set_fill_color(0,102,153)
	pdf.set_text_color(255,255,255)
	pdf.set_font('Arial','',48)
	pdf.cell(297,35,'Certificate',0,1,'C',fill=True)
	pdf.cell(297,10,'',0,1,'C')
	# Certificate Text
	pdf.set_font('Arial','',20)
	pdf.set_text_color(0,0,0)
	# This pdf element is used to center ( Note: (297-240)/2 = 28.5)
	pdf.cell(19,20,'',0,0,'C')
	pdf.multi_cell(259,12.5, 'We certifiy that '+l_name+' participated in the talk \"'+w_name+'\", organized by the ISEPinIEEE.',0,1,'C')
	#MultiCell( 200, 40, $reportSubtitle, 1);
	# Certificate Date
	pdf.cell(297,10,'',0,1,'C')
	pdf.cell(19,15,'',0,0,'C')
	pdf.cell(240,10,'Porto, '+workshop_month+' '+str(workshop_day)+', '+str(workshop_year),0,1,'L')

	#Speaker & Chair Signature
	pdf.image(workshop_name+'/signatures/speaker.jpg',167.5,170, 0, 17,'','')
	pdf.image(workshop_name+'/signatures/chair.jpg',240.5,170, 0, 17,'','')

	#Speaker & Chair
	pdf.set_font('Arial','',18)
	pdf.cell(150,20,'',0,0,'C')
	pdf.cell(73.5,20,'Speaker',0,0,'C')
	pdf.cell(73.5,20,'Chair',0,1,'C')
	pdf.cell(150,35,'',0,0,'C')
	pdf.cell(73.5,35,s_name,0,0,'C')
	pdf.cell(73.5,35,c_name,0,1,'C')

	#SpeakerLine & ChairLine
	pdf.line(155, 180, 218, 180)
	pdf.line(228, 180, 292, 180)
	# IEEE and ISEP logos
	pdf.image('logos/ieee_logo.jpg',20,175, 0, 17,'','')
	pdf.image('logos/isep_logo.jpg',85,175, 0, 17,'','')
	# Save PDF File
	certificate_name = hashlib.md5(student_mail)
	pdf.output(workshop_name+'/'+certificate_name.hexdigest()+'.pdf','F')
Example #42
0
def invoice_to_PDF(order, client, filename=None):
    """
    creates and pdf invoice of the order, and returns the pfd as a string buffer.
    @order: the order used to create a invoice
    @client: if specified this data is used for the client address, otherwise the address is taken from the order
    @filename: if specified the pdf is written to disk with the given filename,
               filename can contains a complete path
    """
    pdf = FPDF()
    pdf.add_font('DejaVu', '', fname='{0}/fonts/ttf-dejavu/DejaVuSerif.ttf'.format(settings.STATIC_ROOT), uni=True)
    pdf.add_font('DejaVu', 'B', fname='{0}/fonts/ttf-dejavu/DejaVuSerif-Bold.ttf'.format(settings.STATIC_ROOT), uni=True)
    pdf.add_font('DejaVu', 'I', fname='{0}/fonts/ttf-dejavu/DejaVuSerif-Italic.ttf'.format(settings.STATIC_ROOT), uni=True)
    pdf.add_font('DejaVu', 'BI', fname='{0}/fonts/ttf-dejavu/DejaVuSerif-BoldItalic.ttf'.format(settings.STATIC_ROOT), uni=True)

    def check_for_new_page():
        if pdf.get_y() > PAGE_BOTTOM_Y:
            pdf.add_page()

    def text_fonts():
        pdf.set_font('DejaVu', '', 11.0)

    def add_row(column_data, columns=COLUMNS, border=0):
        """
        add a row to the pdf
        """
        cell_margin_left = 2
        cell_margin_right = 2

        check_for_new_page()
        last_y = START_TABLE_Y if pdf.page_no() == 1 else TOP_PAGE_MARGIN
        row_y = pdf.get_y() if pdf.get_y() > last_y else last_y
        max_y = row_y  # max_y is used to check if multi cell is wrapping text and so uses more rows.

        next_x = LEFT_PAGE_MARGIN
        for i, column in enumerate(columns):
            width = column[0]
            align = column[1]
            pdf.set_xy(next_x+cell_margin_left, row_y)
            pdf.multi_cell(w=width-cell_margin_right,
                           h=TABLE_ROW_HIGH,
                           txt=column_data[i] if len(column_data) > i else '', align=align, border=border)
            max_y = max(max_y, pdf.get_y())  # keep track if multi cell wrapped text
            next_x += width

        pdf.set_y(max_y)

    def add_row_line():
        last_y = START_TABLE_Y if pdf.page_no() == 1 else TOP_PAGE_MARGIN
        line_y = pdf.get_y() if pdf.get_y() > last_y else last_y - 2
        pdf.set_xy(LEFT_PAGE_MARGIN + 1, line_y)
        pdf.line(LEFT_PAGE_MARGIN, line_y+2, RIGHT_PAGE_MARGIN, line_y+2)
        pdf.set_y(line_y+5)

    def draw_vertical_lines_around_columns(columns = COLUMNS, top_y=TOP_PAGE_MARGIN, bottom_y=PAGE_BOTTOM_Y):
        ####
        # draw table vertical lines
        ####
        line_y = pdf.get_y() - 3
        line_x = LEFT_PAGE_MARGIN
        first = True
        for column in columns:
            if first:
                pdf.line(line_x, START_TABLE_Y, line_x, line_y)  # vertical line in front of table
                first = False

            line_x += column[0]
            pdf.line(line_x, START_TABLE_Y, line_x, line_y)  # vertical line after column

    pdf.add_page()
    text_fonts()

    ####
    # Header: logo and company info
    ####
    pdf.image('{0}/gfx/logos/logo_jeslee.jpg'.format(settings.STATIC_ROOT), 20.0, TOP_PAGE_MARGIN, link='', type='', w=79.5, h=33.0)
    pdf.set_xy(125.0, TOP_PAGE_MARGIN)
    # pdf.set_font('arial', 'B', 13.0)
    pdf.set_left_margin(125.0)
    pdf.write(6, '{company}\n{street}\n{zip} {city}\n{email}\n\nBank: {bank_account}\nKvk: {kvk}\nBTW: {btw}'.format(
        company=settings.COMPANY['business_name'],
        street=settings.COMPANY['street'], zip=settings.COMPANY['zip'], city=settings.COMPANY['city'],
        email=settings.COMPANY['email'], bank_account=settings.COMPANY['bank_account'], kvk=settings.COMPANY['kvk_nr'], btw=settings.COMPANY['btw_nr']
    ))

    ####
    # Invoice data
    ####
    pdf.set_xy(LEFT_PAGE_MARGIN, 75)
    pdf.set_left_margin(LEFT_PAGE_MARGIN)
    pdf.set_font('DejaVu', 'B', 14.0)
    pdf.write(6, 'Factuur {number}'.format(number=order.number))
    text_fonts()
    pdf.set_xy(125, 75)
    pdf.write(6, 'Factuurdatum: {date}'.format(date=datetime.now().strftime("%d %B %Y")))
    pdf.set_xy(LEFT_PAGE_MARGIN, 85)
    pdf.write(5, 'Referentie: {reference}'.format(reference=order.invoice_line2 if order.invoice_line2 else 'Uw bestelling bij Jeslee'))
    pdf.set_xy(LEFT_PAGE_MARGIN, 100)
    name = order.invoice_company_name \
        if order.invoice_company_name \
        else "{0} {1}".format(order.invoice_firstname, order.invoice_lastname)
    address = order.invoice_line1
    pdf.write(6, '{name}\n{address}\n{zip} {city}'.format(
        name=name.strip(), address=address.strip(),
        zip=order.invoice_code, city=order.invoice_city
    ))


    ####
    # Article data
    ####
    pdf.set_font('DejaVu', '', 9.0)
    add_row_line()
    add_row(['Artikelcode', 'Omschrijving', '', 'Bedrag\nincl. btw', 'Totaal'])
    add_row_line()
    for item in order.items.all():
        code = ''
        description = ''
        if item.product:
            code = item.product.sku
            description = item.product.description if item.product.description else item.product.name
            str(item.product.tax if item.product.tax else '')
        add_row([code,
                 description,
                 '%.0f x' % item.product_amount,
                 to_currency(item.product_price_gross),
                 to_currency(item.price_gross)])

    add_row_line()

    columns_below_items = [(COLUMN_1_WIDTH + COLUMN_2_WIDTH + COLUMN_3_WIDTH+COLUMN_4_WIDTH , 'R'),
                           (COLUMN_5_WIDTH, 'R')]
    add_row(['Subtotaal', to_currency(order.price-order.tax)], columns=columns_below_items)
    taxes = tax_per_percentage(order)

    for tax_percentage, tax in taxes.iteritems():
        add_row(['Btw {0}%'.format(tax_percentage), to_currency(tax)], columns=columns_below_items)
    add_row_line()
    pdf.set_font('DejaVu', 'B', 10.0)
    add_row(['Totaal', to_currency(order.price)], columns=columns_below_items)
    table_bottom = pdf.get_y() + 2
    pdf.line(LEFT_PAGE_MARGIN, table_bottom, RIGHT_PAGE_MARGIN, table_bottom)  # bottom horizontal line of table

    pdf.set_font('DejaVu', '', 10.0)
    pdf.set_y(pdf.get_y() + 10)
    check_for_new_page()
    pdf.set_x(LEFT_PAGE_MARGIN)
    pdf.multi_cell(w=COLUMN_1_WIDTH + COLUMN_2_WIDTH + COLUMN_3_WIDTH+COLUMN_4_WIDTH+COLUMN_5_WIDTH,
                   h=TABLE_ROW_HIGH,
                   txt=order.message, align='L', border=0)




    pdf.set_font('DejaVu', '', 10.0)
    pdf.set_xy(LEFT_PAGE_MARGIN, PAGE_BOTTOM_Y-14)
    pay_date = datetime.now() + timedelta(PAY_INVOICE_WITHIN_DAYS)
    pdf.write(4, 'We verzoeken u vriendelijk het bovenstaande bedrag van {order_price} voor '
                 '{pay_date} te voldoen op onze bankrekening onder vermelding van het '
                 'factuurnummer {invoice_number}.\nVoor vragen kunt u contact opnemen per e­mail ({email}).'.
              format(order_price=to_currency(order.price),
                     pay_date=pay_date.strftime("%d %B %Y"),
                     invoice_number=order.number,
                     email=settings.COMPANY['email']))

    pdf.set_draw_color(80)
    pdf.set_text_color(80)
    pdf.line(LEFT_PAGE_MARGIN, PAGE_BOTTOM_Y, RIGHT_PAGE_MARGIN, PAGE_BOTTOM_Y)  # bottom horizontal line
    pdf.set_xy(LEFT_PAGE_MARGIN+5, PAGE_BOTTOM_Y+2)
    if filename:
        pdf.output(filename, 'F')
    return pdf.output('invoice.pdf', 'S')
Example #43
0
pdf.set_line_width(0.0)
pdf.rect(15.0, 15.0, 170.0, 245.0)
pdf.set_line_width(0.0)
pdf.rect(95.0, 15.0, 10.0, 10.0)
pdf.image('../tutorial/logo.png', 20.0, 17.0, link='', type='', w=13.0, h=13.0)
pdf.set_font('arial', 'B', 16.0)
pdf.set_xy(95.0, 18.0)
pdf.cell(ln=0, h=2.0, align='C', w=10.0, txt='X', border=0)
pdf.set_font('arial', '', 8.0)
pdf.set_xy(105.0, 21.0)
pdf.cell(ln=0, h=4.0, align='C', w=75.0, txt='Original', border=0)
pdf.set_font('arial', 'B', 7.0)
pdf.set_xy(95.0, 21.5)
pdf.cell(ln=0, h=4.5, align='C', w=10.0, txt='COD.00', border=0)
pdf.set_line_width(0.0)
pdf.line(100.0, 25.0, 100.0, 57.0)
pdf.set_font('arial', 'B', 14.0)
pdf.set_xy(125.0, 25.5)
pdf.cell(ln=0, h=9.5, align='L', w=60.0, txt='00000001', border=0)
pdf.set_xy(115.0, 27.5)
pdf.cell(ln=0, h=5.5, align='L', w=10.0, txt='N\xba: ', border=0)
pdf.set_font('arial', 'B', 12.0)
pdf.set_xy(17.0, 32.5)
pdf.cell(ln=0, h=5.0, align='L', w=98.0, txt='COMPANY', border=0)
pdf.set_font('arial', '', 12.0)
pdf.set_xy(115.0, 33.0)
pdf.cell(ln=0, h=7.0, align='L', w=60.0, txt='Date:', border=0)
pdf.set_xy(135.0, 33.0)
pdf.cell(ln=0, h=7.0, align='L', w=40.0, txt='19/02/2009', border=0)
pdf.set_line_width(0.0)
pdf.line(15.0, 57.0, 185.0, 57.0)
Example #44
0
def addpdf2(request, profID): # use to generate pdf file for lend another teacher.
    #template = 'grop4/pdf.html'
    #teachObj = Teach.objects.get(pk= int(profID))   # get all objects teacher.

    Obj = WithdrawCure.objects.get(pk= int(profID))
    print Obj.user
    print WithdrawStudy.user
    #familyObj = Family.objects.get(user=Obj.user)
    lists = Obj.user.family_set.all()
    dad = Obj.user.Father_set.all()
    mom = Obj.user.Monther_set.all()
    ch = Obj.user.Child_set.all()
    presi = EditPresident.objects.all()
    sp = Obj.user.Spouse_set.all()

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


    try:
        firstname = Obj.user.firstname_th
    except:
        firstname = 'None'

    try:
        lastname = Obj.user.lastname_th
    except:
        lastname = 'None'

    try:
        department = Obj.user.department
    except:
        department = 'None'

    try:
        faculty = Obj.user.faculty
    except:
        faculty = 'None'

    try:
        typeuser = Obj.user.type
    except:
        typeuser = '******'

    try:
        user = Obj.user
    except:
        user = '******'

    try:
        account_id = Obj.account_id
    except:
        account_id = 'None'

    try:
        disease = Obj.disease
    except:
        disease = 'None'

    try:
        hospital = Obj.hospital
    except:
        hospital = 'None'

    try:
        hospitalOf = Obj.hospitalOf
    except:
        hospitalOf = 'None'

    try:
        startDate = Obj.startDate
    except:
        startDate = 'None'

    try:
        stopDate = Obj.stopDate
    except:
        stopDate = 'None'

    try:
        value = Obj.value
    except:
        value = 'None'

    try:
        valueChar = Obj.valueChar
    except:
        valueChar = 'None'

    try:
        numBill = Obj.numBill
    except:
        numBill = 'None'

    try:
        typeWithdraw = Obj.typeWithdraw
    except:
        typeWithdraw = 'None'


    pdf.line(12, 38, 198, 38)
    pdf.line(12, 38, 12, 280)
    pdf.line(12, 280, 198, 280)
    pdf.line(198, 38, 198, 280)

    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',80,27,6)

    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',29,50,6) #ข้าราชการ
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',49,50,6) #ลูกจ้างประจำ
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',73,50,6) #ข้าราชการบำนาช
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',145,50,6) #พนักงานมหาวิทยาลัย

    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,71,6) #ไม่เป็นข้าราชการหรือลูกจ้างประจำ
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,78,6) #เป็นข้าราชการ
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',45,78,6) #ลูกจ้างประจำ
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',70,78,6) #พนักงานมหาวิทยาลัย
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,85,6) #เป็นพนักงานหรือลูกจ้าง

    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,106,6) #เป็นบิดาชอบด้วยกฏหมาย
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,113,6) #เป็นมารดา
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,120,6) #บุตรอยู่ในความปกครองของข้าพเจ้า
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,127,6) #บุตรอยู่ในความอุปการะการเลี้ยงดูของข้าพเจ้า




    pdf.add_font('THSarabunNew Bold', '', 'THSarabunNew Bold.ttf', uni=True)
    pdf.set_font('THSarabunNew Bold', '', 14)
    pdf.cell(169, 10, u'')
    pdf.cell(0, 10, u'แบบ 7223')
    pdf.ln(8)
    pdf.set_font('THSarabunNew Bold', '', 18)
    pdf.cell(0, 10, u'                                    ใบเบิกเงินสวัสดิการการเกี่ยวกับการศึกษาของบุตร     ')
    pdf.ln(7)
    pdf.set_font('THSarabunNew Bold', '', 14)
    pdf.cell(0, 10, u'                                     โปรดทำเครื่องหมาย      ลงในช่องว่าง  พร้อมทั้งกรอกข้อความให้ครบถ้วน    ')
    pdf.ln(16)
    pdf.add_font('THSarabunNew', '', 'THSarabunNew.ttf', uni=True)
    pdf.set_font('THSarabunNew', '', 14)
    pdf.cell(30, 10, u'     1. ข้าพเจ้า................................................................................................เลขที่บัญชีสหกรณ์ออมทรัพย์ SA-.....................................................')
    pdf.cell(115, 8, u'' + firstname + u'  ' + lastname)
    pdf.cell(20, 8, u'' + account_id)
    pdf.ln(7)
    pdf.cell(0, 10, u'        สถานะ  ข้าราชการ   ลูกจ้างประจำ   ข้าราชการบำนาญ(เปลี่ยนสถานะ และ เกษียณอายุ)   พนักงานมหาวิทยาลัย ')
    if typeuser == '0':
        pdf.image('group4\son2.png',29,50,6)
    elif typeuser == '1':
        pdf.image('group4\son2.png',49,50,6)
    elif typeuser == '2':
        pdf.image('group4\son2.png',73,50,6)
    elif typeuser == '3':
        pdf.image('group4\son2.png',145,50,6)
    pdf.ln(7)
    pdf.cell(40, 10, u'        สังกัด ภาควิชา.................................................................................................คณะ......................................................................................')
    if department == '1':
        pdf.cell(85, 8, u'วิศวกรรมไฟฟ้าและคอมพิวเตอร์')
    if faculty == '1':
        pdf.cell(0, 8, u'วิศวกรรมศาสตร์')
    pdf.ln(7)
    pdf.cell(50, 10, u'     2. คู่สมรสของข้าพเจ้าชื่อ .................................................................................................................................................................................')
    pdf.cell(0, 8, u'' + sp.title + sp.firstname + u'  ' + sp.lastname)
    pdf.ln(7)
    pdf.cell(0, 10, u'        □  ไม่เป็นข้าราชการหรือลูกจ้างประจำ')
    if sp.typeOfWork == '0':
        pdf.image('group4\son2.png',19,71,6)
    pdf.ln(7)
    pdf.cell(109, 10, u'        □  เป็นข้าราชการ  □  ลูกจ้างประจำ  □  พนักงานมหาวิทยาลัย ตำแหน่ง...........................................สังกัด.........................................')
    if sp.typeOfWork == '1':
        pdf.image('group4\son2.png',19,78,6)
        pdf.cell(41, 8, u'' + sp.office)
        pdf.cell(0, 8, u'' + sp.position)
    elif sp.typeOfWork == '2':
        pdf.image('group4\son2.png',45,71,6)
        pdf.cell(41, 8, u'' + sp.office)
        pdf.cell(0, 8, u'' + sp.position)
    elif sp.typeOfWork == '3':
        pdf.image('group4\son2.png',70,71,6)
        pdf.cell(41, 8, u'' + sp.office)
        pdf.cell(0, 8, u'' + sp.position)
    pdf.ln(7)
    pdf.cell(0, 10, u'        □  เป็นพนักงานหรือลูกจ้างในรัฐวิสาหกิจ/หน่วยงานของทางราชการ ราชการส่วนท้องถิ่น กรุงเทพมหานคร องค์กรอิสระ')
    if sp.typeOfWork == '4':
        pdf.image('group4\son2.png',19,85,6)
    pdf.ln(7)
    pdf.cell(80, 10, u'             องค์กรมหาชน หรือ หน่วยงานอื่นใด ตำแหน่ง.........................................................................สังกัด.....................................................')
    if sp.typeOfWork == '4':
        pdf.cell(62, 8, u'' + sp.office)
        pdf.cell(0, 8, u'' + sp.position)
    pdf.ln(7)
    pdf.cell(0, 10, u'     3. ข้าพเจ้าเป็นผู้มีสิทธิและขอใช้สิทธิเนื่องจาก ')
    pdf.ln(7)
    pdf.cell(0, 10, u'        □ เป็นบิดาชอบด้วยกฏหมาย')
    if ch.parentRelate == '0':
        pdf.image('group4\son2.png',19,106,6)
    pdf.ln(7)
    pdf.cell(0, 10, u'        □ เป็นมารดา')
    if ch.parentRelate == '1':
        pdf.image('group4\son2.png',19,113,6)
    pdf.ln(7)
    pdf.cell(0, 10, u'        □ บุตรอยู่ในความปกครองของข้าพเจ้า โดยการสิ้นสุดของการสมรส ')
    if ch.parentRelate == '2':
        pdf.image('group4\son2.png',19,120,6)
    pdf.ln(7)
    pdf.cell(0, 10, u'        □ บุตรอยู่ในความอุปการะการเลี้ยงดูของข้าพเจ้าเนื่องจากแยกกันอยู่ โดยมิได้หย่าขาดตามกฏหมาย')
    if ch.parentRelate == '3':
        pdf.image('group4\son2.png',19,127,6)
    pdf.ln(7)
    pdf.cell(0, 10, u'     4. ข้าพเจ้าได้จ่ายเงินสำหรับการศึกษาของบุตร ดังนี้')
    pdf.ln(7)
    pdf.cell(0, 10, u'        (1) เงินบำรุงการศึกษา                                    (2) เงินค่าเล่าเรียน ')
    pdf.ln(7)
    pdf.cell(33, 10, u'            1)  บุตรชื่อ........................................................................................เกิดเมื่อ...........................................................................................')
    pdf.cell(90, 8, u'' + ch.title + ch.firstname + u'  ' + ch.lastname)
    pdf.cell(0, 8, u'' + ch.birthDate)
    pdf.ln(7)
    pdf.cell(70, 10, u'                เป็นบุตรลำดับที่(ของบิดา)...........................................................เป็นบุตรลำดับที่(ของมารดา)..........................................................')
    pdf.cell(80, 8, u'' + ch.orderF)
    pdf.cell(0, 8, u'' + ch.orderM)
    pdf.ln(7)
    pdf.cell(120, 10, u'                (กรณีเป็นบุตรแทนที่บุตรซึ่งถึงแก่กรรมแล้ว) แทนที่บุตรลำดับที่........................................................................................................')
    pdf.cell(0, 8, u'')
    pdf.ln(7)
    pdf.cell(27, 10, u'                ชื่อ...........................................................................เกิดเมื่อ................................................ถึงแก่กรรมเมื่อ........................................')
    pdf.cell(70, 8, u'นายกิตติพงศ์ จันทร์นัณทยงว์ป่า')
    pdf.cell(58, 8, u'11/11/1111')
    pdf.cell(0, 8, u'11/11/1111')
    pdf.ln(7)
    pdf.cell(35, 10, u'                สถานศึกษา.................................................................................อำเภอ........................................จังหวัด..........................................')
    pdf.cell(75, 8, u'มหาวิทยาลัยหหหหหหหหหหหหหหหหหหห')
    pdf.cell(40, 8, u'เมือง')
    pdf.cell(0, 8, u'ราชบุรี')
    pdf.ln(7)
    pdf.cell(35, 10, u'                ชั้นที่ศึกษา..........................................................................................................จำนวน..............................................................บาท')
    pdf.cell(100, 8, u'ประถมศึกษาปีที่4')
    pdf.cell(0, 8, u'2,000')
    pdf.ln(7)
    pdf.cell(0, 10, u'            2)  บุตรชื่อ........................................................................................เกิดเมื่อ...........................................................................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                เป็นบุตรลำดับที่(ของบิดา)...........................................................เป็นบุตรลำดับที่(ของมารดา)..........................................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                (กรณีเป็นบุตรแทนที่บุตรซึ่งถึงแก่กรรมแล้ว) แทนที่บุตรลำดับที่........................................................................................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                ชื่อ...........................................................................เกิดเมื่อ................................................ถึงแก่กรรมเมื่อ........................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                สถานศึกษา.................................................................................อำเภอ........................................จังหวัด..........................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                ชั้นที่ศึกษา..........................................................................................................จำนวน..............................................................บาท')
    pdf.ln(7)
    pdf.cell(0, 10, u'            3)  บุตรชื่อ........................................................................................เกิดเมื่อ...........................................................................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                เป็นบุตรลำดับที่(ของบิดา)...........................................................เป็นบุตรลำดับที่(ของมารดา)..........................................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                (กรณีเป็นบุตรแทนที่บุตรซึ่งถึงแก่กรรมแล้ว) แทนที่บุตรลำดับที่........................................................................................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                ชื่อ...........................................................................เกิดเมื่อ................................................ถึงแก่กรรมเมื่อ........................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                สถานศึกษา.................................................................................อำเภอ........................................จังหวัด..........................................')
    pdf.ln(7)
    pdf.cell(0, 10, u'                ชั้นที่ศึกษา..........................................................................................................จำนวน..............................................................บาท')



    pdf.add_page()

    #frame
    pdf.line(12, 15, 198, 15)
    pdf.line(12, 15, 12, 253)
    pdf.line(12, 253, 198, 253)
    pdf.line(198, 15, 198, 253)
    pdf.line(12, 124, 198, 124)
    pdf.line(12, 175, 198, 175)

    #table
    pdf.line(20, 205, 83, 205)
    pdf.line(20, 205, 20, 250)
    pdf.line(20, 250, 83, 250)
    pdf.line(83, 205, 83, 250)

    pdf.line(20, 213, 83, 213)
    pdf.line(20, 220, 83, 220)
    pdf.line(20, 228, 83, 228)
    pdf.line(20, 235, 83, 235)
    pdf.line(48, 205, 48, 235)

    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,26,6) #ตามสิทธิ
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',59,26,6) #เฉพาะส่วน
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,47,6) #ข้าพเจ้ามีสิทธิได้รับเงินช่วยเหลือ
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,61,6) #บุตรของข้าพเจ้าอยู่ในข่าย
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,68,6) #เป็นผู้ใช้สิทธิเบิกเงินช่วยเหลือ
    pdf.image('C:\Users\Artty\PycharmProjects\untitled\son2.png',19,75,6) #คู่สมรสของข้าพเจ้าได้รับการช่วยเหลือ

    pdf.add_font('THSarabunNew', '', 'THSarabunNew.ttf', uni=True)
    pdf.set_font('THSarabunNew', '', 14)
    pdf.ln(7)
    pdf.cell(0, 10, u'     5. ข้าพเจ้าขอรับเงินสวัสดิการเกี่ยวกับการศึกษาของบุตร')
    pdf.ln(7)
    pdf.cell(120, 10, u'        □  ตามสิทธิ                      □  เฉพาะส่วนที่ยังขาดจากสิทธิ เป็นจำนวนเงิน ............................................................. บาท')
    pdf.cell(0, 8, u'20000')
    pdf.ln(7)
    pdf.cell(20, 10, u'        (...............................................................................................................................................)')
    pdf.cell(0, 8, u'เก้าพันเก้าร้อยเก้าสิบเก้าบาทถ้วน')
    pdf.ln(7)
    pdf.cell(0, 10, u'     6. เสนอ........................................... ')
    pdf.ln(7)
    pdf.cell(0, 10, u'        □  ข้าพเจ้ามีสิทธิได้รับเงินช่วยเหลือตามพระราชกฤษฎีกาเงินสวัสดิการเกี่ยวกับการศึกษาของบุตร')
    pdf.ln(7)
    pdf.cell(0, 10, u'             และข้อความระบุข้างต้นเป็นความจริง ')
    pdf.ln(7)
    pdf.cell(0, 10, u'        □  บุตรของข้าพเจ้าอยู่ในข่ายได้บการช่วยเหลือตามพระราชกฤษฎีกาเงินสวัสดิการเกี่ยวกับการศึกษาของบุตร')
    pdf.ln(7)
    pdf.cell(0, 10, u'        □  เป็นผู้ใช้สิทธิเบิกเงินช่วยเหลือตามพระราชกฤษฎีกาเงินสวัสดิการเกี่ยวกับการศึกษาของบุตรแต่เพียงฝ่ายเดียว')
    pdf.ln(7)
    pdf.cell(0, 10, u'        □  คู่สมรสของข้าพเจ้าได้รับการช่วยเหลือจากรัฐวิสาหกิจ หน่วยงานของทางราชการ ราชการส่วนท้องถิ่นกรุงเทพมหานคร')
    pdf.ln(7)
    pdf.cell(0, 10, u'             องค์กรอิสระ องค์การมหาชน หรือหน่วยงานอื่นใด ต่ำกว่าจำนวนเงินที่ได้รับจากทางราชการเป็นจำนวนเงิน.....................บาท')
    pdf.ln(7)
    pdf.cell(0, 10, u'        ข้าพเจ้าขอรับรองว่ามีสิทธิเบิกได้ตามกฏหมายตามจำนวนเงินที่ขอเบิก')
    pdf.ln(12)
    pdf.cell(0, 10, u'                                                                                            (ลงชื่อ)........................................................ผู้ขอรับเงินสวัสดิการ')
    pdf.ln(7)
    pdf.cell(110, 10, u'                                                                                                   (..........................................................)')
    pdf.cell(0, 8, u'' + firstname + u'   ' + lastname)
    pdf.ln(7)
    pdf.cell(0, 10, u'                                                                                               วันที่............เดือน..........................พ.ศ...............')
    pdf.ln(12)
    pdf.cell(0, 10, u'    7. คำอนุมัติ ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                  อนุมัติให้เบิกได้')
    pdf.ln(10)
    pdf.cell(0, 10, u'                                                                                             (ลงชื่อ)......................................................... ')
    pdf.ln(7)
    pdf.cell(110, 10, u'                                                                                                    (..........................................................)')
    pdf.cell(0, 8, u'' + presi.presidentName)
    pdf.ln(7)
    pdf.cell(115, 10, u'                                                                                             ตำแหน่ง..........................................................')
    pdf.cell(0, 8, u'' + presi.position)
    pdf.ln(7)
    pdf.cell(0, 10, u'                                                                                             วันที่............เดือน..........................พ.ศ............... ')
    pdf.ln(12)
    pdf.cell(0, 10, u'    8. ใบรับเงิน')
    pdf.ln(7)
    pdf.cell(95, 10, u'                 ได้รับเงินสวัสดิการเกี่ยวกับการรักษาพยาบาล จำนวน...........................................................................บาท ')
    pdf.cell(0, 8, u'66,000')
    pdf.ln(7)
    pdf.cell(35, 10, u'          (..............................................................................................................................................................................)ไปถูกต้องแล้ว ')
    pdf.cell(0, 8, u'หกพันบาทถ้วน')
    pdf.ln(15)
    pdf.cell(45, 10, u'           อัตราที่เบิกได้ต่อปี                                                                   (ลงชื่อ)......................................................ผู้รับเงิน')
    pdf.cell(0, 10, u'66,000')
    pdf.ln(7)
    pdf.cell(45, 10, u'           เบิกครั้งก่อน                                                                                 (..........................................................)    ')
    pdf.cell(73, 10, u'6,000')
    pdf.cell(0, 8, u'นายกิตติพงศ์ จันทร์นัณทยงว์ป่า')
    pdf.ln(7)
    pdf.cell(45, 10, u'           เบิกครั้งนี้ ')
    pdf.cell(0, 10, u'6,000')
    pdf.ln(7)
    pdf.cell(45, 10, u'           คงเหลือ                                                                               (ลงชื่อ)......................................................ผู้จ่ายเงิน ')
    pdf.cell(0, 10, u'6,000')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                                                                                          (..........................................................)')
    pdf.ln(7)
    pdf.cell(0, 10, u'                ....................................ผู้คุมยอดการเบิก                                     วันที่...........เดือน.........................พ.ศ...............')
    pdf.ln(13)
    pdf.cell(0, 10, u'     คำชี้แจง')
    pdf.ln(7)
    pdf.cell(0, 10, u'                   ให้ระบุการมีสิทธิเพียงใด เมื่อเทียบกับสิทธิที่ได้รับตามพระราชกฤษฎีกาเงินสวัสดิการเกี่ยวกับการศึกษาของบุตร')
    pdf.ln(7)
    pdf.cell(0, 10, u'                   ให้เสนอต่อผู่มีอำนาจอนุมัติ')
    pdf.ln(7)


    pdf.output("group4/bursary.pdf", 'F')

    # next path will open pdf file in new tab on browser.
    with open('group4/bursary.pdf', 'rb') as pdf: # path to pdf in directory views.
        response = HttpResponse(pdf.read(),content_type='application/pdf')
        response['Content-Disposition'] = 'filename=bursary.pdf'
        return response
    pdf.closed
Example #45
0
def addpdf(request, profID): # use to generate pdf file for lend another teacher.

    obj = WithdrawCure.objects.get(pk= int(profID))
    if obj.spouseW == '1':
        sp = Spouse.objects.get(user=obj.user)
    if obj.fatherW == '1':
        dad = Father.objects.get(user=obj.user)
    if obj.motherW == '1':
        mom = Mother.objects.get(user=obj.user)
    if obj.childW1 == '1':
        ch = Child.objects.all()
        ch1list = []
        for i in ch:
            if i.user == obj.user:
                ch1list.append(i)
        for j in ch1list:
            if obj.orderChildW1 == j.OrderF:
                ch1 = j

    if obj.childW2 == '1':
        ch = Child.objects.all()
        ch2list = []
        for i in ch:
            if i.user == obj.user:
                ch2list.append(i)
        for j in ch2list:
            if obj.orderChildW1 == j.OrderF:
                ch2 = j

    pres = EditPresident.objects.all()
    presi = pres[0]
    pdf = FPDF('P', 'mm', 'A4')    # start pdf file
    pdf.add_page()                 # begin first page.


    try:
        firstname = obj.user.firstname_th
    except:
        firstname = 'None'

    try:
        lastname = obj.user.lastname_th
    except:
        lastname = 'None'

    try:
        department = obj.user.department
    except:
        department = 'None'

    try:
        faculty = obj.user.faculty
    except:
        faculty = 'None'

    try:
        if obj.user.type=='1':
            typeu = Teacher.objects.get(userprofile=obj.user)
            typeuser = typeu.position
        elif obj.user.type=='2':
            typeu = Officer.objects.get(userprofile=obj.user)
            typeuser = typeu.position
    except:
        typeuser = '******'

    try:
        user = obj.user
    except:
        user = '******'

    try:
        account_id = obj.account_id
    except:
        account_id = 'None'

    try:
        disease = obj.disease
    except:
        disease = 'None'

    try:
        hospital = obj.hospital
    except:
        hospital = 'None'

    try:
        hospitalOf = obj.hospitalOf
    except:
        hospitalOf = 'None'

    try:
        startDate = obj.startDate
    except:
        startDate = 'None'

    try:
        stopDate = obj.stopDate
    except:
        stopDate = 'None'

    try:
        value = obj.value
    except:
        value = 'None'

    try:
        valueChar = obj.valueChar
    except:
        valueChar = 'None'

    try:
        numBill = obj.numBill
    except:
        numBill = 'None'

    try:
        typeWithdraw = obj.typeWithdraw
    except:
        typeWithdraw = 'None'

    pdf.line(12, 31, 198, 31)
    pdf.line(12, 31, 12, 285)
    pdf.line(12, 285, 198, 285)
    pdf.line(198, 31, 198, 285)
    pdf.line(12, 179, 198, 179)

    pdf.image('group4\A.png',145,113,6) #ก
    pdf.image('group4\B.png',140,190,6) #ข
    pdf.image('group4\C.png',27,254,6) #ค

    pdf.add_font('THSarabunNew Bold', '', 'THSarabunNew Bold.ttf', uni=True)
    pdf.set_font('THSarabunNew Bold', '', 18)
    pdf.cell(169, 10, u'                                    ใบเบิกเงินสวัสดิการเกี่ยวกับการรักษาพยาบาล     ')
    pdf.set_font('THSarabunNew Bold', '', 14)
    pdf.cell(0, 10, u'แบบ 7131')
    pdf.ln(8)
    pdf.cell(0, 10, u'                                     โปรดทำเครื่องหมาย      ลงในช่องว่าง  พร้อมทั้งกรอกข้อความให้ครบถ้วน    ')
    pdf.image('group4\son2.png',80,20,6)
    pdf.ln(16)
    pdf.add_font('THSarabunNew', '', 'THSarabunNew.ttf', uni=True)
    pdf.set_font('THSarabunNew', '', 14)
    pdf.cell(30, 10, u'     1. ข้าพเจ้า................................................................................................เลขที่บัญชีสหกรณ์ออมทรัพย์ SA-.....................................................')
    pdf.cell(115, 8, u'' + firstname + u'  ' + lastname)
    pdf.cell(20, 8, u'' + account_id)
    pdf.ln(7)
    pdf.cell(0, 10, u'        สถานะ  ข้าราชการ   ลูกจ้างประจำ   ข้าราชการบำนาญ(เปลี่ยนสถานะ และ เกษียณอายุ)   พนักงานมหาวิทยาลัย ')
    if typeuser == '0':
        pdf.image('group4\son2.png',29,43,6)
    elif typeuser == '1':
        pdf.image('group4\son2.png',49,43,6)
    elif typeuser == '2':
        pdf.image('group4\son2.png',73,43,6)
    elif typeuser == '3':
        pdf.image('group4\son2.png',145,43,6)
    pdf.ln(7)

    pdf.cell(40, 10, u'        สังกัด ภาควิชา.................................................................................................คณะ......................................................................................')
    if department == '1':
        pdf.cell(85, 8, u'วิศวกรรมไฟฟ้าและคอมพิวเตอร์')
    if faculty == '1':
        pdf.cell(0, 8, u'วิศวกรรมศาสตร์')
    pdf.ln(7)
    pdf.cell(0, 10, u'     2. ขอเบิกเงินค่ารักษาพยาบาลของ')
    pdf.ln(7)
    pdf.cell(0, 10, u'           ตนเอง')
    if obj.selfW == '1':
        pdf.image('group4/son2.png',20,64,6)
    pdf.ln(7)
    pdf.cell(40, 10, u'           คู่สมรส  ชื่อ...............................................................................เลขประจำตัวประชาชน......................................................')
    if obj.spouseW == '1':
        pdf.image('group4\son2.png',20,71,6)
        pdf.cell(90, 8, u'' + sp.title + sp.firstname +u'  '+sp.lastname)
        pdf.cell(0, 8, u''+ sp.pid)
    pdf.ln(7)
    pdf.cell(45, 10, u'                         ที่ทำงาน......................................................................ตำแหน่ง..............................................................................')
    if obj.spouseW == '1':
        pdf.cell(70, 8, u''+ sp.office)
        pdf.cell(0, 8, u''+sp.position)
    pdf.ln(7)

    pdf.cell(40, 10, u'           บิดา      ชื่อ..............................................................................เลขประจำตัวประชาชน......................................................')
    if obj.fatherW == '1':
        pdf.image('group4\son2.png',20,85,6)
        pdf.cell(90, 8, u'' + dad.title + dad.firstname+u'  '+ dad.lastname)
        pdf.cell(0, 8, u''+ dad.pid)
    pdf.ln(7)

    pdf.cell(40, 10, u'           มารดา   ชื่อ..............................................................................เลขประจำตัวประชาชน......................................................')
    if obj.motherW == '1':
        pdf.image('group4\son2.png',20,92,6)
        pdf.cell(90, 8, u''+ mom.title + mom.firstname + u'  '+ mom.lastname)
        pdf.cell(0, 8, u''+ mom.pid)
    pdf.ln(7)

    pdf.cell(40, 10, u'           บุตร      ชื่อ..............................................................................เลขประจำตัวประชาชน......................................................')
    if obj.childW1 == '1':
        pdf.image('group4\son2.png',20,99,6)
        pdf.cell(90, 8, u''+ ch1.title + ch1.firstname +u'  '+ch1.lastname)
        pdf.cell(0, 8, u''+ch1.pid)
    pdf.ln(7)
    pdf.cell(42, 10, u'                          เกิดเมื่อ.................................................เป็นบุตรลำดับที่(ของบิดา)..................เป็นบุตรลำดับที่(ของมารดา)................... ')
    if obj.childW1 == '1':
        pdf.cell(75, 8, u'' + str(ch1.birthDate))
        pdf.cell(50, 8, u'' + str(ch1.orderF))
        pdf.cell(0, 8, u'' + str(ch1.orderM))
    pdf.ln(7)
    pdf.cell(0, 10, u'                           ยังไม่บรรลุนิติภาวะ    เป็นบุตรไร้ความสามารถ หรือเสมือนไร้ความสามารถ ')
    if obj.childW1 == '1':
        if ch1.disable=='1':
            pdf.image('group4\son2.png',71,113,6)
        year = timezone.now().year
        month = timezone.now().month
        today = timezone.now().day
        print today
        birthdate = str(ch1.birthDate).split('-')
        year = year-int(birthdate[0])
        month = month-int(birthdate[1])
        today = today-int(birthdate[2])
        if year > 20   :
             pdf.image('group4\son2.png',38,113,6)
        elif year == 20 and month > 0 :
             pdf.image('group4\son2.png',38,113,6)
        elif year == 20 and today >= 0 and month == 0:
             pdf.image('group4\son2.png',38,113,6)

    pdf.ln(7)
    pdf.cell(40, 10, u'           บุตร      ชื่อ..............................................................................เลขประจำตัวประชาชน.....................................................')
    pdf.ln(7)
    pdf.cell(42, 10, u'                          เกิดเมื่อ.................................................เป็นบุตรลำดับที่(ของบิดา)..................เป็นบุตรลำดับที่(ของมารดา)................... ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                           ยังไม่บรรลุนิติภาวะ    เป็นบุตรไร้ความสามารถ หรือเสมือนไร้ความสามารถ ')
    pdf.ln(7)

    pdf.cell(35, 10, u'         ป่วยเป็นโรค............................................................................................................................................................................................')
    pdf.cell(20, 8, u'' + disease)
    pdf.ln(7)
    pdf.cell(95, 10, u'         และได้รับการตรวจรักษาพยาบาลจาก(ชื่อสถานพยาบาล).....................................................................................................................')
    pdf.cell(20, 8, u'' + hospital)
    pdf.ln(7)
    pdf.cell(115, 10, u'         ซึ่งเป็นสถานพยาบาลของ    ของทางราชการ     เอกชน   ตั้งแต่วันที่.........................................................................................')
    pdf.cell(20, 8, u'' + str(startDate) )
    if hospitalOf == '0':
        pdf.image('group4\son2.png',55,155,6)
    elif hospitalOf == '1':
        pdf.image('group4\son2.png',85,155,6)
    pdf.ln(7)
    pdf.cell(30, 10, u'         ถึงวันที่...........................................................................................เป็นเงินรวมทั้งสิ้น.....................................................................บาท')
    pdf.cell(100, 8, u'' + str(stopDate))
    pdf.cell(20, 8, u'' + str(value))
    pdf.ln(7)
    pdf.cell(30, 10, u'         (.......................................................................................................................) ตามใบเสร็จรับเงินที่แนบ จำนวน.........................ฉบับ')
    pdf.cell(128, 8, u'' + valueChar)
    pdf.cell(20, 8, u'' + str(numBill))
    pdf.ln(14)

    pdf.cell(0, 10, u'    3. ข้าพเจ้ามีสิทธิได้รับเงินสวัสดิการเกี่ยวกับการรักษาพยาบาล ตามพระราชกฤษฎีกาเงินสวัสดิการเกี่ยวกับการรักษาพยาบาล ')
    pdf.ln(7)
    pdf.cell(0, 10, u'         ตามสิทธิ                     เฉพาะส่วนที่ขาดอยู่จากสิทธิที่ได้รับจากหน่วยงานอื่น ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                            เฉพาะส่วนที่ขาดอยู่จากสัญญาประกันภัย ')
    pdf.ln(7)

    pdf.cell(30, 10, u'       เป็นเงิน.....................................................บาท (............................................................................................................................) และ ')
    pdf.cell(55, 8, u'' + str(value))
    pdf.cell(0, 8, u'' + valueChar)
    pdf.ln(12)
    pdf.cell(0, 10, u'       (1)  ข้าพเจ้า                ไม่มีสิทธิได้รับค่ารักษาพยาบาลจากหน่วยงานอื่น  ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                      มีสิทธิได้รับค่ารักษาพยาบาลจากหน่วยงานอื่นแต่เลือกใช้สิทธิจากทางราชการ ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                      มีสิทธิได้รับค่ารักษาพยาบาลตามสัญญาประกันภัย  ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                      เป็นผู้ใช้สิทธิเบิกค่ารักษาพยาบาลสำหรับบุตรแค่เพียงฝ่ายเดียว ')
    pdf.ln(10)


    pdf.cell(0, 10, u'       (2) ................ข้าพเจ้า     ไม่มีสิทธิได้รับค่ารักษาพยาบาลจากหน่วยงานอื่น                      ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                      มีสิทธิได้รับค่ารักษาพยาบาลจากหน่วยงานอื่นแต่ค่ารักษาพยาบาลที่ได้รับต่ำกว่าสิทธิตามพระราชกฤษฎีกาฯ ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                      มีสิทธิได้รับค่ารักษาพยาบาลตามสัญญาประกันภัย ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                      มีสิทธิได้รับค่ารักษาพยาบาลจากหน่วยงานอื่นในฐานะเป็นผู้อาศัยสิทธิของผู้อื่น ')
    pdf.ln(7)



    pdf.add_page()

    #frame
    pdf.line(12, 15, 198, 15)
    pdf.line(12, 15, 12, 282)
    pdf.line(12, 282, 198, 282)
    pdf.line(198, 15, 198, 282)
    pdf.line(12, 80, 198, 80)
    pdf.line(12, 137, 198, 137)

    #table
    pdf.line(20, 170, 80, 170)
    pdf.line(20, 170, 20, 215)
    pdf.line(20, 215, 80, 215)
    pdf.line(80, 170, 80, 215)
    pdf.line(20, 178, 80, 178)
    pdf.line(20, 185, 80, 185)
    pdf.line(20, 193, 80, 193)
    pdf.line(20, 200, 80, 200)
    pdf.line(42, 170, 42, 200)

    pdf.image('group4\D.png',55,19,6) #ง

    pdf.image('group4\A.png',19,239,6) #A
    pdf.image('group4\B.png',19,246,6) #B
    pdf.image('group4\C.png',19,260,6) #C
    pdf.image('group4\D.png',19,267,6) #D


    pdf.add_font('THSarabunNew', '', 'THSarabunNew.ttf', uni=True)
    pdf.set_font('THSarabunNew', '', 14)
    pdf.cell(0, 10, u'')
    pdf.ln(7)
    pdf.cell(0, 10, u'     4. เสนอ อธิการบดี')
    pdf.ln(14)
    pdf.cell(0, 10, u'                      ข้าพเจ้าขอรับรองว่าข้าพเจ้ามีสิทธิเบิกค่ารักษาพยาบาลสำหรับตนเองและบุคคลในครอบครัวตามจำนวนที่ขอเบิก ซึ่งกำหนด')
    pdf.ln(7)
    pdf.cell(0, 10, u'      ไว้ในกฏหมายและข้อความข้างต้นเป็นจริงทุกประการ')
    pdf.ln(16)
    pdf.cell(0, 10, u'                                                                                       (ลงชื่อ)........................................................ผู้รับเงินสวัสดิการ')
    pdf.ln(7)
    pdf.cell(103, 10, u'                                                                                             (..........................................................)')
    pdf.cell(0, 8, u'' + firstname + u'  ' + lastname)
    pdf.ln(7)
    pdf.cell(0, 10, u'                                                                                          วันที่............เดือน..........................พ.ศ...............')
    pdf.ln(14)

    pdf.cell(0, 10, u'    5. คำอนุมัติ ')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                  อนุมัติให้เบิกได้')
    pdf.ln(14)
    pdf.cell(0, 10, u'                                                                       (ลงชื่อ)........................................................ ')
    pdf.ln(7)
    pdf.cell(86, 10, u'                                                                             (..........................................................)')
    pdf.cell(0, 8, u'' + presi.presidentName)
    pdf.ln(7)
    pdf.cell(90, 10, u'                                                                      ตำแหน่ง..........................................................')
    pdf.cell(0, 8, u'' + presi.position)
    pdf.ln(7)
    pdf.cell(0, 10, u'                                                                     วันที่............เดือน..........................พ.ศ............... ')
    pdf.ln(14)

    pdf.cell(0, 10, u'    6. ใบรับเงิน')
    pdf.ln(7)
    pdf.cell(100, 10, u'                 ได้รับเงินสวัสดิการเกี่ยวกับการรักษาพยาบาล จำนวน...........................................................................บาท ')
    pdf.cell(0, 8, u'' + str(value))
    pdf.ln(7)
    pdf.cell(30, 10, u'          (................................................................................................................................................)ไปถูกต้องแล้ว ')
    pdf.cell(0, 8, u'' + valueChar)
    pdf.ln(18)
    pdf.cell(40, 10, u'           วงเงินที่ได้รับ                                                                          (ลงชื่อ)......................................................ผู้รับเงิน')
    pdf.cell(0, 8, u'20,000')
    pdf.ln(7)
    pdf.cell(40, 10, u'           เบิกครั้งก่อน                                                                                 (..........................................................)    ')
    pdf.cell(78, 8, u'9,999')
    pdf.cell(0, 8, u'' + firstname + u'  ' + lastname)
    pdf.ln(7)
    pdf.cell(40, 10, u'           เบิกครั้งนี้ ')
    pdf.cell(0, 8, u'9,999')
    pdf.ln(7)
    pdf.cell(40, 10, u'           คงเหลือ                                                                               (ลงชื่อ)......................................................ผู้จ่ายเงิน ')
    pdf.cell(0, 8, u'9,999')
    pdf.ln(7)
    pdf.cell(0, 10, u'                                                                                                          (..........................................................)')
    pdf.ln(7)
    pdf.cell(0, 10, u'                ....................................ผู้คุมยอดการเบิก                                     วันที่...........เดือน.........................พ.ศ...............')
    pdf.ln(22)
    pdf.cell(0, 10, u'                                                                            คำชี้แจง')
    pdf.ln(10)
    pdf.cell(0, 10, u'              ให้แนบสำเนาคำสั่งศาลที่สั่ง/พิพากษาให้เป็นบุคคลไร้ความสามารถ  หรือเสมือนไร้ความสามารถ ')
    pdf.ln(7)
    pdf.cell(0, 10, u'              ให้มีคำชี้แจงด้วยว่ามีสิทธิเพียงใด และขาดอยู่เท่าใด กรณีที่ได้รับจากหน่วยงานอื่นเมื่อเทียบสิทธิตามพระราชกฤษฎีกาเงินสวัสดิการ')
    pdf.ln(7)
    pdf.cell(0, 10, u'               เกี่ยวกับการรักษาพยาบาลหรือขาดอยู่เท่าใดเมื่อได้รับค่ารักษาพยาบาลตามสัญญาประกันภัย ')
    pdf.ln(7)
    pdf.cell(0, 10, u'              ให้เติมคำว่า คู่สมรส บิดา มารดา หรือบุตรแล้วแต่กรณี')
    pdf.ln(7)
    pdf.cell(0, 10, u'              ให้เสนอต่อผู้มีอำนาจอนุมัติ')
    pdf.ln(7)

    pdf.output("group4/safe.pdf", 'F')

    # next path will open pdf file in new tab on browser.
    with open('group4/safe.pdf', 'rb') as pdf: # path to pdf in directory views.
        response = HttpResponse(pdf.read(),content_type='application/pdf')
        response['Content-Disposition'] = 'filename=safe.pdf'
        return response
    pdf.closed
Example #46
0
from fpdf import FPDF

pdf = FPDF()

#header of the pdf file
header = 'Header of PDF Report'
pdf.add_page()
pdf.set_font('Arial', 'B', 16)
w = pdf.get_string_width(header) + 6
pdf.set_x((210 - w) / 2)
pdf.cell(w, 9, header, 0, 0, 'C')
pdf.line(20, 18, 210 - 20, 18)

#line break
pdf.ln(10)
pdf.set_font('Times', '', 12)
pdf.multi_cell(
    0, 5,
    'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'
)

pdf.ln()
pdf.set_font('Arial', '', 12)
pdf.set_fill_color(200, 220, 255)
pdf.cell(0, 6, 'Chapter %d : %s' % (1, 'Sample Label'), 0, 1, 'L', 1)

pdf.ln()
pdf.set_font('Courier', 'B', 12)
pdf.multi_cell(
    0, 5,
    'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'
Example #47
0
class kut2fpdf(object):

    _document = None  # Aquí se irán guardando los datos del documento
    logger = None
    _xml = None
    _xml_data = None
    _page_orientation = None
    _page_size = None
    _bottom_margin = None
    _left_margin = None
    _right_margin = None
    _top_margin = None
    _page_top = {}
    _data_row = None  # Apunta a la fila actual en data
    _parser_tools = None
    _avalible_fonts = []

    def __init__(self):

        self.logger = logging.getLogger("kut2rml")
        checkDependencies({"fpdf": "fpdf"})
        from pineboolib.plugins.kugar.parsertools import parsertools
        self._parser_tools = parsertools()

    """
    Convierte una cadena de texto que contiene el ".kut" en un pdf y retorna la ruta a este último.
    @param name. Nombre de ".kut".
    @param kut. Cadena de texto que contiene el ".kut".
    @param data. Cadena de texto que contiene los datos para ser rellenados en el informe.
    @return Ruta a fichero pdf.
    """

    def parse(self, name, kut, data):

        try:
            self._xml = self._parser_tools.loadKut(kut)
        except Exception:
            self.logger.exception(
                "KUT2FPDF: Problema al procesar %s.kut", name)
            return False

        try:
            self._xml_data = load2xml(data)
        except Exception:
            self.logger.exception("KUT2FPDF: Problema al procesar xml_data")
            return False

        self.setPageFormat(self._xml)
        # self._page_orientation =
        # self._page_size =

        from fpdf import FPDF
        self._document = FPDF(self._page_orientation, "pt", self._page_size)
        # Seteamos rutas a carpetas con tipos de letra ...

        # Cargamos las fuentes disponibles
        for f in self._document.core_fonts:
            self.logger.debug("KUT2FPDF :: Adding font %s", f)
            self._avalible_fonts.append(f)

        self.newPage()
        self.processDetails()

        pdfname = pineboolib.project.getTempDir()
        pdfname += "/%s_%s.pdf" % (name, datetime.datetime.now().strftime("%Y%m%d%H%M%S"))

        # Datos del creador del documento
        self._document.set_title(name)
        self._document.set_author("Pineboo - kut2fpdf plugin")

        self._document.output(pdfname, 'F')

        return pdfname

    """
    Indica el techo para calcular la posición de los objetos de esa sección.
    @return Número con el techo de la página actual.
    """

    def topSection(self):
        return self._page_top[str(self._document.page_no())]

    """
    Actualiza el valor del techo de la página actual. Se suele actualizar al procesar una sección.
    @param value. Numero que elspecifica el nuevo techo.
    """

    def setTopSection(self, value):
        self._page_top[str(self._document.page_no())] = value

    """
    Añade una nueva página al documento.
    """

    def newPage(self):
        self._document.add_page(self._page_orientation)
        self._page_top[str(self._document.page_no())] = self._top_margin
        self._document.set_margins(self._left_margin, self._top_margin,
                                   self._right_margin)  # Lo dejo pero no se nota nada
        # Corta con el borde inferior ...
        # self._document.set_auto_page_break(
        #    True, self._document.h - self._bottom_margin)

        self.processSection("PageHeader")
    """
    Procesa las secciones details con sus correspondientes detailHeader y detailFooter.
    """

    def processDetails(self):
        # Procesamos la cabecera si procede ..
        prevLevel = 0
        level = None
        for data in self._xml_data.findall("Row"):
            level = int(data.get("level"))
            if prevLevel > level:
                self.processData("DetailFooter", data, prevLevel)
            elif prevLevel < level:
                self.processData("DetailHeader",  data, level)

            self.processData("Detail", data, level)

            prevLevel = level

        if level:
            for l in reversed(range(level + 1)):
                self.processData("DetailFooter", data, l)

        if self._xml.find("PageFooter"):
            self.processSection("PageFooter")
        elif self._xml.find("AddOnFooter"):
            self.processSection("AddOnFooter")

    """
    Paso intermedio que calcula si detailHeader + detail + detailFooter entran en el resto de la ṕagina. Si no es así crea nueva página.
    @param section_name. Nombre de la sección a procesar.
    @param data. Linea de datos a procesar.
    @param data_level. Nivel de seccion.
    """

    def processData(self, section_name, data, data_level):
        listDF = self._xml.findall(section_name)
        for dF in listDF:
            if dF.get("Level") == str(data_level):
                if section_name == "Detail" and (not dF.get("DrawIf") or data.get(dF.get("DrawIf"))):
                    heightCalculated = self._parser_tools.getHeight(dF) + self.topSection()
                    for dFooter in self._xml.findall("DetailFooter"):
                        if dFooter.get("Level") == str(data_level):
                            heightCalculated += self._parser_tools.getHeight(dFooter)
                    pageFooter = self._xml.get("PageFooter")
                    if pageFooter:
                        if self._document.page_no() == 1 or pageFooter.get("PrintFrecuency") == "1":
                            heightCalculated += self._parser_tools.getHeight(pageFooter)

                    heightCalculated += self._bottom_margin

                    if heightCalculated > self._document.h:  # Si nos pasamos
                        self.processSection("PageFooter")  # Pie de página
                        self.newPage()

                if not dF.get("DrawIf") or data.get(dF.get("DrawIf")):
                    self.processXML(dF, data)
                    #self.logger.debug("%s_BOTTON = %s" % (name.upper(), self.actualVSize[str(self.pagina)]))

    """
    Procesa las secciones fuera de detail, pageHeader, pageFooter, AddOnFooter.
    @param name. Nombre de la sección a procesar.
    """

    def processSection(self, name):
        sec_ = self._xml.find(name)
        if sec_:
            if sec_.get("PrintFrequency") == "1" or self._document.page_no() == 1:
                if sec_.tag == "PageFooter":
                    self.setTopSection(self._document.h - int(sec_.get("Height")))
                self.processXML(sec_)

    """
    Procesa un elemento de xml.
    @param xml: El elemento a procesar.
    @param. data: Linea de datos afectada.
    """

    def processXML(self, xml, data=None):
        fix_height = True
        if xml.tag == "DetailFooter":
            if xml.get("PlaceAtBottom") == "true":
                self.setTopSection(self.topSection() + self._parser_tools.getHeight(xml))

        if xml.tag == "PageFooter":
            fix_height = False

        for child in xml.iter():
            if child.tag in ("Label", "Field", "Special", "CalculatedField"):
                self.processText(child, data, fix_height)
            elif child.tag == "Line":
                self.processLine(child, fix_height)

        if xml.get("PlaceAtBottom") != "true":
            self.setTopSection(self.topSection() + self._parser_tools.getHeight(xml))

    """
    Procesa una linea.
    @param xml. Sección de xml a procesar.
    @param fix_height. Ajusta la altura a los .kut originales, excepto el pageFooter.
    """

    def processLine(self, xml, fix_height=True):

        color = xml.get("Color")
        r = 0 if not color else int(color.split(",")[0])
        g = 0 if not color else int(color.split(",")[1])
        b = 0 if not color else int(color.split(",")[2])

        #style = int(xml.get("Style"))
        width = int(xml.get("Width"))
        X1 = self.calculateLeftStart(xml.get("X1"))
        X2 = self.calculateRightEnd(xml.get("X2"))
        # Ajustar altura a secciones ya creadas
        Y1 = int(xml.get("Y1")) + self.topSection()
        Y2 = int(xml.get("Y2")) + self.topSection()
        if fix_height:
            Y1 = self._parser_tools.heightCorrection(Y1)
            Y2 = self._parser_tools.heightCorrection(Y2)
        self._document.set_line_width(width)
        self._document.set_draw_color(r, g, b)
        self._document.line(X1, Y1, X2, Y2)

    """
    Comprueba si excedemos el margen izquierdo de la página actual
    @param x. Posición a comprobar.
    @return Valor corregido, si procede.
    """

    def calculateLeftStart(self, x):
        x = int(x)
        ret_ = x
        if x < self._left_margin:
            ret_ = self._left_margin

        return ret_

    """
    Comprueba si excedemos el margen derecho de la página actual
    @param x. Posición a comprobar.
    @return Valor corregido, si procede.
    """

    def calculateRightEnd(self, x):
        x = int(x)
        ret_ = x
        if x > (self._document.w - self._right_margin):
            ret_ = self._document.w - self._right_margin

        return ret_

    """
    Procesa una etiqueta. Esta peude ser un campo calculado, una etiqueta, un campo especial o una imagen.
    @param xml. Sección de xml a procesar.
    @param fix_height. Ajusta la altura a los .kut originales, excepto el pageFooter.
    """

    def processText(self, xml, data_row=None, fix_height=True):
        isImage = False
        text = xml.get("Text")
        BorderWidth = int(xml.get("BorderWidth"))
        borderColor = xml.get("BorderColor")

        # x,y,W,H se calcula y corrigen aquí para luego estar correctos en los diferentes destinos posibles
        W = int(xml.get("Width"))
        H = self._parser_tools.getHeight(xml)

        x = int(xml.get("X"))
        y = int(xml.get("Y")) + self.topSection()  # Añade la altura que hay ocupada por otras secciones
        if fix_height:
            y = self._parser_tools.heightCorrection(y)  # Corrige la posición con respecto al kut original

        dataType = xml.get("Datatype")

        if xml.tag == "Field" and data_row is not None:
            text = data_row.get(xml.get("Field"))

        elif xml.tag == "Special":
            text = self._parser_tools.getSpecial(
                text[1:len(text) - 1], self._document.page_no())

        elif xml.tag == "CalculatedField":
            if xml.get("FunctionName"):
                function_name = xml.get("FunctionName")
                try:
                    nodo = self._parser_tools.convertToNode(data_row)
                    text = str(pineboolib.project.call(function_name, [nodo]))
                except Exception:
                    self.logger.exception(
                        "KUT2FPDF:: Error llamando a function %s", function_name)
                    return
            else:
                if data_row is None:
                    data_row = self._xml_data[0]
                if xml.get("Field"):
                    text = data_row.get(
                        xml.get("Field")) if not "None" else ""

            if text and dataType is not None:
                text = self._parser_tools.calculated(text, int(dataType), xml.get("Precision"), data_row)

            if dataType == "5":
                isImage = True

        if text and text.startswith(filedir("../tempdata")):
            isImage = True

        precision = xml.get("Precision")
        negValueColor = xml.get("NegValueColor")
        Currency = xml.get("Currency")

        commaSeparator = xml.get("CommaSeparator")
        dateFormat = xml.get("DateFormat")

        if not isImage:

            self.drawText(x, y, W, H, xml, text)
        else:
            self.drawImage(x, y, W, H, xml, text)

    """
    Dibuja un campo texto en la página.
    @param x. Pos x de la etiqueta.
    @param y. Pos y de la etiqueta.
    @param W. Anchura de la etiqueta.
    @param H. Altura de la etiqueta.
    @param xml. Sección del xml afectada.
    @param txt. Texto calculado de la etiqueta a crear.
    """

    def drawText(self, x, y, W, H, xml, txt):

        if txt in ("None", None):
            return

        # Corregimos margenes:
        x = self.calculateLeftStart(x)
        W = self.calculateRightEnd(x + W) - x

        bg_color = xml.get("BackgroundColor").split(",")
        fg_color = xml.get("ForegroundColor").split(",")

        self._document.set_text_color(int(fg_color[0]), int(fg_color[1]), int(fg_color[2]))
        self._document.set_fill_color(int(bg_color[0]), int(bg_color[1]), int(bg_color[2]))

        if xml.get("BorderStyle") == "1":
            # FIXME: Hay que ajustar los margenes
            self.drawRect(x, y, W, H)

        #font_name, font_size, font_style
        font_style = ""
        font_size = int(xml.get("FontSize"))
        font_name = xml.get("FontFamily").lower()

        fontW = int(xml.get("FontWeight"))
        fontI = xml.get("FontItalic")
        fontU = xml.get("FontUnderlined")  # FIXME: hay que ver si es así

        if fontW > 60 and font_size > 10:
            font_style += "B"

        if fontI == "1":
            font_style += "I"

        if fontU == "1":
            font_style += "U"

        while font_name not in self._avalible_fonts:
            font_found = self._parser_tools.find_font(font_name)
            if font_found:
                self.logger.info("KUT2FPDF::Añadiendo el tipo de letra %s (%s)", font_name, font_found)
                self._document.add_font(font_name, "", font_found, True)
                self._avalible_fonts.append(font_name)

            else:
                self.logger.warning("KUT2FPDF:: No se encuentra el tipo de letra %s. Sustituido por helvetica.", font_name)
                font_name = "helvetica"

        self._document.set_font(font_name, font_style, font_size)

        # Corregir alineación
        VAlignment = xml.get("VAlignment")  # 0 izquierda, 1 centrado,2 derecha
        HAlignment = xml.get("HAlignment")

        if HAlignment == "1":  # sobre X
            # Centrado
            x = x + (W / 2) - (self._document.get_string_width(txt) / 2)
        elif HAlignment == "2":
            # Derecha
            x = x + W - self._document.get_string_width(txt)
        else:
            # Izquierda
            x = x

        if VAlignment == "1":  # sobre Y
            # Centrado
            y = (y + H / 2) + (self._document.font_size_pt / 2)
        elif VAlignment == "2":
            # Abajo
            y = y + W - font_size
        else:
            # Arriba
            y = y

        self._document.text(x, y, txt)

    """
    Dibuja un cuadrado en la página actual.
    @param x. Pos x del cuadrado.
    @param y. Pos y del cuadrado.
    @param W. Anchura del cuadrado.
    @param H. Altura del cuadrado.
    """

    def drawRect(self, x, y, W, H):
        self._document.rect(x, y, W, H, "DF")

    """
    Inserta una imagen en la página actual.
    @param x. Pos x de la imagen.
    @param y. Pos y de la imagen.
    @param W. Anchura de la imagen.
    @param H. Altura de la imagen.
    @param xml. Sección del xml afectada.
    @param file_name. Nombr del fichero de tempdata a usar
    """

    def drawImage(self, x, y, W, H, xml, file_name):

        self._document.image(file_name, x, y, W, H, "PNG")
    """
    Define los parámetros de la página
    @param xml: Elemento xml con los datos del fichero .kut a procesar
    """

    def setPageFormat(self, xml):
        custom_size = None

        self._bottom_margin = int(xml.get("BottomMargin"))
        self._left_margin = int(xml.get("LeftMargin"))
        self._right_margin = int(xml.get("RightMargin"))
        self._top_margin = int(xml.get("TopMargin"))

        page_size = int(xml.get("PageSize"))
        page_orientation = xml.get("PageOrientation")

        if page_size in [30, 31]:
            custom_size = [int(xml.get("CustomHeightMM")), int(xml.get("CustomWidthMM"))]

        self._page_orientation = "P" if page_orientation == "0" else "L"
        self._page_size = self._parser_tools.converPageSize(
            page_size, int(page_orientation), custom_size)  # devuelve un array