def test_link_with_zoom_and_shift(tmp_path): pdf = FPDF() pdf.set_font("helvetica", size=24) pdf.add_page() link = pdf.add_link() pdf.set_link(link, page=2, x=pdf.epw / 4, y=pdf.epw / 3, zoom=4) pdf.set_xy(30, 50) pdf.cell( w=140, h=10, txt="Link to 2nd page zoomed & shifted", border=1, align="C", link=link, ) pdf.add_page() pdf.multi_cell( pdf.epw, txt="Lorem ipsum dolor sit amet, consectetur adipiscing elit," " sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." " Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." " Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." " Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", ) # Drawing Adobe Reader viewport after clicking on the link, # with the right panel open. The initial zoom level does not matter. pdf.set_draw_color(r=255, g=0, b=0) pdf.rect(x=pdf.epw / 4, y=pdf.epw / 3, w=53.5, h=31) assert_pdf_equal(pdf, HERE / "link_with_zoom_and_shift.pdf", tmp_path)
def color_code_to_pdf(colored_square_code: str, output_file_name: str = "fractal") -> None: """Method for converting a color_code to a pdf file Args: colored_square_code: The encoded colored square. Encoded using hex color codes in 9 chunks each of length 3 or 6 Obtained from the database. output_file_name: Returns: File is output to images directory with the given file name """ if "." in output_file_name: output_file_name = output_file_name.split('.')[0] colored_square_list = Image.decode_square(colored_square_code) pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) for i in colored_square_list: for j in range(9): pdf.set_fill_color(r=i["red"], g=i["green"], b=i["blue"]) pdf.rect(x=i["index"][0] * 20, y=i["index"][1] * 20, w=20, h=20, style='F') pdf.output(name=f"{ROOT}/images/{output_file_name}.pdf") print(f"File output to {output_file_name}.pdf")
def create_markers(marker_type): # Get marker IDs marker_ids = utils.get_marker_ids(marker_type) if marker_type == 'robots': marker_ids = 5 * marker_ids + marker_ids[:4] elif marker_type == 'cubes': marker_ids = [ marker_id for marker_id in marker_ids[:8] for _ in range(6) ] elif marker_type == 'corners': marker_ids = 3 * marker_ids + marker_ids[:15] # Paper params output_dir = 'printouts' pdf_name = 'markers-{}.pdf'.format(marker_type) orientation = 'P' paper_params = utils.get_paper_params(orientation) # Marker params marker_length = 0.018 # 18 mm marker_length_pixels = 6 sticker_length_mm = {'robots': 25, 'cubes': 28, 'corners': 24}[marker_type] sticker_spacing_mm = 3 marker_length_mm = 1000 * marker_length scale_factor = marker_length_mm / (paper_params['mm_per_printed_pixel'] * marker_length_pixels) stickers_per_row = int( (paper_params['width_mm'] - 2 * paper_params['margin_mm']) / (sticker_length_mm + sticker_spacing_mm)) aruco_dict = cv2.aruco.Dictionary_get(utils.get_marker_dict_id()) # Create PDF pdf = FPDF(orientation, 'mm', 'letter') pdf.add_page() with tempfile.TemporaryDirectory() as tmp_dir_name: for i, marker_id in enumerate(marker_ids): image_path = str(Path(tmp_dir_name) / '{}.png'.format(marker_id)) Image.fromarray( cv2.aruco.drawMarker( aruco_dict, marker_id, int(scale_factor * marker_length_pixels))).save(image_path) center_x = (sticker_length_mm + sticker_spacing_mm) * (i % stickers_per_row + 1) center_y = (sticker_length_mm + sticker_spacing_mm) * (i // stickers_per_row + 1) pdf.rect(x=(center_x - sticker_length_mm / 2 - pdf.line_width / 2), y=(center_y - sticker_length_mm / 2 - pdf.line_width / 2), w=(sticker_length_mm + pdf.line_width), h=(sticker_length_mm + pdf.line_width)) pdf.image(image_path, x=(center_x - marker_length_mm / 2), y=(center_y - marker_length_mm / 2), w=marker_length_mm, h=marker_length_mm) # Save PDF output_dir = Path(output_dir) if not output_dir.exists(): output_dir.mkdir(parents=True) pdf.output(output_dir / pdf_name)
def generate_hall_ticket(email, subjects): pdf = FPDF() pdf.add_page() pdf.image('static\\images\\images.jpg', x=47, y=30) pdf.set_font('arial', 'B', 23.0) pdf.cell(ln=0, h=7.0, align='C', w=0, txt="Hall Ticket", border=0) pdf.rect(20, 20, 165, 250) x = 30 y = 90 for subject in subjects: pdf.set_font('arial', 'B', 13.0) pdf.set_xy(x, y) y += 6 pdf.cell(ln=0, h=7.0, align='L', w=0, txt='{}({})'.format(subject.subject_name, subject.subject_code), border=0) pdf.set_font('arial', 'B', 8.0) pdf.set_xy(x, y) y += 6 pdf.cell(ln=0, h=7.0, align='L', w=0, txt=subject.exam_date, border=0) new = "" for i in email: if i == '.': new += '_' else: new += i pdf.output('static\\pdf\\{}.pdf'.format(new), 'F') return 'static\\pdf\\{}.pdf'.format(new)
def make_pdf(self, **kwargs): # grabing the inputed values serial_no = self.sr_no.text name = self.name_input.text email = self.mail_input.text content = self.contents_input.text tot = self.total_input.text doc = FPDF(orientation='P', unit='mm', format='A4') doc.add_page() doc.rect(5, 5, 200, 287, 'D') doc.image('logo.jpg', 165, 10, 30, 30, type='JPG') doc.set_font('Times', size=28, style='B') doc.ln(10) doc.cell(90) doc.cell(10, 10, txt="SMART-RECEIPT", align='C') doc.ln(25) doc.set_font('Arial', size=17, style='B') doc.cell(20) doc.cell(30, 7, txt=f"SR No : {serial_no}", align='L') doc.ln() doc.cell(20) doc.cell(30, 7, txt=f"Name : {name}", align='L') doc.ln() doc.cell(20) doc.cell(30, 7, txt=f"E-mail : {email}", align='L') doc.ln(15) doc.cell(20) doc.set_font('Arial', size=20, style='B') doc.cell(30, 10, txt="Contents : ", align='L') doc.ln(10) doc.cell(20) doc.set_font('Arial', size=14, style='B') doc.multi_cell(150, 10, txt=f"{content}", align='L', border=1) doc.ln(20) doc.cell(20) doc.cell(90, 15, txt=f" Total : RS. {tot}", align='L', border=1) doc.ln(20) doc.cell(20) doc.cell(20, 10, txt=f"Date : {dt}", align='L') doc.ln(50) doc.cell(150) doc.cell(30, 15, txt=" VERIFIED", align='L', border=1) doc.set_font('Times', style='B', size=15) doc.ln(40) doc.cell( 50, 5, txt= "Please Check the receipt carefully and acknowledge probems if any.", align='L') doc.ln() doc.set_font('Times', style='B', size=15) doc.cell(50, 5, txt='For any queries write to : ') doc.cell(10) doc.set_text_color(0, 0, 255) doc.set_font('Times', style='U', size=15) doc.cell(30, 7, txt='*****@*****.**', link='*****@*****.**') doc.output('sample.pdf')
class SignInSheet: LIST_COLUMN_Y_START = 40 LIST_COLUMN_Y_STOP = 275 LIST_COLUMN_1_X = 40 LIST_COLUMN_2_X = 120 LIST_ENTRY_FONT_SIZE = 10 def __init__(self, page_title=None, page_subtitle=None, names=None, output_filepath=None): self.page_title = page_title self.page_subtitle = page_subtitle self.output_filepath = output_filepath if output_filepath else "sign_in_sheet.pdf" self.names = names if names is not None else [] self.pdf = None def generate(self): try: self.pdf = FPDF() self.add_page() current_x = self.LIST_COLUMN_1_X current_y = self.LIST_COLUMN_Y_START for name in sorted(self.names): self.pdf.set_font('Arial', size=self.LIST_ENTRY_FONT_SIZE) self.pdf.rect(current_x - 5, current_y - 2.5, w=3, h=3) self.pdf.text(current_x, current_y, name) current_y += 6 if current_y > self.LIST_COLUMN_Y_STOP: current_y = self.LIST_COLUMN_Y_START if current_x == self.LIST_COLUMN_1_X: current_x = self.LIST_COLUMN_2_X else: current_x = self.LIST_COLUMN_1_X self.add_page() self.pdf.output(self.output_filepath, 'F') finally: self.pdf = None def add_page(self): self.pdf.add_page() self.generate_headers() def generate_headers(self): if self.page_title: self.pdf.set_font('Arial', 'B', 16) self.pdf.cell(0, txt=self.page_title, h=10, ln=1, align='C') if self.page_subtitle: self.pdf.set_font('Arial', 'B', 14) self.pdf.cell(0, txt=self.page_subtitle, h=10, ln=1, align='C')
def draw_shapes(): pdf = FPDF() pdf.add_page() pdf.set_fill_color(0, 255, 255) pdf.ellipse(10, 10, 10, 100, 'F') # F: Fill; DF: Draw & fill pdf.set_line_width(1) pdf.set_fill_color(255, 0, 255) pdf.rect(15, 15, 100, 50) pdf.output('draw_shapes.pdf')
def draw_shapes(): pdf = FPDF() pdf.add_page() pdf.set_fill_color(255, 0, 0) pdf.ellipse(10, 10, 10, 100, 'F') pdf.set_line_width(1) pdf.set_fill_color(0, 255, 0) pdf.rect(20, 20, 100, 50) pdf.output('draw_shapes.pdf')
def draw_shapes(request): pdf = FPDF() pdf.add_page() pdf.set_fill_color(255, 0, 0) pdf.ellipse(10, 10, 10, 100, 'F') pdf.set_line_width(1) pdf.set_fill_color(0, 255, 0) pdf.rect(20, 20, 100, 50) pdf.output('draw_shapes.pdf') return HttpResponse('<h1>Pdf created successfully</h1>')
def pokepdf(pokemon): # FPDF Object pdf = FPDF("L", "mm", "A5") # Add page pdf.add_page() # Paint the background pdf.set_fill_color(*color.get(pokemon["type"][0], (255, ))) pdf.rect(0, 0, 210, 297, "F") # Set font pdf.set_font(*fonts["title"]) pdf.set_xy(20, 10) # Add Pokeball ball = {False: "pokeball", True: "masterball"}[pokemon["legendary"]] pdf.image(f"images/balls/{ball}.png", pdf.get_x(), pdf.get_y() + 25, w=20) # Add Pokemon Name pdf.cell(w=0, txt=f"{pokemon['id']} - {pokemon['name']}".title(), align="C", ln=1) # Add Pokemon Sprite pdf.image(pokemon["sprite_url"], 80, pdf.get_y() + 10, w=50) # Set new font font = fonts["flavor"] pdf.set_font(*font) pdf.set_xy(10, 70) # Cut text if larger than page flavor = chunks(pokemon["flavor"], font) # Add flavor text for i in flavor: pdf.cell(w=0, h=5, txt=i, align="C", ln=2) # Add type symbols for i, typ in enumerate(pokemon["type"]): if len(pokemon["type"]) == 1: pos = [90] else: pos = [50, 120] pdf.image(f"images/types/{typ}.png", pos[i], pdf.get_y() + 15, w=40) # Export pdf path = f"output/{pokemon['id']}_{pokemon['name']}.pdf" pdf.output(path) print(f"pdf saved to {path}")
def generatePdf(keywords): mbPaths = getMagicSchoolBusPaths() txts = buildPageTxt(keywords) pdf = FPDF() pageNumb = 0 for keyword in keywords: pdf.add_page() pdf.set_line_width(1) color = randBackColorGen() # create color pdf.set_fill_color(*color) pdf.rect(-5, -5, 1000, 2000, "DF") inverseColor = getColorInverse(*color) pdf.set_text_color(*inverseColor) pdf.set_font("Arial", size=20) pdf.cell(200, 10, txt=keyword.title(), ln=1, align="C") dir = './downloads/' + keyword + adjunctKeyword offsetY = 0 try: im = Image.open(mbPaths[pageNumb]) width, height = im.size imgHeight = 40 pdf.image(mbPaths[pageNumb], x=random.randint(100, 150), y=60, w=imgHeight) offsetY = 70 + height * (imgHeight / width) except: offsetY = 70 offsetX = 20 for file in os.listdir(dir): path = os.path.join(dir, file) if file.endswith(".jpg"): try: im = Image.open(path) width, height = im.size pdf.image(path, x=offsetX, y=offsetY, w=100) offsetY += 20 + height * (100 / width) except: print("error with jpg file shtuff") elif file.endswith(".png"): # todo put back in on refresh im = Image.open(path) rgb_im = im.convert('RGB') width, height = im.size rgb_im.save(path + '.jpg') pdf.image(path + '.jpg', x=offsetX, y=offsetY, w=100) offsetY += 20 + height * (100 / width) offsetX += 20 pdf.set_font("Arial", size=12) for txtSnip in txts[pageNumb]: pdf.cell(200, 13, txt=txtSnip, ln=1, align="L") pdf.ln(1) pageNumb += 1 pdf.output("simple_demo.pdf")
def test_local_context_shared_props(tmp_path): "Test local_context() with settings that are controlled by both GraphicsStateMixin and drawing.GraphicsStyle" pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", "", 12) with pdf.local_context( draw_color=(0, 128, 255), fill_color=(255, 128, 0), line_width=2, dash_pattern=dict(dash=0.5, gap=9.5, phase=3.25), ): pdf.rect(x=60, y=60, w=60, h=60, style="DF") pdf.rect(x=60, y=150, w=60, h=60, style="DF") assert_pdf_equal(pdf, HERE / "local_context_shared_props.pdf", tmp_path)
def generate_mail(doc_name,reg_no): exam_center,land_mark,maplink=mail.generate_hall(reg_no) name = doc_name reg_no = 1234455 datetime = '10-08-2020' exam_center = exam_center land_mark = land_mark maplink = maplink msg_header = f"""ADMIT CARD STATE TEACHERS ELIGIBILITY TEST - 2020 EXAMINATION Selection Committee Directrate of Education, Sikkim E-CALL FOT THE STET EXAMINATION - 2020 """ msg_body = [["Name of the candidate", name], ['Register Number', reg_no], ["Exam Date/Reporting Time", datetime], ["Exam Center", exam_center], ["Land Mark ", land_mark], ["Google Map link:", maplink]] msg_footer = f""" TO BE FILLED ON EXAMINATION Candidate's sign Invigilator's sign """ pdf = FPDF('P', 'mm',(250,240)) pdf.add_page() pdf.rect(x=5,y=5,w=(pdf.w)-10,h=(pdf.h)-10) pdf.rect(x=6, y=6, w=(pdf.w) - 12, h=(pdf.h) - 12) pdf.set_font('Times', size=12) epw = pdf.w - 2 * pdf.l_margin col_width = epw / 2 th = (pdf.font_size) + 5 pdf.image('sikkim_logo_2.jpg',w=40,h=30) for line in msg_header.split('\n'): pdf.cell(200, 10, txt=line, ln=1, align='C') for row in msg_body: for col in row: pdf.cell(col_width, th, str(col), border=1) \ pdf.ln(th) for line in msg_footer.split('\n'): pdf.cell(200, 10, txt=line, ln=1, align='C') file_name='admit_card_'+str(doc_name)+'.pdf' pdf.output(file_name) return file_name
def test_local_context_inherited_shared_props(tmp_path): "The only thing that should differ between the 2 squares is their opacity" pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", "", 12) pdf.set_draw_color(0, 128, 255) pdf.set_fill_color(255, 128, 0) pdf.set_line_width(2) pdf.set_dash_pattern(dash=0.5, gap=9.5, phase=3.25) with pdf.local_context( fill_opacity=0.5): # => triggers creation of a local GraphicsStyle pdf.rect(x=60, y=60, w=60, h=60, style="DF") pdf.rect(x=60, y=150, w=60, h=60, style="DF") assert_pdf_equal(pdf, HERE / "local_context_inherited_shared_props.pdf", tmp_path)
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)
def markirovka(): input_file = session['input_file'] places = session['places'] pile = session['pile'] perekladka_filename = 'perekladka_' + os.path.splitext( input_file)[0] + '_' + str(places) + 'x' + str(pile) + '.csv' do_perekladka(input_file, perekladka_filename) pdf_name = 'mark.pdf' # if pdf_name.ex # os.remove(pdf_name) pdf = FPDF('P', 'mm', [100, 60]) if os.getenv("FLASK_ENV") == 'production': font_path = '/app/static/DejaVuSans.ttf' encoding = 'utf-8' else: font_path = 'C:\\Windows\\Fonts\\DejaVuSans.ttf' encoding = 'windows-1251' pdf.add_font('DejaVuSans', '', font_path, uni=True) pdf.set_font('DejaVuSans', '', 12) pdf.set_auto_page_break(False, 0) with open(perekladka_filename, 'r', encoding=encoding) as f: reader = csv.DictReader(f) for row in reader: pdf.add_page() txt = '\n'.join([ row['order'], row['privertka'], row['pachka'], row['amount'], row['pers'] ]) # pdf.cell(0, 0, row['order'], ln=2) # pdf.cell(0, 0, row['privertka'], ln=2) # pdf.cell(0, 0, row['pachka'], ln=2) # pdf.cell(0, 0, row['amount'], ln=2) # pdf.cell(0, 0, row['pers'], ln=2) pdf.set_xy(20, 15) pdf.multi_cell(0, 5, txt, 0, 'L') pdf.rect(0.1, 0.1, 99.8, 59.9) pdf.output(pdf_name, 'F') return send_file(pdf_name, as_attachment=True, mimetype='application/pdf')
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')
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)
def generate_pdf(card, qrcode_enabled=True) -> str: """ Make a PDF from a card :param card: dict from fetcher.py :return: Binary PDF buffer """ from eclaire.base import SPECIAL_LABELS, MAX_LABEL_CHARS pdf = FPDF("L", "mm", (62, 140)) pdf.set_margins(2.8, 2.8, 2.8) pdf.set_auto_page_break(False, margin=0) pdf.add_page() font = pkg_resources.resource_filename("eclaire", "font/Clairifont.ttf") pdf.add_font("Clairifont", fname=font, uni=True) pdf.set_font("Clairifont", size=40) pdf.multi_cell(0, 18, txt=card.name.upper(), align="L") if qrcode_enabled: qrcode = generate_qr_code(card.shortUrl) qrcode_file = mktemp(suffix=".png", prefix="trello_qr_") qrcode.save(qrcode_file) pdf.image(qrcode_file, 118, 35, 20, 20) os.unlink(qrcode_file) # May we never speak of this again. pdf.set_fill_color(255, 255, 255) pdf.rect(0, 55, 140, 20, "F") pdf.set_font("Clairifont", "", 14) pdf.set_y(-4) labels = ", ".join([ label.name for label in card.labels if label.name not in SPECIAL_LABELS ])[:MAX_LABEL_CHARS] pdf.multi_cell(0, 0, labels, 0, "R") return pdf.output(dest="S").encode("latin-1")
def change_data_to_pdf(data): pdf = FPDF(orientation='L', unit='mm') # pdf = fpdf.FPDF('L', 'mm', format=(30, 10)) pdf = fpdf.FPDF(format='A4') pdf.add_page() pdf.set_font("Arial", size=12,) pdf.cell(150, 10, txt="Results Sheet", ln=1, align="C") # border styling pdf.set_line_width(1) pdf.set_fill_color(0, 255, 0) pdf.rect(2, 2, 205, 160) # excel cell data text = f""" Name: {data[1]} Father Name: {data[2]} subject Math: {data[3]} Chemistry: {data[4]} Biology: {data[5]} Geology: {data[6]} English: {data[7]} Average score: Final Result: """ # show excel data pdf.set_right_margin(444) pdf.multi_cell(150, 9, text, align='R') # adding Image pdf.image('images/1_jobs.jpeg', x=50, y=50, w=50) # pdf.cell(400, 40, txt="{}".format('images/Ahmad.jpeg'), ln=1) pdf.ln() pdf.output("File.pdf")
def generate_pdf(card): """ Make a PDF from a card :param card: dict from fetcher.py :return: Binary PDF buffer """ from eclaire.base import SPECIAL_LABELS pdf = FPDF('L', 'mm', (62, 140)) pdf.set_margins(2.8, 2.8, 2.8) pdf.set_auto_page_break(False, margin=0) pdf.add_page() font = pkg_resources.resource_filename('eclaire', 'font/Clairifont.ttf') pdf.add_font('Clairifont', fname=font, uni=True) pdf.set_font('Clairifont', size=48) pdf.multi_cell(0, 18, txt=card.name.upper(), align='L') qrcode = generate_qr_code(card.url) qrcode_file = mktemp(suffix='.png', prefix='trello_qr_') qrcode.save(qrcode_file) pdf.image(qrcode_file, 118, 35, 20, 20) os.unlink(qrcode_file) # May we never speak of this again. pdf.set_fill_color(255, 255, 255) pdf.rect(0, 55, 140, 20, 'F') pdf.set_font('Clairifont', '', 16) pdf.set_y(-4) labels = ', '.join([ label.name for label in card.labels if label.name not in SPECIAL_LABELS ]) pdf.multi_cell(0, 0, labels, 0, 'R') return pdf.output(dest='S')
def generate_pdf(card): """ Make a PDF from a card :param card: dict from fetcher.py :return: Binary PDF buffer """ from eclaire.base import SPECIAL_LABELS pdf = FPDF('L', 'mm', (62, 140)) pdf.set_margins(2.8, 2.8, 2.8) pdf.set_auto_page_break(False, margin=0) pdf.add_page() font = pkg_resources.resource_filename('eclaire', 'font/Clairifont.ttf') pdf.add_font('Clairifont', fname=font, uni=True) pdf.set_font('Clairifont', size=48) pdf.multi_cell(0, 18, txt=card.name.upper(), align='L') qrcode = generate_qr_code(card.url) qrcode_file = mktemp(suffix='.png', prefix='trello_qr_') qrcode.save(qrcode_file) pdf.image(qrcode_file, 118, 35, 20, 20) os.unlink(qrcode_file) # May we never speak of this again. pdf.set_fill_color(255, 255, 255) pdf.rect(0, 55, 140, 20, 'F') pdf.set_font('Clairifont', '', 16) pdf.set_y(-4) labels = ', '.join([label.name for label in card.labels if label.name not in SPECIAL_LABELS]) pdf.multi_cell(0, 0, labels, 0, 'R') return pdf.output(dest='S')
class Report: def __init__(self, data): """Initialize the Report object.""" self.pdf = FPDF("P", "mm", "A4") self.id = data["id"] self.data = data def render(self): self.pdf.add_page() self.draw_shapes() self.draw_title() self.draw_heading() self.draw_inventory() return self.pdf.output("report_%s.pdf" % self.data["id"]) def draw_shapes(self): """Draw the report edge.""" self.pdf.set_line_width(4) self.pdf.rect(10, 10, 190, 277) self.pdf.set_line_width(2) self.pdf.rect(15, 15, 180, 267) self.pdf.set_draw_color(192, 192, 192) self.pdf.set_line_width(1) self.pdf.rect(16, 16, 178, 265) def draw_inventory(self): """Draw the inventory paragraph the report.""" self.pdf.set_y(100) self.pdf.set_font("Arial", "", 18) self.pdf.cell(170, 7, "Inventory", 0, ln=2, align="C") self.pdf.set_font("Arial", "", 12) for inventory in self.data["inventory"]: text = "%s: %s" % (inventory["name"], inventory["price"]) self.pdf.cell(150, 7, text, 0, ln=2, align="C") def draw_title(self): """Draw the report title.""" title = self.data["organization"] + " report" self.pdf.set_font("Arial", "B", 20) w = self.pdf.get_string_width(title) x = 210 - w / 2 self.pdf.cell(x, 50, title, 0, 1, "C") def draw_heading(self): """Draw the report heading.""" self.pdf.set_font("Arial", "", 12) self.pdf.set_x(0) org_text = "Organization: %s " % self.data["organization"] self.pdf.cell(170, 7, org_text, 0, ln=2, align="R") reported_text = "Reported: %s " % self.data["reported_at"] self.pdf.cell(170, 7, reported_text, 0, ln=2, align="R") created_text = "Created: %s " % self.data["created_at"] self.pdf.cell(170, 7, created_text, 0, ln=2, align="R")
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')
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)
def MakePDFMonthCal (year, month, calParams, outputFile): startMonth = 1 endMonth = 12 # Create a calendar instance if (calParams ['FirstDay'] == SUNDAY): cal = calendar.Calendar (calendar.SUNDAY) else: cal = calendar.Calendar (calendar.MONDAY) pdfFile = FPDF (orientation=calParams['PageOrientation'], unit='in', format='letter') pdfFile.add_page() pdfFile.set_left_margin (calParams['PageXOrigin']) pdfFile.set_top_margin (calParams['PageYOrigin']) calXOffset = 0 calYOffset = 0 calMonth = month fontStyle = '' if (calParams['FontBold'] == True): fontStyle += 'b' if (calParams['FontItalic'] == True): fontStyle += 'i' calHeight = calParams['PageHeight'] calWidth = calParams['PageWidth'] numCols = 1 numRows = 1 if (month == -1): pdfFile.set_draw_color (calParams['DebugColourR'], calParams['DebugColourG'], calParams['DebugColourB']) pdfFile.set_line_width (calParams['DebugLineThickness']) pdfFile.set_xy (calParams['PageXOrigin'], calParams['PageYOrigin']) pdfFile.set_font (calParams['Font'], style=fontStyle, size=INCH_TO_POINT*calParams['YearHeader']) pdfFile.set_text_color (calParams['FontColourR'], calParams['FontColourG'], calParams['FontColourB']) pdfFile.cell (calWidth-calParams['YearGridSpacing'], calParams['YearHeader'], txt=str(year), border=calParams['Debug'], align='C') calParams['PageYOrigin'] += (calParams['YearHeader'] + calParams['YearHeaderSpace']) if (calParams['PageOrientation'] == PORTRAIT): calHeight = (calParams['PageHeight'] - calParams['YearHeader'] - calParams['YearHeaderSpace']) / YEAR_MONTH_ROWS_PORT calWidth = calParams['PageWidth'] / YEAR_MONTH_COLS_PORT numCols = YEAR_MONTH_COLS_PORT numRows = YEAR_MONTH_ROWS_PORT else: calHeight = (calParams['PageHeight'] - calParams['YearHeader'] - calParams['YearHeaderSpace']) / YEAR_MONTH_ROWS_LAND calWidth = calParams['PageWidth'] / YEAR_MONTH_COLS_LAND numCols = YEAR_MONTH_COLS_LAND numRows = YEAR_MONTH_ROWS_LAND calHeight -= calParams['YearGridSpacing'] calWidth -= calParams['YearGridSpacing'] else: startMonth = month endMonth = month for calMonth in range (startMonth, endMonth+1): if (calParams['Debug']): pdfFile.set_draw_color (calParams['DebugColourR'], calParams['DebugColourG'], calParams['DebugColourB']) pdfFile.set_line_width (calParams['DebugLineThickness']) pdfFile.rect (calParams['PageXOrigin'] + calXOffset, calParams['PageYOrigin'] + calYOffset, calWidth, calHeight) # # Make title... # pdfFile.set_text_color (calParams['FontColourR'], calParams['FontColourG'], calParams['FontColourB']) if (calParams['TitleStyle'] == 1): pdfFile.set_xy (calParams['PageXOrigin'] + calXOffset, calParams['PageYOrigin'] + calYOffset) pdfFile.set_font (calParams['Font'], style=fontStyle, size=INCH_TO_POINT*calParams['BlockMonthTitleHeight']*calHeight) pdfFile.cell (calWidth, \ calParams['BlockMonthTitleHeight']*calHeight, \ txt=calendar.month_name[calMonth], \ border=calParams['Debug'], align='C') elif (calParams['TitleStyle'] == 2): pdfFile.set_font (calParams['Font'], style=fontStyle, size=INCH_TO_POINT*calParams['BlockMonthTitleHeight']*calHeight) monthFontWidth = pdfFile.get_string_width (calendar.month_name[calMonth]) yearFontWidth = pdfFile.get_string_width (str(year)) pdfFile.set_xy (calParams['PageXOrigin'] + calXOffset, calParams['PageYOrigin'] + calYOffset) pdfFile.cell (monthFontWidth, calParams['BlockMonthTitleHeight']*calHeight + calYOffset,\ txt=calendar.month_name[calMonth], border=calParams['Debug'], align='L') pdfFile.set_xy (calParams['PageXOrigin'] + calXOffset + calWidth - yearFontWidth, calParams['PageYOrigin'] + calYOffset) pdfFile.cell (yearFontWidth, calParams['BlockMonthTitleHeight']*calHeight + calYOffset,\ txt=str(year), border=calParams['Debug'], align='R') # # Weekday titles... # dayIndices = list ( range (0, NUMBER_WEEKDAYS) ) if (calParams ['FirstDay'] == SUNDAY): dayIndices.insert (0, NUMBER_WEEKDAYS-1) dayIndices.pop () fontScaleFactor, fontMaxWidth, fontMaxSize = FindMaxFontHeight (calParams['Font'], fontStyle, \ calParams['BlockDayTitleHeight'] * calHeight, \ calWidth/NUMBER_WEEKDAYS, \ MAX_WEEKDAY_STR) for day in range (0, NUMBER_WEEKDAYS): pdfFile.set_xy (calParams['PageXOrigin'] + calXOffset + calWidth * day / NUMBER_WEEKDAYS, \ calParams['PageYOrigin'] + calYOffset + (calParams['BlockMonthTitleHeight'] + calParams['BlockTitleSpace']) * calHeight) pdfFile.set_font (calParams['Font'], style=fontStyle, size=fontScaleFactor*calParams['BlockDayTitleHeight']*calHeight) if (calParams['DayTitleStyle'] == 1): pdfFile.cell (calWidth / NUMBER_WEEKDAYS, calParams['BlockDayTitleHeight'] * calHeight, \ txt=calendar.day_name[dayIndices[day]], border=calParams['Debug'], align='C') elif (calParams['DayTitleStyle'] == 2): pdfFile.cell (calWidth / NUMBER_WEEKDAYS, calParams['BlockDayTitleHeight'] * calHeight, \ txt=calendar.day_name[dayIndices[day]], border=calParams['Debug'], align='L') # Horizontal Lines if (calParams['HorizontalLines'] == True): pdfFile.set_line_width (calParams['HorizontalLineThickness']) pdfFile.set_draw_color (calParams['HorizontalLineColourR'], calParams['HorizontalLineColourG'], calParams['HorizontalLineColourB']) HorizontalLineAmount = calParams['HorizontalLineSpacing'] * GRID_ROWS for row in range (0, HorizontalLineAmount + 1): lineXStart = calParams['PageXOrigin'] + calXOffset lineXEnd = calParams['PageXOrigin'] + calXOffset + calWidth lineYStart = calParams['PageYOrigin'] + calYOffset + calHeight \ - (row / HorizontalLineAmount) * calParams['BlockDayRegionHeight'] * calHeight lineYEnd = lineYStart pdfFile.line (lineXStart, lineYStart, lineXEnd, lineYEnd) # boxes... if (calParams['DayGridStyle'] == 4): pdfFile.set_line_width (calParams['GridLineThickness']) pdfFile.set_draw_color (calParams['DayRegionColourR'], calParams['DayRegionColourG'], calParams['DayRegionColourB']) gridOffset = calParams['DayGridSpacing'] for col in range (0, NUMBER_WEEKDAYS): for row in range (0, GRID_ROWS): boxXStart = calParams['PageXOrigin'] + calXOffset + (col / NUMBER_WEEKDAYS) * calWidth + gridOffset boxXEnd = calWidth / NUMBER_WEEKDAYS - 2*gridOffset boxYStart = calParams['PageYOrigin'] + calYOffset + (1 - calParams['BlockDayRegionHeight']) * calHeight \ + calParams['BlockDayRegionHeight'] * calHeight * row / GRID_ROWS + gridOffset boxYEnd = calParams['BlockDayRegionHeight'] * calHeight / GRID_ROWS - 2*gridOffset drawStyle = 'D' if (calParams['DayGridInvert'] == True): pdfFile.set_fill_color (calParams['FontColourR'], calParams['FontColourG'], calParams['FontColourB']) drawStyle = 'F' pdfFile.rect (boxXStart, boxYStart, boxXEnd, boxYEnd, style=drawStyle) # circles if (calParams['DayGridStyle'] == 5 or calParams['DayGridStyle'] == 6): pdfFile.set_line_width (calParams['GridLineThickness']) pdfFile.set_draw_color (calParams['DayRegionColourR'], calParams['DayRegionColourG'], calParams['DayRegionColourB']) gridOffset = calParams['DayGridSpacing'] for col in range (0, NUMBER_WEEKDAYS): for row in range (0, GRID_ROWS): boxXStart = calParams['PageXOrigin'] + calXOffset + (col / NUMBER_WEEKDAYS) * calWidth + gridOffset boxXEnd = calWidth / NUMBER_WEEKDAYS - 2*gridOffset boxYStart = calParams['PageYOrigin'] + calYOffset + (1 - calParams['BlockDayRegionHeight']) * calHeight \ + calParams['BlockDayRegionHeight'] * calHeight * row / GRID_ROWS + gridOffset boxYEnd = calParams['BlockDayRegionHeight'] * calHeight / GRID_ROWS - 2*gridOffset dX = boxXEnd dY = boxYEnd minBoxXStart = maxBoxXStart = boxXStart minBoxXEnd = maxBoxXEnd = boxXEnd minBoxYStart = maxBoxYStart = boxYStart minBoxYEnd = maxBoxYEnd = boxYEnd if (dX < dY): offset = (dY - dX) / 2 minBoxYStart += offset minBoxYEnd -= (2*offset) maxBoxXStart -= offset maxBoxXEnd += offset else: offset = (dX - dY) / 2 minBoxXStart += offset minBoxXEnd -= (2*offset) maxBoxYStart -= offset maxBoxYEnd += (2*offset) drawStyle = 'D' if (calParams['DayGridInvert'] == True): pdfFile.set_fill_color (calParams['FontColourR'], calParams['FontColourG'], calParams['FontColourB']) drawStyle = 'F' pdfFile.ellipse (minBoxXStart, minBoxYStart, minBoxXEnd, minBoxYEnd, style=drawStyle) if (calParams['DayGridStyle'] == 6): pdfFile.ellipse (boxXStart, boxYStart, boxXEnd, boxYEnd) ## ## numbers ## if (calParams['Debug']): pdfFile.set_draw_color (calParams['DebugColourR'], calParams['DebugColourG'], calParams['DebugColourB']) pdfFile.set_line_width (calParams['DebugLineThickness']) fontScaleFactor, fontMaxWidth, fontMaxSize = FindMaxFontHeight (calParams['Font'], fontStyle, \ calParams['BlockDayRegionHeight'] * calHeight / GRID_ROWS, \ calParams['DayFontScale'] * calWidth / NUMBER_WEEKDAYS, MAX_NUMBER_STR) gridOffset = 0 if (calParams['DayNumPlacement'] == 2): gridOffset += max (calParams['DayCornerOffset'] * calWidth / NUMBER_WEEKDAYS, \ calParams['DayCornerOffset'] * calParams['BlockDayRegionHeight'] * calHeight / GRID_ROWS) if (calParams['DayGridStyle'] == 4): gridOffset += calParams['DayGridSpacing'] if (calParams['DayGridInvert'] == True): pdfFile.set_text_color (255, 255, 255) else: pdfFile.set_text_color (calParams['FontColourR'], calParams['FontColourG'], calParams['FontColourB']) # iterate over all the days in the month col = 0 row = 0 for i in cal.itermonthdays (year, calMonth): # if it is a day within the month, not from the previous or next month then display it if (i != 0): # Central placement if (calParams['DayNumPlacement'] == 1): numberXLoc = calParams['PageXOrigin'] + calXOffset + col / NUMBER_WEEKDAYS * calWidth numberYLoc = calParams['PageYOrigin'] + calYOffset + (1 - calParams['BlockDayRegionHeight']) * calHeight \ + (row / GRID_ROWS) * calParams['BlockDayRegionHeight'] * calHeight \ + calParams['BlockDayRegionHeight'] * calHeight / (2 * GRID_ROWS) \ + gridOffset pdfFile.set_xy (numberXLoc, numberYLoc) pdfFile.set_font (calParams['Font'], style=fontStyle, size=fontScaleFactor*calParams['BlockDayRegionHeight'] * calHeight / GRID_ROWS) pdfFile.cell (calWidth/NUMBER_WEEKDAYS, 0, txt=str(i), align='C', border=calParams['Debug']) # Corner placement elif (calParams['DayNumPlacement'] == 2): numberXLoc = calParams['PageXOrigin'] + calXOffset + col / NUMBER_WEEKDAYS * calWidth numberYLoc = calParams['PageYOrigin'] + calYOffset + (1 - calParams['BlockDayRegionHeight']) * calHeight \ + (row / GRID_ROWS) * calParams['BlockDayRegionHeight'] * calHeight if (calParams['HorizontalLines'] == True): pdfFile.set_fill_color (255, 255, 255) pdfFile.rect (numberXLoc, numberYLoc, fontMaxWidth + 3*gridOffset, fontMaxSize / INCH_TO_POINT + 3*gridOffset, style='F') numberXLoc += gridOffset numberYLoc += gridOffset pdfFile.set_xy (numberXLoc, numberYLoc) pdfFile.set_font (calParams['Font'], style=fontStyle, size=fontScaleFactor*calParams['BlockDayRegionHeight'] * calHeight / GRID_ROWS) pdfFile.cell (fontMaxWidth, fontMaxSize / INCH_TO_POINT, txt=str(i), align='L', border=calParams['Debug']) col += 1 if (col % 7 == 0): col = 0 row += 1 if (calParams['Debug']): pdfFile.set_draw_color (calParams['DayRegionColourR'], calParams['DayRegionColourG'], calParams['DayRegionColourB']) pdfFile.set_line_width (calParams['GridLineThickness']) ## ## grid ## pdfFile.set_draw_color (calParams['DayRegionColourR'], calParams['DayRegionColourG'], calParams['DayRegionColourB']) pdfFile.set_line_width (calParams['GridLineThickness']) # horizontal grid lines if (calParams['DayGridStyle'] == 1 or calParams['DayGridStyle'] == 2): for row in range (0, GRID_ROWS+1): lineXStart = calParams['PageXOrigin'] + calXOffset lineXEnd = calParams['PageXOrigin'] + calXOffset + calWidth lineYStart = calParams['PageYOrigin'] + calYOffset + calHeight - (row / GRID_ROWS) * calParams['BlockDayRegionHeight'] * calHeight lineYEnd = lineYStart pdfFile.line (lineXStart, lineYStart, lineXEnd, lineYEnd) # vertical grid lines if (calParams['DayGridStyle'] == 1 or calParams['DayGridStyle'] == 3): for day in range (0, NUMBER_WEEKDAYS+1): lineXStart = calParams['PageXOrigin'] + calXOffset + calWidth - (day / NUMBER_WEEKDAYS) * calWidth lineXEnd = lineXStart lineYStart = calParams['PageYOrigin'] + calYOffset + (1 - calParams['BlockDayRegionHeight']) * calHeight lineYEnd = calParams['PageYOrigin'] + calYOffset + calHeight pdfFile.line (lineXStart, lineYStart, lineXEnd, lineYEnd) if (calMonth % numCols == 0): calXOffset = 0 calYOffset += (calHeight + calParams['YearGridSpacing']) else: calXOffset += calWidth calXOffset += calParams['YearGridSpacing'] pdfFile.output (outputFile) return 0
def retrospective(request): context = {} if request.method == 'POST': template = loader.get_template( 'RainyDaysHero/rain-insurance/retrospectiveAnswer-onSide.html') form = RetroForm(request.POST) if form.is_valid(): context['form'] = form #compute retrospective premium, covered, notcovered, c, nc, cm, ncm = computeRetro( form['location'].value(), form['subscriptionDate'].value(), form['rainfall'].value(), form['dailyMaxTurnover'].value(), form['fixedCosts'].value()) context['price'] = str(premium) context['c'] = str(covered) context['nc'] = str(notcovered) context['cm'] = str(list(cm.values())) context['ncm'] = str(list(ncm.values())) print(str(list(cm.values()))) print(str(list(ncm.values()))) pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.add_page() pdf.rect(5.0, 5.0, 200.0, 287.0) pdf.rect(8.0, 8.0, 194.0, 282.0) #App pic #pdf.image(static('RainyDaysHero/images/rdh.png'), 10, 8, 33) dirname = os.path.dirname( os.path.dirname(os.path.dirname(__file__))) pdf.image( os.path.join(dirname, 'static/RainyDaysHero/images/rdh.png'), 10, 8, 33) pdf.set_font('Arial', 'B', 15) # Client Name pdf.cell(140) pdf.cell(0, 5, str(form['clientName'].value()), ln=1) #Company name pdf.ln(25) pdf.cell(0, 5, 'Rainy Days Hero', ln=1) #Informatios pdf.set_text_color(238, 58, 20) pdf.ln(6) pdf.cell(60) pdf.cell(65, 10, 'Rain Insurance quotation', 'B', ln=2) pdf.set_text_color(0, 0, 0) pdf.set_font('Arial', 'B', 10) pdf.cell(65, 10, "Max daily turover: " + str(form['dailyMaxTurnover'].value()), ln=2) pdf.cell(65, 10, "Fixed costs: " + str(form['fixedCosts'].value()), ln=2) pdf.cell(65, 10, "Crucial rainfall: " + str(form['rainfall'].value()), ln=2) pdf.cell(65, 10, "Subsciption date: " + form['subscriptionDate'].value(), ln=2) #pdf.cell(65, 10, "Subsciption date: "+form['subscriptionDate'].value().strftime("%Y-%m-%d"), ln=2) pdf.cell(65, 10, "Duration: " + "365 days", ln=2) pdf.cell(65, 10, "Location: " + form['location'].value(), ln=2) #premium pdf.set_text_color(39, 174, 96) pdf.ln(10) pdf.cell(60) pdf.set_font('Arial', 'B', 15) pdf.cell(65, 10, "Premium Price: " + premium + " " + chr(128), ln=2) pdf.cell(65, 10, "Covered Result: " + covered + " " + chr(128), ln=2) pdf.cell(65, 10, "Uncovered Result: " + notcovered + " " + chr(128), ln=2) #graph days ''' days = [i for i in range(365)] plt.plot(days,c,label="Covered") plt.plot(days,nc,label="Uncovered") ''' #graph months months = [i for i in range(1, 13)] months_c = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] plt.xticks(rotation=45, ha='right') plt.xlabel('Months') plt.ylabel('Results') plt.plot(months_c, cm.values(), label="Covered") plt.plot(months_c, ncm.values(), label="Uncovered") #plot graph plt.title("Result Evolution Graph", fontweight="bold", fontsize=16, color="blue") plt.tight_layout() #plt.legend(loc='best') #lgd = plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),fancybox=True, shadow=True, ncol=5) lgd = plt.legend(title='Caption', bbox_to_anchor=(1.05, 1), loc='upper left') retroFIG = ''.join(choice(ascii_uppercase) for i in range(100)) + '.png' plt.savefig(retroFIG, bbox_extra_artists=(lgd, ), bbox_inches='tight') pdf.image(retroFIG, 45, 170, 120) #delete the fig os.remove(retroFIG) plt.close() #save file and del after response quotationPDFFile = ''.join( choice(ascii_uppercase) for i in range(100)) + '.pdf' pdf.output(quotationPDFFile, 'F') response = HttpResponse(pdf, content_type='application/pdf') response[ 'Content-Disposition'] = "attachment; filename=quotationPDFFile" removequotationfile.after_response(quotationPDFFile) #response.write(open("tuto.pdf")) if form['printPDF'].value() == 'Yes': return FileResponse(open(quotationPDFFile, "rb"), as_attachment=True, filename='retrospective.pdf') else: return HttpResponse(template.render(context, request)) else: template = loader.get_template( 'RainyDaysHero/rain-insurance/retrospective.html') form = RetroForm(request.POST) context = dict(form=form) return HttpResponse(template.render(context, request))
def PureEndowment(request): context = {} if request.method == 'GET': template = loader.get_template( 'RainyDaysHero/life-insurance/PE/pe.html') form = PureEndowmentForm(request.POST) context = dict(form=form) return HttpResponse(template.render(context, request)) else: template = loader.get_template( 'RainyDaysHero/life-insurance/PE/peAnswer.html') form = PureEndowmentForm(request.POST) if form.is_valid(): context['form'] = form #compute price x, m, n, i, a, mdl = form['clientAge'].value( ), form['numberOfPayements'].value(), form['maturity'].value( ), form['interestRate'].value(), form['amount'].value( ), form['model'].value() premium = predictPEPremiumLive(x, n, m, i, a, mdl) context['price'] = premium context['actuarial_price'] = premiumComputation.PEAnnual( int(x), int(m), int(n), float(i) / 100, float(a)) if form['printPDF'].value() == 'Yes': pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.add_page() pdf.rect(5.0, 5.0, 200.0, 287.0) pdf.rect(8.0, 8.0, 194.0, 282.0) # App pic # pdf.image(static('RainyDaysHero/images/rdh.png'), 10, 8, 33) dirname = os.path.dirname( os.path.dirname(os.path.dirname(__file__))) pdf.image( os.path.join(dirname, 'static/RainyDaysHero/images/rdh.png'), 10, 8, 33) pdf.set_font('Arial', 'B', 15) # Client Name pdf.cell(140) pdf.cell(0, 5, str(form['clientName'].value()), ln=1) # Company name pdf.ln(25) pdf.cell(0, 5, 'Rainy Days Hero', ln=1) # Informations pdf.set_text_color(238, 58, 20) pdf.ln(6) pdf.cell(60) pdf.cell(65, 10, 'Life Insurance quotation', 'B', ln=2) pdf.set_text_color(0, 0, 0) pdf.set_font('Arial', 'B', 10) pdf.cell(65, 10, "Product: Pure Endowment", ln=2) pdf.cell(65, 10, "Age: " + str(form['clientAge'].value()), ln=2) pdf.cell(65, 10, "Maturity: " + str(form['maturity'].value()), ln=2) pdf.cell(65, 10, "Number of payements: " + str(form['numberOfPayements'].value()), ln=2) pdf.cell(65, 10, "Interest rate: " + form['interestRate'].value() + "%", ln=2) pdf.cell(65, 10, "Amount: " + form['amount'].value(), ln=2) pdf.set_text_color(39, 174, 96) pdf.ln(25) pdf.cell(60) pdf.set_font('Arial', 'B', 15) pdf.cell(65, 10, "Premium: " + premium + " " + chr(128), ln=2) # save file and del after response quotationPDFFile = ''.join( choice(ascii_uppercase) for i in range(100)) + '.pdf' pdf.output(quotationPDFFile, 'F') response = HttpResponse(pdf, content_type='application/pdf') response[ 'Content-Disposition'] = "attachment; filename=quotationPDFFile" removequotationfile.after_response(quotationPDFFile) return FileResponse(open(quotationPDFFile, "rb"), as_attachment=True, filename='quotation.pdf') else: return HttpResponse(template.render(context, request))
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)
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 = None _unavalible_fonts = None design_mode = None _actual_data_line = None _no_print_footer = False _actual_section_size = None increase_section_size = None last_detail = False actual_data_level = None last_data_processed = None prev_level = None draws_at_header = None detailn = None name_ = None _actual_append_page_no = None reset_page_count = None def __init__(self): self.logger = logging.getLogger("kut2fpdf") checkDependencies({"fpdf": "pyfpdf"}) from pineboolib.plugins.kugar.parsertools import parsertools self._parser_tools = parsertools() self._avalible_fonts = [] self._unavalible_fonts = [] self.design_mode = FLSettings().readBoolEntry("ebcomportamiento/kugar_debug_mode") self._actual_data_line = None self._no_print_footer = False self.increase_section_size = 0 self.actual_data_level = 0 self.prev_level = -1 self.draws_at_header = {} self.detailn = {} self.name_ = None self._actual_append_page_no = 0 self.reset_page_count = False self.new_page = False """ 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, report = None, flags = []): 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.name_ = name self.setPageFormat(self._xml) # self._page_orientation = # self._page_size = if report is None: from fpdf import FPDF self._actual_append_page_no = -1 self._document = FPDF(self._page_orientation, "pt", self._page_size) for f in self._document.core_fonts: self.logger.debug("KUT2FPDF :: Adding font %s", f) self._avalible_fonts.append(f) else: self._document = report # Seteamos rutas a carpetas con tipos de letra ... # Cargamos las fuentes disponibles next_page_break = (flags[2] == 1) if len(flags) == 3 else True page_append = (flags[1] == 1) if len(flags) > 1 else False page_display = (flags[0] == 1) if len(flags) > 0 else False if page_append: self.prev_level = -1 self.last_detail = False page_break = False if self.new_page: page_break = True self.new_page = False if self.reset_page_count: self.reset_page_no() self.reset_page_count = False if self.design_mode: print("Append", page_append) print("Display", page_display) print("Page break", next_page_break) if next_page_break: self.reset_page_count = True if page_display: self.new_page = True self.processDetails(not page_break) #FIXME:Alguno valores no se encuentran for p in self._document.pages.keys(): page_content = self._document.pages[p]["content"] for h in self.draws_at_header.keys(): page_content = page_content.replace(h, str(self.draws_at_header[h])) self._document.pages[p]["content"] = page_content #print(self.draws_at_header.keys()) self._document.set_title(self.name_) self._document.set_author("Pineboo - kut2fpdf plugin") return self._document def get_file_name(self): import os pdf_name = aqApp.tmp_dir() pdf_name += "/%s_%s.pdf" % (self.name_, datetime.datetime.now().strftime("%Y%m%d%H%M%S")) if os.path.exists(pdf_name): os.remove(pdf_name) if self._document is not None: self._document.output(pdf_name, 'F') return pdf_name else: return None """ 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._actual_section_size = value - self.topSection() self._page_top[str(self._document.page_no())] = value """ Añade una nueva página al documento. """ def newPage(self, data_level, add_on_header = True): 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 self._no_print_footer = False if self.design_mode: self.draw_margins() self._actual_section_size = 0 self._actual_append_page_no += 1 if self.design_mode: print("Nueva página", self.number_pages()) #l_ini = data_level #l_end = self.prev_level #if l_ini == l_end: # l_end = l_end + 1 #if l_ini <= l_end: # for l in range(l_ini , l_end): # print(l) # self.processSection("AddOnHeader", str(l)) pg_headers = self._xml.findall("PageHeader") for ph in pg_headers: if self.number_pages() == 0 or ph.get("PrintFrequency") == "1": ph_level = ph.get("Level") if ph.get("Level") is not None else None self.processSection("PageHeader", ph_level) break if add_on_header and not self.number_pages() == 0: for l in range(data_level + 1): self.processSection("AddOnHeader", str(l)) #Por ahora se omite detail header """ Procesa las secciones details con sus correspondientes detailHeader y detailFooter. """ def processDetails(self, keep_page = None): # Procesamos la cabecera si procede .. top_level = 0 level = 0 first_page_created = keep_page if keep_page is not None and self._document.page_no() > 0 else False rows_array = self._xml_data.findall("Row") for data in rows_array: self._actual_data_line = data level = int(data.get("level")) if level > top_level: top_level = level if not first_page_created: self.newPage(level) first_page_created = True if rows_array[len(rows_array) - 1] is data: self.last_detail = True if level < self.prev_level: for l in range(level + 1, self.prev_level + 1): self.processData("DetailFooter", self.last_data_processed, l) if not str(level) in self.detailn.keys(): self.detailn[str(level)] = 0 else: self.detailn[str(level)] += 1 if level > self.prev_level: self.processData("DetailHeader", data, level) self.processData("Detail", data, level) self.last_data_processed = data self.prev_level = level if not self._no_print_footer: for l in reversed(range(top_level + 1)): self.processData("DetailFooter", data, l) """ 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): self.actual_data_level = data_level listDF = self._xml.findall(section_name) data_size = len(listDF) for dF in listDF: draw_if = dF.get("DrawIf") show = True if draw_if: show = data.get(draw_if) if dF.get("Level") == str(data_level) and show not in ("None", "False"): if section_name in ("DetailHeader","Detail"): heightCalculated = self._parser_tools.getHeight(dF) + self.topSection() if section_name is "DetailHeader": for detail in self._xml.findall("Detail"): if detail.get("Level") == str(data_level): heightCalculated += self._parser_tools.getHeight(detail) for dFooter in self._xml.findall("DetailFooter"): if dFooter.get("Level") == str(data_level): heightCalculated += self._parser_tools.getHeight(dFooter) #for addFooter in self._xml.findall("AddOnFooter"): # if addFooter.get("Level") == str(data_level): # heightCalculated += self._parser_tools.getHeight(addFooter) 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._no_print_footer = True #Vemos el tope por abajo limit_bottom = self._document.h - self._parser_tools.getHeight(self._xml.get("AddOnFooter")) actual_size = self._parser_tools.getHeight(dF) + self.topSection() if (actual_size > limit_bottom + 2) or self.last_detail: # +2 se usa de margen extra self.processSection("AddOnFooter", str(data_level)) self.newPage(data_level) self.processXML(dF, data) if dF.get("NewPage") == "true" and not self.last_detail: self.newPage(data_level, False) break #Se ejecuta una sola instancia """ Procesa las secciones fuera de detail @param name. Nombre de la sección a procesar. """ def processSection(self, name, level=0): sec_list = self._xml.findall(name) sec_ = None for s in sec_list: if s.get("Level") == str(level) or s.get("Level") is None: sec_ = s if sec_ is not None: if sec_.get("PrintFrequency") == "1" or self._document.page_no() == 1 or name in ("AddOnHeader","AddOnFooter"): 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 data is None: data = self._actual_data_line if self.design_mode: print("Procesando", xml.tag, data.get("level")) size_updated = False if xml.tag == "DetailFooter": if xml.get("PlaceAtBottom") == "true": self.setTopSection(self._document.h - self._parser_tools.getHeight(xml)) size_updated = True if xml.tag == "PageFooter": fix_height = False self.fix_extra_size() #Sirve para actualizar la altura con lineas que se han partido porque son muy largas for label in xml.iter("Label"): self.processText(label, data, fix_height) for field in xml.iter("Field"): self.processText(field, data, fix_height) for special in xml.iter("Special"): self.processText(special, data, fix_height, xml.tag) for calculated in xml.iter("CalculatedField"): self.processText(calculated, data, fix_height, xml.tag) #Busco draw_at_header en DetailFooter y los meto también if xml.tag == "DetailHeader": detail_level = xml.get("Level") for df in self._xml.iter("DetailFooter"): if df.get("Level") == detail_level: for cf in df.iter("CalculatedField"): if cf.get("DrawAtHeader") == "true": header_name = "%s_header_%s_%s" % (self.detailn[detail_level], detail_level, cf.get("Field")) self.draws_at_header[header_name] = "" self.processText(cf, data, fix_height, xml.tag) for line in xml.iter("Line"): self.processLine(line, fix_height) if not size_updated: self.setTopSection(self.topSection() + self._parser_tools.getHeight(xml)) def fix_extra_size(self): if self.increase_section_size > 0: self.setTopSection(self.topSection() + self.increase_section_size) self.increase_section_size = 0 """ 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")) X1 = self.calculateWidth(X1, 0, False) X2 = self.calculateLeftStart(xml.get("X2")) X2 = self.calculateWidth(X2, 0, False) # 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.ratio_correction(Y1) Y2 = self._parser_tools.ratio_correction(Y2) self._document.set_line_width(width) self._document.set_draw_color(r, g, b) dash_length = 1 space_length = 1 if style == 2: dash_length = 20 space_length = 20 elif style == 3: dash_length = 10 space_length = 10 self._document.dashed_line(X1, Y1, X2, Y2, dash_length, space_length) #else: # 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): return self._parser_tools.ratio_correction(int(x)) + self._left_margin """ Comprueba si excedemos el margen derecho de la página actual @param x. Posición a comprobar. @return Valor corregido, si procede. """ def calculateWidth(self, width, pos_x, fix_ratio = True): width = int(width) if fix_ratio: width = self._parser_tools.ratio_correction(int(width)) ret_ = width limit = self._document.w - self._right_margin if pos_x + width > limit: ret_ = limit - pos_x return ret_ """ Procesa una etiqueta. Esta puede 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, section_name = None): is_image = False is_barcode = False text = xml.get("Text") borderColor = xml.get("BorderColor") field_name = xml.get("Field") # 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.ratio_correction(y) # Corrige la posición con respecto al kut original data_type = xml.get("DataType") if xml.tag == "Field" and data_row is not None: text = data_row.get(field_name) elif xml.tag == "Special": if text == "": if xml.get("Type") == "1": text = "PageNo" text = self._parser_tools.getSpecial( text, self._actual_append_page_no) calculation_type = xml.get("CalculationType") if calculation_type is not None and xml.tag != "Field": if calculation_type == "6": function_name = xml.get("FunctionName") try: nodo = self._parser_tools.convertToNode(data_row) from pineboolib.pncontrolsfactory import aqApp ret_ = aqApp.call(function_name, [nodo, field_name]) if ret_ is False: return else: text = str(ret_) except Exception: self.logger.exception( "KUT2FPDF:: Error llamando a function %s", function_name) return elif calculation_type == "1": text = self._parser_tools.calculate_sum(field_name, self.last_data_processed, self._xml_data, self.actual_data_level) elif calculation_type in ("5"): if data_row is None: data_row = self._xml_data[0] text = data_row.get(field_name) if data_type is not None: text = self._parser_tools.calculated(text, int(data_type), xml.get("Precision"), data_row) if data_type == "5": is_image = True elif data_type == "6": is_barcode = True if xml.get("BlankZero") == "1" and text is not None: res_ = re.findall(r'\d+', text) res_ = "".join(res_) if int(res_) == 0: return if text is not None and text.startswith(filedir("../tempdata")): is_image = True negValueColor = xml.get("NegValueColor") Currency = xml.get("Currency") commaSeparator = xml.get("CommaSeparator") dateFormat = xml.get("DateFormat") if is_image: self.draw_image(x, y, W, H, xml, text) elif is_barcode: self.draw_barcode(x, y, W, H, xml, text) else: level = data_row.get("level") if level and str(level) in self.detailn.keys(): val = "%s_header_%s_%s" % ( self.detailn[str(level)], level,field_name) if xml.get("DrawAtHeader") == "true" and level: if section_name == "DetailHeader": val = "" self.drawText(x, y, W, H, xml, val) print(level, section_name, val, text) if section_name == "DetailFooter" and xml.get("DrawAtHeader") == "true": self.draws_at_header[val] = text print("Añadiendo a", val, text, level) else: self.drawText(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 txt = self._parser_tools.restore_text(txt) resizeable = False if xml.get("ChangeHeight") == "1": resizeable = True height_resized = False orig_x = x orig_y = y orig_W = W orig_H = H # Corregimos margenes: x = self.calculateLeftStart(x) W = self.calculateWidth(W, x) #bg_color = xml.get("BackgroundColor").split(",") fg_color = self.get_color(xml.get("ForegroundColor")) self._document.set_text_color(fg_color[0], fg_color[1], fg_color[2]) #self._document.set_draw_color(255, 255, 255) #if xml.get("BorderStyle") == "1": # FIXME: Hay que ajustar los margenes #font_name, font_size, font_style font_style = "" font_size = int(xml.get("FontSize")) font_name_orig = xml.get("FontFamily").lower() if xml.get("FontFamily") is not None else "helvetica" font_name = font_name_orig font_w = xml.get("FontWeight") if font_w in (None, "50"): #Normal font_w = 100 elif int(font_w) >= 65: font_style += "B" font_w = 100 fontI = xml.get("FontItalic") fontU = xml.get("FontUnderlined") # FIXME: hay que ver si es así background_color = self.get_color(xml.get("BackgroundColor")) #if background_color != [255,255,255]: #Los textos que llevan fondo no blanco van en negrita # font_style += "B" if fontI == "1": font_style += "I" if fontU == "1": font_style += "U" font_full_name = "%s%s" % (font_name, font_style) if font_full_name not in self._avalible_fonts: font_found = self._parser_tools.find_font(font_full_name) if font_found: self.logger.warning("KUT2FPDF::Añadiendo el tipo de letra %s (%s)", font_full_name, font_found) self._document.add_font(font_full_name, "", font_found, True) self._avalible_fonts.append(font_full_name) else: if font_full_name not in self._unavalible_fonts: self.logger.warning("KUT2FPDF:: No se encuentra el tipo de letra %s. Sustituido por helvetica%s." %(font_full_name, font_style)) self._unavalible_fonts.append(font_full_name) font_name = "helvetica" if font_name is not font_name_orig and font_name_orig.lower().find("narrow") > -1: font_w = 85 self._document.set_font(font_name, font_style, font_size) self._document.set_stretching(font_w) # Corregir alineación VAlignment = xml.get("VAlignment") # 0 izquierda, 1 centrado,2 derecha HAlignment = xml.get("HAlignment") layout_direction = xml.get("layoutDirection") start_section_size = self._actual_section_size result_section_size = 0 #Miramos si el texto sobrepasa el ancho array_text = [] array_n = [] text_lines = [] if txt.find("\n") > -1: for t in txt.split("\n"): array_n.append(t) if array_n: #Hay saltos de lineas ... for n in array_n: text_lines.append(n) else: #No hay saltos de lineas text_lines.append(txt) for tl in text_lines: str_width = self._document.get_string_width(tl) if str_width > W + 2 and xml.tag !="Label" and resizeable: #Una linea es mas larga que el ancho del campo(Dejando 2 de juego) height_resized = True array_text = self.split_text(tl, W) else: array_text.append(tl) #calculated_h = orig_H * len(array_text) self.drawRect(orig_x, orig_y, orig_W, orig_H, xml) processed_lines = 0 extra_size = 0 for actual_text in array_text: if actual_text is None: continue processed_lines += 1 if processed_lines > 1: extra_size += font_size + 2 if HAlignment == "1": # sobre X # Centrado x = x + (W / 2) - (self._document.get_string_width(actual_text) / 2) #x = x + (W / 2) - (str_width if not height_resized else W / 2) elif HAlignment == "2": # Derecha x = x + W - self._document.get_string_width(actual_text) - 2 # -2 de margen #x = x + W - str_width if not height_resized else W else: # Izquierda x = x + 2 if VAlignment == "1": # sobre Y # Centrado #y = (y + ((H / 2) / processed_lines)) + (((self._document.font_size_pt / 2) / 2) * processed_lines) y = ( orig_y + ( orig_H / 2))+ ((self._document.font_size_pt / 2) /2) elif VAlignment == "2": # Abajo y = orig_y + orig_H - font_size else: # Arriba y = orig_y + font_size y = y + extra_size if self.design_mode: self.write_debug(self.calculateLeftStart(orig_x), y, "Hal:%s, Val:%s, T:%s st:%s" % (HAlignment, VAlignment, txt, font_w), 6, "green") if xml.tag == "CalculatedField": self.write_debug(self.calculateLeftStart(orig_x), y, "CalculatedField:%s, Field:%s" % (xml.get("FunctionName"), xml.get("Field")), 3, "blue") self._document.text(x, y, actual_text) result_section_size += start_section_size result_section_size = result_section_size - start_section_size if self.increase_section_size < extra_size: #Si algun incremento extra hay superior se respeta self.increase_section_size = extra_size def split_text(self, texto, limit_w): list_ = [] linea_ = None for t in texto.split(" "): if linea_ is None and t == "": continue if linea_ is not None: if self._document.get_string_width(linea_ + t) > limit_w: list_.append(linea_) linea_ = "" else: linea_ = "" linea_ += "%s " % t list_.append(linea_) return list_ """ 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 get_color(self, value): value = value.split(",") r = None g = None b = None if len(value) == 3: r = int(value[0]) g = int(value[1]) b = int(value[2]) else: r = int(value[0:2]) g = int(value[3:5]) b = int(value[6:8]) return [r,g,b] def drawRect(self, x, y, W, H, xml = None): style_ = "" border_color = None bg_color = None line_width = self._document.line_width border_width = 0.2 #Calculamos borde y restamos del ancho orig_x = x orig_y = y orig_w = W x = self.calculateLeftStart(orig_x) W = self.calculateWidth(W, x) if xml is not None and not self.design_mode: if xml.get("BorderStyle") == "1": border_color = self.get_color(xml.get("BorderColor")) self._document.set_draw_color(border_color[0], border_color[1], border_color[2]) style_ += "D" bg_color = self.get_color(xml.get("BackgroundColor")) self._document.set_fill_color(bg_color[0], bg_color[1], bg_color[2]) style_ = "F" + style_ border_width = int(xml.get("BorderWidth") if xml.get("BorderWidth") else 0.2) else: self.write_cords_debug(x,y,W,H, orig_x, orig_w) style_ = "D" self._document.set_draw_color(0, 0, 0) if style_ is not "": self._document.set_line_width(border_width) self._document.rect(x, y, W, H, style_) self._document.set_line_width(line_width) self._document.set_xy(orig_x, orig_y) #self._document.set_draw_color(255, 255, 255) #self._document.set_fill_color(0, 0, 0) def write_cords_debug(self, x, y, w, h, ox, ow): self.write_debug(x,y,"X:%s Y:%s W:%s H:%s orig_x:%s, orig_W:%s" % (round(x, 2),round(y, 2),round(w, 2),round(h, 2), round(ox, 2), round(ow, 2)), 2, "red") def write_debug(self, x,y,text, h, color = None): orig_color = self._document.text_color r = None g = None b = None current_font_family = self._document.font_family current_font_size = self._document.font_size_pt current_font_style = self._document.font_style if color is "red": r = 255 g = 0 b = 0 elif color is "green": r = 0 g = 255 b = 0 elif color is "blue": r = 0 g = 0 b = 255 self._document.set_text_color(r,g,b) self._document.set_font_size(4) self._document.text(x, y + h, text) self._document.text_color = orig_color #self._document.set_xy(orig_x, orig_y) self._document.set_font(current_font_family, current_font_style, current_font_size) """ 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 draw_image(self, x, y, W, H, xml, file_name): import os if not file_name.lower().endswith(".png"): file_name = self._parser_tools.parseKey(file_name) if file_name is not None and os.path.exists(file_name): x = self.calculateLeftStart(x) W = self.calculateWidth(W, x) self._document.image(file_name, x, y, W, H, "PNG") def draw_barcode(self, x, y, W, H, xml, text): if text == "None": return from pineboolib.fllegacy.flcodbar import FLCodBar file_name = aqApp.tmp_dir() file_name += "/%s.png" % (text) type = xml.get("CodBarType") if not os.path.exists(file_name): bar_code = FLCodBar(text) #Code128 if type is not None: type = bar_code.nameToType(type.lower()) bar_code.setType(type) pix = bar_code.pixmap() if not pix.isNull(): pix.save(file_name, "PNG") self.draw_image(x , y, W, H, xml, file_name) """ 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 def draw_margins(self): self.draw_debug_line(0 + self._left_margin , 0, 0+ self._left_margin , self._page_size[1]) #Vertical derecha self.draw_debug_line(self._page_size[0] - self._right_margin , 0, self._page_size[0] - self._right_margin , self._page_size[1])#Vertical izquierda self.draw_debug_line(0, 0 + self._top_margin, self._page_size[0], 0 + self._top_margin) #Horizontal superior self.draw_debug_line(0, self._page_size[1] - self._bottom_margin, self._page_size[0], self._page_size[1] - self._bottom_margin) #Horizontal inferior def draw_debug_line(self, X1, Y1, X2, Y2, title= None, color="GREY"): dash_length = 2 space_length = 2 r = 0 g = 0 b = 0 if color == "GREY": r = 220 g = 220 b = 220 self._document.set_line_width(1) self._document.set_draw_color(r, g, b) self._document.dashed_line(X1, Y1, X2, Y2, dash_length, space_length) def number_pages(self): return self._actual_append_page_no if self._actual_append_page_no > 0 else 0 def reset_page_no(self): self._actual_append_page_no = -1
pdf.set_fill_color(0, 0, 0) # Parse data strips = parse_strips(numbers) thickness = sum(strips) # Draw lines start = (float(config['papersize']['width']) - thickness) / 2 black = True y = 0 for th in strips: if (black): pdf.rect( x=0, y=start + y, w=float(config['papersize']['height']), h=th, style='F', ) y += th black = not (black) print(' ' + str(th), end='') # Add target name pdf.set_font('Helvetica', 'B', 8) pdf.text(x=20, y=start + y + 10, txt=name) # Add arrow, if neccessary if name == 'finish': pdf.text(x=17, y=start + y + 10, txt='^')
pdf.cell(95, 10, "C", 1, 0, 'C') # .set_draw_color(r,g,b) pdf.set_draw_color(198, 21, 21) # .set_line_width(size) in user defined unit pdf.set_line_width(1) pdf.cell(95, 10, "Python", 1, 0, 'C') pdf.set_draw_color(4, 139, 63) pdf.set_fill_color(4, 139, 63) pdf.line(10, 50, 200, 10) pdf.set_draw_color(4, 139, 63) pdf.set_fill_color(4, 139, 63) # .rect(x,y,w,h,style) pdf.rect(10, 60, 190, 10, 'DF') pdf.set_draw_color(198, 21, 21) pdf.set_fill_color(198, 21, 21) # use parameter as values for i in range(72, 157, 12): pdf.rect(10, i, 190, 10, 'DF') # .image for jpeg, png and gif images pdf.image('zamora.png', 10, 170, h=50, link='http://www.diputaciondezamora.es/') pdf.image('ironhacker.jpg', 100,
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
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
def make_pdf_report(fn, dfs, cfg, cfg_ssv, campus, debug, do_solo): """Master function for creating the pdf reports do_solo will be true if we want a single file per student""" # First create Class and process config settings local_cfg = {} for label, cfg_name in [ ("sort", "sort_students"), ("labels", "category_labels"), ]: if campus in cfg[cfg_name]: local_cfg[label] = cfg[cfg_name][campus] else: local_cfg[label] = cfg[cfg_name]["Standard"] labels = local_cfg["labels"] tgr_label = labels["TargetGR"] igr_label = labels["IdealGR"] for label, ssv_name in [ ("orient", "pdf_orientation"), ("c_header", "counselor_header"), ("p_header", "print_header"), ("p_footer", "print_footer"), ]: if campus in cfg_ssv[ssv_name]: local_cfg[label] = cfg_ssv[ssv_name][campus] else: local_cfg[label] = cfg_ssv[ssv_name]["Standard"] if campus in cfg_ssv["school_goals"]: school_goals = cfg_ssv["school_goals"][campus] goal_descriptions = cfg_ssv["goal_descriptions"] else: school_goals = None top_margin = cfg_ssv["pdf_margins"]["top"] left_margin = cfg_ssv["pdf_margins"]["left"] right_margin = cfg_ssv["pdf_margins"]["right"] thick_line = cfg_ssv["pdf_lines"]["thick"] line = cfg_ssv["pdf_lines"]["line"] goals_start = cfg_ssv["pdf_goals_start"] footer_start = cfg_ssv["pdf_footer_start"] college_max = cfg_ssv["pdf_college_max"] if not do_solo: pdf = FPDF(orientation=local_cfg["orient"], unit="in", format="Letter") for font_name, filename in cfg_ssv["pdf_fonts"].items(): pdf.add_font(font_name, "", filename, uni=True) pdf.set_line_width(line) pdf.set_margins(left=left_margin, top=top_margin, right=right_margin) else: create_folder_if_necessary(["Reports", campus]) filenames = [] # Get the student data and sort as appropriate df = dfs["roster"].copy() app_df = dfs["apps"].copy() # The sort string is pseudocode linking table columns surrounded by % with # ampersands and preceded by an equals to map to an Excel formula. The # next line reduces that to an ordered list of table names sort_order = [ x for x in local_cfg["sort"].split(sep="%") if x not in ["=", "&", ""] ] if debug: print("Sort order for PDF: {}".format(str(sort_order))) df.sort_values(by=sort_order, inplace=True) #################################### # start repeating here for each page for i, stu_data in df.iterrows(): if do_solo: student_fn = (campus + "_" + stu_data["LastFirst"].replace(" ", "_") + "_" + str(i) + date.today().strftime("_on_%m_%d_%Y") + ".pdf") pdf = FPDF(orientation=local_cfg["orient"], unit="in", format="Letter") for font_name, filename in cfg_ssv["pdf_fonts"].items(): pdf.add_font(font_name, "", filename, uni=True) pdf.set_line_width(line) pdf.set_margins(left=left_margin, top=top_margin, right=right_margin) pdf.add_page() pdf.set_y(top_margin) w = cfg_ssv["pdf_widths"] # list of cell widths in inches h = cfg_ssv["pdf_heights"] # list of cell heights in inches # The width of next two columns is variable based on header sizes # *First row name_text = ("College application odds report for " + stu_data["First"] + " " + stu_data["Last"]) c_text = _clean_excel(local_cfg["c_header"], stu_data, labels) pdf.set_font("font_b", "", 11) c_width = pdf.get_string_width(c_text) + 0.05 if local_cfg["p_header"]: # We're squeezing in one more entry, so stealing off the name # and the counselor header pdf.set_font("font_i", "", 11) p_text = _clean_excel(local_cfg["p_header"], stu_data, labels) p_width = pdf.get_string_width(p_text) + 0.05 n_width = sum(w) - p_width - c_width - 0.05 else: n_width = sum(w) - c_width - 0.05 pdf.set_font("font_b", "", 14) _shrink_cell( pdf=pdf, w=n_width, txt=name_text, h=h[0], border=0, ln=0, align="L", fill=False, ) if local_cfg["p_header"]: pdf.set_font("font_i", "", 11) _shrink_cell( pdf=pdf, w=p_width, txt=p_text, h=h[0], border=0, ln=0, align="L", fill=False, ) pdf.set_font("font_b", "", 11) _shrink_cell( pdf=pdf, w=c_width, txt=c_text, h=h[0], border=0, ln=1, align="L", fill=False, ) # *Second row _set_color_name(pdf, "light_blue") pdf.cell(w=w[0], txt="Student's name:", h=h[1], border=1, ln=0, align="L", fill=True) pdf.set_font("font_r", "", 11) pdf.cell(w=w[1], txt="ACT/SAT", h=h[1], border="B", ln=0, align="C", fill=True) pdf.cell(w=w[2], txt="GPA", h=h[1], border="B", ln=0, align="C", fill=True) pdf.cell(w=w[3], txt="Race/Eth", h=h[1], border=1, ln=0, align="C", fill=True) txt = igr_label[0] + "GR" pdf.cell(w=w[4], txt=txt, h=h[1], border="B", ln=0, align="C", fill=True) txt = _notnan(stu_data["local_ideal_gr"], "TBD", "{:2.0%}") pdf.cell(w=w[5], txt=txt, h=h[1], border="B", ln=1, align="C", fill=False) # *Third row _set_color_name(pdf, "salmon") pdf.cell( w=w[0], txt=stu_data["LastFirst"], h=h[2], border=1, ln=0, align="L", fill=True, ) txt = (_notnan(stu_data["ACT"], "TBD", "{:d}") + "/" + _notnan(stu_data["SAT"], "TBD", "{:d}")) pdf.cell(w=w[1], txt=txt, h=h[2], border=0, ln=0, align="C", fill=False) pdf.cell( w=w[2], txt=_notnan(stu_data["GPA"], "TBD", "{:4.2f}"), h=h[2], border=0, ln=0, align="C", fill=False, ) pdf.cell( w=w[3], txt=_notnan(stu_data["Race/ Eth"], "TBD", "{}"), h=h[2], border=1, ln=0, align="C", fill=False, ) _set_color_name(pdf, "light_blue") txt = tgr_label[0] + "GR" pdf.cell(w=w[4], txt=txt, h=h[2], border="T", ln=0, align="C", fill=True) txt = _notnan(stu_data["local_target_gr"], "TBD", "{:2.0%}") pdf.cell(w=w[5], txt=txt, h=h[2], border=0, ln=1, align="C", fill=False) # *Fourth row pdf.set_font("font_b", "", 11) pdf.cell( w=w[0], txt="Odds of 1 or more acceptances to:", h=h[3], border=0, ln=0, align="L", fill=True, ) txt = _notnan(stu_data["local_sat_max"], "TBD", "{:1.0f}") pdf.cell(w=w[1], txt=txt, h=h[3], border=0, ln=0, align="C", fill=True) pdf.cell(w=w[2], txt="", h=h[3], border=0, ln=0, align="C", fill=True) pdf.cell( w=sum(w[3:]), txt="Goals for #s to the left:", h=h[3], border=0, ln=1, align="L", fill=True, ) # *Fifth row pdf.set_font("font_r", "", 11) pdf.cell( w=sum(w[:2]), txt='"Money" ' + tgr_label + " grade rate (" + tgr_label[0] + "GR) or better schools", h=h[4], border=0, ln=0, align="L", fill=False, ) txt = _notnan(stu_data["local_oneplus_mtgr"], "TBD", "{:3.0%}") pdf.cell(w=w[2], txt=txt, h=h[4], border=0, ln=0, align="C", fill=False) txt = "<--Shoot for at least 90% for Money " + tgr_label[0] + "GR" pdf.cell(w=sum(w[3:]), txt=txt, h=h[4], border=0, ln=1, align="L", fill=False) # *Sixth row pdf.cell( w=sum(w[:2]), txt='"Money" ' + igr_label + " grade rate (" + igr_label[0] + "GR) or better schools", h=h[5], border=0, ln=0, align="L", fill=False, ) txt = _notnan(stu_data["local_oneplus_migr"], "TBD", "{:3.0%}") pdf.cell(w=w[2], txt=txt, h=h[5], border=0, ln=0, align="C", fill=False) txt = "<--Shoot for at least 50% for Money " + igr_label[0] + "GR" pdf.cell(w=sum(w[3:]), txt=txt, h=h[5], border=0, ln=1, align="L", fill=False) # *Seventh row is skinny/skip row pdf.cell(w=w[0], txt="", h=h[6], border=0, ln=1, align="C", fill=False) # *Eighth row is header for college lists and is actually the first of # *two rows used for that purpose pdf.set_font("font_b", "", 11) pdf.cell( w=w[0], txt='Schools currently applying to ("*" indicates', h=h[7], border=0, ln=0, align="L", fill=True, ) if (stu_data["Race/ Eth"] == "W") or (stu_data["Race/ Eth"] == "A"): txt_race = "6 yr (all)" else: txt_race = "6 yr AA/H" for w_this, txt_this, ln_this in [ (w[1], txt_race, 0), (w[2], "Odds of", 0), (w[3], "For you,", 0), (w[4], "", 0), (w[5], "", 1) # (0.8,'Award',0), # Replace the above with these two for new "award" column # (0.9,'Award letter',1) ]: pdf.cell( w=w_this, h=h[7], txt=txt_this, ln=ln_this, border=0, align="C", fill=True, ) # *Ninth row is continuation of college header pdf.cell(w=w[0], txt="prospective):", h=h[8], border=0, ln=0, align="L", fill=True) for w_this, txt_this, ln_this in [ (w[1], "Grad Rate", 0), (w[2], "Admit", 0), (w[3], "school is a", 0), (w[4], "App Status", 0), (w[5], "Award code", 1) # (0.80, 'code', 0), # Replace the above with these two for new "award" column # (0.9, 'received', 1) ]: pdf.cell( w=w_this, h=h[8], txt=txt_this, ln=ln_this, border=0, align="C", fill=True, ) # From here on, we'll have a variable # of rows stu_apps = app_df[app_df["hs_student_id"] == i] num_apps = len(stu_apps) pdf.set_font("font_r", "", 11) tgr = stu_data["local_target_gr"] igr = stu_data["local_ideal_gr"] _set_color_name(pdf, "light_blue") apps_displayed = 0 if num_apps: for j, app_data in stu_apps.iterrows(): college_text = app_data["collegename"] _shrink_cell( pdf=pdf, w=w[0], h=h[9], ln=0, txt=college_text, align="L", fill=False, border=0, ) # This block is complicated because of grad rate highlighting gr_this = app_data["local_6yr_all_aah"] gr_text = _notnan(gr_this, "N/A", "{:2.0%}") if gr_this >= igr: _set_color_name(pdf, "navy_blue", type="text") pdf.set_font("font_b", "", 11) if gr_this < tgr: _set_color_name(pdf, "red", type="text") _set_color_name(pdf, "grey") gr_fill = gr_this < tgr pdf.cell(w=w[1], h=h[9], ln=0, txt=gr_text, align="C", fill=gr_fill, border=0) # Back to normal for last entries _set_color_name(pdf, "black", type="text") pdf.set_font("font_r", "", 11) for w_, txt_, ln_ in [ ( w[2], _notnan(app_data["local_odds"] / 100.0, "N/A", "{:2.0%}"), 0, ), (w[3], app_data["local_class"], 0), (w[4], app_data["local_result"], 0), ( w[5], _notnan( app_data[ "local_money_code"], # (0.8, _notnan(app_data['local_money_code'], "N/A", "{}", ), 1, ), ]: pdf.cell(w=w_, h=h[9], txt=txt_, align="C", fill=False, ln=ln_, border=0) apps_displayed += 1 if apps_displayed == college_max: break # Optional school based goals at the bottom if school_goals is not None: pads, goal_eval = _get_student_goal_performance( pdf, w[0], school_goals, goal_descriptions, stu_data, stu_apps, labels) pdf.set_y(goals_start) # Two header lines: pdf.set_font("font_bi", "", 11) pdf.cell( w=w[0], h=h[10], border=0, ln=1, align="L", fill=False, txt="Your list compared to campus goals:", ) pdf.set_font("font_b", "", 11) _set_color_name(pdf, "light_blue") if pads > 0: padder = max([1, pads - 3]) * " " else: padder = "" pdf.cell( w=w[0], h=h[10], border=0, ln=0, align="L", fill=True, txt=(padder + "Campus Goal"), ) pdf.cell(w=w[1], h=h[10], border=0, ln=0, align="C", fill=True, txt="You") pdf.cell(w=w[1], h=h[10], border=0, ln=1, align="C", fill=True, txt="Met?") # Now do the variable number of goals pdf.set_font("font_r", "", 11) for goal_text, score, judgement in goal_eval: pdf.cell( w=w[0], h=h[10], border=0, ln=0, align="L", fill=False, txt=(pads * " " + goal_text), ) pdf.cell(w=w[1], h=h[10], border=0, ln=0, align="C", fill=False, txt=score) pdf.cell( w=w[1], h=h[10], border=0, ln=1, align="C", fill=False, txt=judgement, ) # Final (optional) print line for a page if local_cfg["p_footer"]: pdf.set_y(footer_start) pdf.set_font("font_bi", "", 11) p_text = _clean_excel(local_cfg["p_footer"], stu_data, labels) pdf.cell(w=sum(w), h=h[11], border="T", ln=0, align="L", fill=False, txt=p_text) # Final formatting of lines: bold rects then lines pdf.set_line_width(thick_line) pdf.rect(left_margin, top_margin + h[0], w[0], sum(h[1:3])) # around name pdf.rect( left_margin, top_margin + h[0], # around name and scores/gpa sum(w[:3]), sum(h[1:3]), ) pdf.rect( left_margin, top_margin + h[0], # around whole left side sum(w[:3]), sum(h[1:6]), ) pdf.rect( left_margin + sum(w[:4]), top_margin + h[0], # upper right sum(w[4:]), sum(h[1:3]), ) pdf.rect( left_margin + sum(w[:3]), top_margin + sum(h[:3]), # lower right sum(w[3:]), sum(h[3:6]), ) if school_goals is not None: pdf.rect( left_margin, goals_start + h[10], sum([w[0], w[1], w[1]]), h[10] * (1 + len(school_goals)), ) # Skinny rects then lines pdf.set_line_width(line) line_top = top_margin + sum(h[:7]) line_bottom = (top_margin + sum(h[:9]) + h[9] * (num_apps if num_apps <= college_max else college_max)) for x in [1, 2, 4, 5]: pdf.line( left_margin + sum(w[:x]), line_top, left_margin + sum(w[:x]), line_bottom, ) # pdf.line(left_margin+sum(w[:x])+0.8,line_top, # left_margin+sum(w[:x])+0.8,line_bottom) if do_solo: with warnings.catch_warnings(): warnings.simplefilter("ignore") this_file = os.path.join("Reports", campus, student_fn) pdf.output(this_file, "F") filenames.append(this_file) # The font we use is missing an unusued glyph and so throws two warnings # at save. The next three lines supress this, but probably good to # occasionally uncomment them if not do_solo: with warnings.catch_warnings(): warnings.simplefilter("ignore") pdf.output(fn, "F") else: # Create a zip file of all of the single files campus_fn = (campus + "_single_file_SSVs" + date.today().strftime("_%m_%d_%Y") + ".zip") with zipfile.ZipFile(campus_fn, "w", zipfile.ZIP_DEFLATED) as myzip: for file in filenames: myzip.write(file)
# -*- coding: iso-8859-1 -*- import os from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font('helvetica', '', 13.0) pdf.set_xy(105.0, 8.0) pdf.cell(ln=0, h=22.0, align='C', w=75.0, txt='Sample Invoice', 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('../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)
class PDFPrinter: PAGE_FORMAT = 'A4' UNIT = 'mm' MARGIN = 10 CONTENT_WIDTH = 297 - 2 * MARGIN CONTENT_HEIGHT = 210 - 2 * MARGIN HEADER_HEIGHT = 30 NOTES_HEIGHT = 17 TABLE_HEIGHT = CONTENT_HEIGHT - HEADER_HEIGHT - NOTES_HEIGHT FONT_S = 7 FONT_XS = 6.5 def __init__(self): self.colors = {} self.timelinesCount = None self.fontSize = 12 self.textColor = Color.WHITE self.pdf = FPDF(orientation='L', unit=PDFPrinter.UNIT, format=PDFPrinter.PAGE_FORMAT) self.pdf.add_font('regular', '', os.path.join('fonts', 'ubuntu', 'Ubuntu-B.ttf'), uni=True) self.pdf.add_font('condensed', '', os.path.join('fonts', 'roboto', 'RobotoCondensed-Regular.ttf'), uni=True) self.pdf.add_font('italic', '', os.path.join('fonts', 'roboto', 'RobotoCondensed-Bold.ttf'), uni=True) self.pdf.set_font("regular", size=self.fontSize) self.pdf.add_page() self.pdf.set_margins(PDFPrinter.MARGIN, PDFPrinter.MARGIN, PDFPrinter.MARGIN) self.uglyMeasure = FPDF(orientation='L', unit=PDFPrinter.UNIT, format=PDFPrinter.PAGE_FORMAT) self.uglyMeasure.add_font('regular', '', os.path.join('fonts', 'ubuntu', 'Ubuntu-B.ttf'), uni=True) self.uglyMeasure.add_font('condensed', '', os.path.join('fonts', 'roboto', 'RobotoCondensed-Regular.ttf'), uni=True) self.uglyMeasure.add_font('italic', '', os.path.join('fonts', 'roboto', 'RobotoCondensed-Bold.ttf'), uni=True) self.uglyMeasure.set_font("regular", size=self.fontSize) self.uglyMeasure.add_page() def defineColor(self, key, color): hex = color.lstrip('#') self.colors[key.lower()] = tuple( int(hex[i:i + 2], 16) for i in (0, 2, 4)) def printHeader(self, names): self.timelinesCount = len(names) boxWidth = PDFPrinter.CONTENT_WIDTH / self.timelinesCount boxPos = 0 for name in names: color = self.colors[name.lower()] x = PDFPrinter.MARGIN + boxWidth * boxPos y = PDFPrinter.MARGIN w = boxWidth h = 7 self._box(x, y, w, h, color=color, lineColor=Color.BLACK, lineWidth=0.1) self._text(x, y, w, h, text=name, color=self.textColor, font='regular', size=self.fontSize) boxPos += 1 def printTimetable(self, timetable): colCount = len(timetable.keys()) colWidth = PDFPrinter.CONTENT_WIDTH / colCount tablePositionY = 30 tableHeight = PDFPrinter.TABLE_HEIGHT + 1 tableHeaderHeight = 7 timelineRowHeight = tableHeight - tableHeaderHeight timelineRowPositionY = tablePositionY + tableHeaderHeight timeBlockWidth = (colWidth - 2) / self.timelinesCount timeWindow = self._findTimeWindow(timetable) yPerMin = (timelineRowHeight - 2) / (timeWindow["toTime"] - timeWindow["fromTime"]) colNo = 0 for key, schedules in timetable.items(): x = PDFPrinter.MARGIN + colWidth * colNo self._box(x=x, y=tablePositionY, w=colWidth, h=tableHeaderHeight, color=Color.LIGHT_GREY, lineColor=Color.BLACK, lineWidth=0.2) self._text(x=x, y=tablePositionY, w=colWidth, h=tableHeaderHeight, text=key, color=Color.BLACK, font='regular', size=self.fontSize) self._box(x=x, y=timelineRowPositionY, w=colWidth, h=timelineRowHeight, color=None, lineColor=Color.BLACK, lineWidth=0.2) self._drawTimeblocks(schedules, areaWidth=timeBlockWidth, areaPositionX=x, areaPositionY=timelineRowPositionY + 0.8, scaleY=yPerMin, timeWindowStart=timeWindow["fromTime"]) colNo += 1 def _drawTimeblocks(self, schedules, areaWidth, areaPositionX, areaPositionY, scaleY, timeWindowStart): timeBlockNo = 0 for person, timelines in schedules.items(): blockColor = self.colors[person.lower()] blockPositionX = areaPositionX + areaWidth * timeBlockNo + 0.5 * timeBlockNo + 0.5 for timeline in timelines: fromTimePosY = scaleY * (self._timeToInt(timeline.fromTime) - timeWindowStart) + 0.4 blockPositionY = areaPositionY + fromTimePosY blockHeight = scaleY * (self._timeToInt(timeline.toTime) - timeWindowStart) - fromTimePosY self._box(x=blockPositionX, y=blockPositionY, w=areaWidth, h=blockHeight, color=blockColor, lineColor=None) if (timeline.kind == "~"): self._drawLeftLines(x=blockPositionX, y=blockPositionY, w=areaWidth, h=blockHeight) elif (timeline.kind == "d"): self._drawTwoRightLines(x=blockPositionX, y=blockPositionY, w=areaWidth, h=blockHeight) elif (timeline.kind == "e"): self._drawEmptyRightCorner(x=blockPositionX, y=blockPositionY, w=areaWidth, h=blockHeight) self._drawTimeblockLabels(areaX=blockPositionX, areaY=blockPositionY, areaW=areaWidth, areaH=blockHeight, timeline=timeline, backColor=blockColor) timeBlockNo += 1 def _drawLeftLines(self, x, y, w, h): hw = h / w posX = x posXM = x + w posY = y posYM = y + h jump = 3 while (posXM > x): posX += jump posXM -= jump posY += jump * hw posYM -= jump * hw if jump == 2: jump = 0.5 else: jump = 2 if (posX < x + w and posY < y + h): self._line(posX, y, x, posY, Color.WHITE, lineWidth=0.2) if (posXM > x and posYM > y): self._line(posXM, y + h, x + w, posYM, Color.WHITE, lineWidth=0.2) def _drawTwoRightLines(self, x, y, w, h): hw = h / w posX = x posXM = x + w posY = y posYM = y + h jump = 2 for _ in range(4): posX += jump posXM -= jump posY += jump * hw posYM -= jump * hw # if jump == 2: # jump = 0.7 # else: # jump = 2 if (posX < x + w and posY < y + h): self._line(posX, y + h, x, posYM, Color.WHITE, lineWidth=0.3) if (posXM > x and posYM > y): self._line(posXM, y, x + w, posY, Color.WHITE, lineWidth=0.3) def _drawEmptyRightCorner(self, x, y, w, h): hw = h / w posX = x posXM = x + w posY = y posYM = y + h jump = 1 for p in range(9): posX += jump posXM -= jump posY += jump * hw posYM -= jump * hw if p > 5: jump = 1 else: jump = 0.2 if (posX < x + w and posY < y + h): self._line(posX, y + h, x, posYM, Color.WHITE, lineWidth=0.2) if (posXM > x and posYM > y): self._line(posXM, y, x + w, posY, Color.WHITE, lineWidth=0.2) def _drawTimeblockLabels(self, areaX, areaY, areaW, areaH, timeline, backColor): label = [] if (timeline.name): label.append(timeline.name.upper()) for component in timeline.components: label.append(component.upper()) if (label): self._textBlock(x=areaX, y=areaY, w=areaW, h=areaH, textLines=label, color=Color.WHITE, font='condensed', size=PDFPrinter.FONT_XS, align='C', backColor=backColor) if (timeline.fromTime): textSize = self._measure(text=timeline.fromTime, font='italic', size=PDFPrinter.FONT_S) self._text(x=areaX, y=areaY - 1, w=areaW / 2, h=textSize.y, text=timeline.fromTime, color=Color.WHITE, font='italic', size=PDFPrinter.FONT_S, align='L', backColor=backColor) if (timeline.toTime): textSize = self._measure(text=timeline.toTime, font='italic', size=PDFPrinter.FONT_S) self._text(x=areaX + areaW / 2, y=areaY + areaH - textSize.y + 1, w=areaW / 2, h=textSize.y, text=timeline.toTime, color=Color.WHITE, font='italic', size=PDFPrinter.FONT_S, align='R', backColor=backColor) def printNotes(self, notes): x = PDFPrinter.MARGIN y = PDFPrinter.MARGIN + PDFPrinter.HEADER_HEIGHT + PDFPrinter.TABLE_HEIGHT w = PDFPrinter.CONTENT_WIDTH h = 5 for note in notes: y += h self._text(x, y, w, 0, text=note, color=Color.BLACK, font='regular', size=self.fontSize, align='L') def save(self, fileName): self.pdf.output(fileName) def _measure(self, text, font, size): self.uglyMeasure.set_font(font, size=size) self.uglyMeasure.set_xy(0, 0) self.uglyMeasure.write(size / 2.83, txt=text) sizeX = self.uglyMeasure.get_x() self.uglyMeasure.write(size / 2.83, txt="\n") sizeY = self.uglyMeasure.get_y() result = Size(sizeX, sizeY) return result def _text(self, x, y, w, h, text, color, font, size, align='C', backColor=None): self.pdf.set_text_color(color[0], color[1], color[2]) self.pdf.set_font(font, size=size) self.pdf.set_xy(x, y) fillBackground = False if (backColor): self.pdf.set_fill_color(backColor[0], backColor[1], backColor[2]) fillBackground = True self.pdf.cell(w, h, txt=text, ln=1, align=align, fill=fillBackground) def _textBlock(self, x, y, w, h, textLines, color, font, size, align='C', backColor=None): textH = 0 texts = [] for line in textLines: textSize = self._measure(text=line, font=font, size=size) textSize.y += 1 textH += textSize.y texts.append({"txt": line, "height": textSize.y}) self.pdf.set_text_color(color[0], color[1], color[2]) self.pdf.set_font(font, size=size) posY = y + (h - textH) / 2 fillBackground = False if (backColor): self.pdf.set_fill_color(backColor[0], backColor[1], backColor[2]) fillBackground = True for line in texts: self.pdf.set_xy(x, posY) self.pdf.cell(w, line["height"], txt=line["txt"], align=align, fill=fillBackground) posY += line["height"] def _box(self, x, y, w, h, color, lineColor, lineWidth=0): style = '' if (lineColor): self.pdf.set_line_width(lineWidth) self.pdf.set_draw_color(lineColor[0], lineColor[1], lineColor[2]) style += 'D' if (color): self.pdf.set_fill_color(color[0], color[1], color[2]) style += 'F' self.pdf.rect(x, y, w, h, style) def _line(self, x1, y1, x2, y2, color, lineWidth): self.pdf.set_line_width(lineWidth) self.pdf.set_draw_color(color[0], color[1], color[2]) self.pdf.line(x1, y1, x2, y2) def _findTimeWindow(self, timetable): minTime = self._timeToInt("24:00") maxTime = self._timeToInt("00:00") for daySchedule in timetable.values(): for personalSchedule in daySchedule.values(): for schedule in personalSchedule: f = self._timeToInt(schedule.fromTime) t = self._timeToInt(schedule.toTime) minTime = min(minTime, f, t) maxTime = max(maxTime, f, t) return {"fromTime": minTime, "toTime": maxTime} def _timeToInt(self, str): parts = str.split(':') return int(parts[0]) * 60 + int(parts[1])
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
class Report(object): """ PDF report for plots generated on the basis of raw eye-tracking data. """ def __init__(self, file_handler, report_file_name, open_after_download_flag, properties): self.file_handler = file_handler self.open_after_download = open_after_download_flag self.properties = properties self.font_path = join(self.file_handler.fonts_dir, 'DejaVuSans.ttf') # unicode font self.pdf = FPDF(orientation='P', unit='mm', format='A4') fpdf.set_global("FPDF_CACHE_MODE", 1) # get date & time current_date = datetime.now().strftime("%d.%m.%Y %H:%M") current_timestamp = str(time.time()).replace('.', '') self.title = properties.report_title self.subtitle = properties.report_subtitle self.subtitle_date = properties.subtitle_with_date.format(current_date) self.subtitle_rec_dir = properties.subtitle_with_rec_dir_path.format( self.file_handler.recording_dir) self.subtitle_export_dir = properties.subtitle_with_exported_dir_path.format( self.file_handler.exports_dir) self.pdf_file_name = properties.pdf_report_file_name.format( current_timestamp ) if report_file_name == "" else report_file_name + ".pdf" # table with fixation_report.csv data self.fixation_detector_table_description = properties.fixation_detector_table_description self.parameter_table_header_name = properties.fixation_detector_settings_values_param self.value_table_header_name = properties.fixation_detector_settings_values_val self.target_file_path = join(self.file_handler.downloads_dir, self.pdf_file_name) self.title_font_size = 25 self.subtitle_font_size = 20 self.subsection_title_fontsize = 25 self.paragraph_fontsize = 14 def add_first_page(self): """ Creates report first page with: title, date, # recording_directory # and exports_directory """ title_line_break_value = 90 self.pdf.add_page() # add first report page self.pdf.ln(title_line_break_value) self.pdf.alias_nb_pages() # Create the special value {nb} self.pdf.set_margins(left=10.00, top=10.00, right=10.00) self.pdf.set_font("Courier", 'B', size=self.title_font_size) self.pdf.cell(w=190, h=15, txt=self.title, ln=1, align="C") self.pdf.set_font("Courier", 'B', size=self.subtitle_font_size) self.pdf.cell(w=190, h=10, txt=self.subtitle, ln=1, align="C") self.pdf.set_font("Arial", size=10) self.pdf.cell(w=190, h=10, txt=self.subtitle_date, ln=1, align="C") left = self.pdf.l_margin right = self.pdf.r_margin top = self.pdf.t_margin bottom = self.pdf.b_margin # Effective page width and height epw = self.pdf.w - left - right eph = self.pdf.h - top - bottom self.pdf.rect(left, top, w=epw, h=eph) # draw margins def add_subsection(self, title, description): self.pdf.add_page() self.pdf.set_font("Courier", 'B', size=self.subsection_title_fontsize) self.pdf.cell(w=190, h=15, txt=title, ln=1, align="L") self.add_unicode_font(14) self.pdf.multi_cell(w=190, h=10, txt=self.pdf.normalize_text(description)) def add_fixation_report(self, fixation_report_obj): self.add_unicode_font(14) epw = self.pdf.w - 2 * self.pdf.l_margin # effective page width, or just epw col_width = epw / 2 # distribute columns content evenly across table and page data = { self.parameter_table_header_name: self.value_table_header_name, "max_dispersion": fixation_report_obj.max_dispersion, "min_duration": fixation_report_obj.min_duration, "max_duration": fixation_report_obj.max_duration, "fixation_count": fixation_report_obj.fixation_count } th = self.pdf.font_size self.pdf.multi_cell(w=190, h=8, txt=self.fixation_detector_table_description, align="L") counter = 0 for key, value in data.items(): counter += 1 if counter == 1: self.pdf.cell(w=col_width, h=(2 * th), txt=self.pdf.normalize_text(str(key)), border=1, align="C") self.pdf.cell(w=col_width, h=(2 * th), txt=self.pdf.normalize_text(str(value)), border=1, align="C") self.pdf.set_font(family="font", size=10) else: self.pdf.cell(col_width, 2 * th, self.pdf.normalize_text(str(key)), border=1, align="C") self.pdf.cell(col_width, 2 * th, self.pdf.normalize_text(str(value)), border=1, align="C") self.pdf.ln(2 * th) def add_plot(self, plot): self.pdf.add_page() try: self.pdf.image(plot.image_path, w=190) except FileNotFoundError as exception: logger.error(f"NOT FOUND file {plot.image_path}") print(exception) self.add_unicode_font(plot.fontsize) self.pdf.multi_cell(w=190, h=10, txt=self.pdf.normalize_text(plot.description)) def save_report(self): """ Saves report in /exports/../downloads directory """ logger.info(f'Save report into {self.target_file_path}') self.pdf.output(self.target_file_path) logger.info(f"Report '{self.pdf_file_name}' saved") logger.info(f"Report directory: {self.file_handler.downloads_dir}") if self.open_after_download: try: startfile(self.target_file_path) except: system("xdg-open \"%s\"" % self.target_file_path) def add_unicode_font(self, fontsize): print("FONT PATH: \n", self.font_path) self.pdf.add_font(family="font", fname=self.font_path, uni=True) self.pdf.set_font(family="font", size=fontsize)
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")