def dotest(outputname, nostamp): try: from bidi.algorithm import get_display except ImportError: from unittest import SkipTest raise SkipTest("Need python-bidi") pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.compress = False pdf.add_page() pdf.add_font('DejaVu', '', \ os.path.join(common.basepath, 'font/DejaVuSans.ttf'), uni=True) pdf.set_font('DejaVu', '', 14) # this will be displayed wrong as actually it is stored LTR: text= u"این یک متن پارسی است. This is a Persian text !!" pdf.write(8, text) pdf.ln(8) # Reverse the RLT using the Bidirectional Algorithm to be displayed correctly: # (http://unicode.org/reports/tr9/) rtl_text = get_display(text) pdf.write(8, rtl_text) pdf.output(outputname, 'F')
def raport(): day = (datetime.today()).strftime("%d/%m/%y").replace('/0', '/').lstrip('0') WIDTH = 210 HEIGHT = 297 pdf = FPDF() pdf.add_page() pdf.set_font("Arial", 'B', 16) pdf.image("raport/tytul.png", 0, 0, WIDTH) pdf.ln(60) pdf.write(5, f'Raport {day}') pdf.image("raport/obrot_got.png", 10, 80, WIDTH - 20, 120) pdf.image("raport/zyski.png", 5, 200, WIDTH / 2 - 10, WIDTH / 2 - 10) pdf.image("raport/marza.png", WIDTH / 2 + 5, 200, WIDTH / 2 - 10, WIDTH / 2 - 10) pdf.add_page() pdf.image("raport/ilosc_zlec.png", 5, 0, WIDTH - 10) pdf.output("raport_SPIE.pdf", 'F')
def export_certificado(temp, correccion, incertidumbre): now = datetime.datetime.now() nowAux = str(now) nombre_certificado = nowAux[0:20] pdf = FPDF(format='A4', unit='mm') pdf.add_page() pdf.set_font('Arial', '', 10.0) epw = pdf.w - 2 * pdf.l_margin col_width = epw / 4 # Since we do not need to draw lines anymore, there is no need to separate # headers from data matrix. th = pdf.font_size pdf.set_font('Times', 'B', 14.0) pdf.cell(epw, 0.0, '', align='C') pdf.set_font('Times', '', 10.0) pdf.ln(0.5) # Here we add more padding by passing 2*th as height pdf.cell(col_width, 2 * th, str(nombre_certificado), border=1) pdf.cell(col_width, 2 * th, str(temp), border=1) pdf.cell(col_width, 2 * th, str(correccion), border=1) pdf.cell(col_width, 2 * th, str(incertidumbre), border=1) name = "certificados/" + "Certificado_" + str(nombre_certificado) + ".pdf" pdf.output(name)
def simple_table(self): # for making pdf spacing = 3 pdf = FPDF() pdf.set_font("Arial", size=4) pdf.add_page() col_width = pdf.w / 8 row_height = pdf.font_size # print(self.data) headings = [ 'Application', 'Application Date(YY-MM-DD)', 'Name', 'Trademark', 'User Details', 'Class', 'Status', 'Contact', 'Email', 'TMJ', 'Renewal', 'Address' ] for i in headings: # for headings pdf.cell(col_width, row_height * spacing, txt=i, border=2) pdf.ln(row_height * spacing) for row in self.data: # getting data from table(i.e database) print(row) for item in row: pdf.cell(col_width, row_height * spacing, txt=str(item), border=1) pdf.ln(row_height * spacing) pdf.output('pdf_file1.pdf') os.system('explorer.exe "pdf_file1.pdf"' ) # to open default pdf that already have print option
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.add_font('DejaVu', '', os.path.join(common.basepath, 'font/DejaVuSansCondensed.ttf'), uni=True) pdf.set_font('DejaVu', '', 14) # Note: this line cause syntax error in Python 3.0-3.2 text = u""" Veľké písmená A Á Ä B C Č D Ď DZ DŽ E É F G H CH I Í J K L Ĺ Ľ Malé písmená a á ä b c č d ď dz dž e é f g h ch i í j k l ĺ ľ Veľké písmená M N Ň O Ó Ô P Q R Ŕ S Š T Ť U Ú V W X Y Ý Z Ž Malé písmená m n ň o ó ô p q r ŕ s š t ť u ú v w x y ý z ž """ pdf.write(8, text) pdf.ln(8) pdf.output(outputname, 'F')
def create_order_pdf(image_path, data, image_name, spacing=1): pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True) pdf.set_font("DejaVu", size=12) pdf.add_page() text = "Automatic order form 'CRISPY MACHINE'" pdf.cell(200, 10, txt=text, ln=1, align="C") pdf.image(image_path, x=60, y=20, w=100, type='', link='') pdf.ln(150) # ниже на 100 col_width = pdf.w / 2.2 row_height = 2 * pdf.font_size for row in data: for item in row: if len(item) < 36: pdf.cell(col_width, row_height * spacing, txt=item, border=1) else: pdf.multi_cell(col_width, row_height * spacing, txt=item, border=1) pdf.ln(row_height * spacing) text2 = "© 2020 Copyright: 'CRISPY MACHINE'" pdf.cell(200, 10, txt=text2, ln=1, align="C") im_name = image_name[:-3] im_name2 = im_name + 'PDF' im_name2 = im_name2.replace('C:/PP/ORP/ORP_site/OR/media/image_preview/', '') pdf_path = 'C:/PP/ORP/ORP_site/OR/media/temp/' + im_name2 pdf.output(pdf_path) return pdf_path
def report01(self): # try: # from StringIO import StringIO ## for Python 2 # except ImportError: # from io import StringIO ## for Python 3 # output = StringIO() # p = canvas.Canvas(output) # p.drawString(100, 100, 'Hello') # p.showPage() # p.save() # pdf_out = output.getvalue() # output.close() # response = make_response(pdf_out) # response.headers['Content-Disposition'] = "attachment; filename='sakulaci.pdf" # response.mimetype = 'application/pdf' # return response pdf = FPDF() # compression is not yet supported in py3k version pdf.compress = False pdf.add_page() # Unicode is not yet supported in the py3k version; use windows-1252 standard font pdf.set_font('Arial', '', 14) pdf.ln(10) pdf.write(5, 'hello world %s áéíóúüñ' % sys.version) #pdf.image("pyfpdf/tutorial/logo.png", 50, 50) pdf.output('/tmp/py3k.pdf', 'F') return send_file('/tmp/py3k.pdf', mimetype='application/pdf')
def table(self, pdf: FPDF, header: list, data): pdf.set_fill_color(200) pdf.set_line_width(.3) pdf.set_font('', 'B') w = [15, 100, 45, 25] for i in range(len(header)): pdf.cell(w[i], 7, header[i], 1, 0, 'C') pdf.ln() pdf.set_font('') fill = False for row in data: if pdf.get_y() > 250: border = 'LRT' else: border = 'LR' pdf.cell(w[0], 6, str(row.inventory_supply.id), border, 0, 'L', fill) pdf.cell(w[1], 6, self.removeSpecialCharacters(row.inventory_supply.name), border, 0, 'L', fill) username = "******" if row.checked_by is None else self.removeSpecialCharacters( row.checked_by.username) pdf.cell(w[2], 6, username, border, 0, 'C', fill) pdf.cell(w[3], 6, '', border, 0, 'C', fill) pdf.ln() fill = not fill if pdf.get_y() > 250: pdf.cell(sum(w), 0, '', 'T', 1) pdf.cell(sum(w), 0, '', 'T')
def onPrintReportReleased(self): user_name = self.ids.user_name.text entry_substance_name = self.ids.substance_name.text if self.ids.dangerous_checkbox.active: dangerous_value = "Dangerous" else: dangerous_value = "Non-Dangerous" today = datetime.date.today() now = datetime.datetime.now() entry_date = str(now.day) + " " + str(today.strftime('%B')) + " " + str(now.year) pdf = FPDF() # compression is not yet supported in py3k version pdf.compress = False pdf.add_page() # Unicode is not yet supported in the py3k version; use windows-1252 standard font pdf.set_font('Arial', '', 14) pdf.ln(10) pdf.cell(100, 10, user_name, 1) pdf.cell(70, 10, entry_date, 1) pdf.ln(10) pdf.cell(100, 10, entry_substance_name, 1) pdf.cell(70, 10, dangerous_value, 1) pdf.output('lab_report.pdf', 'F') os.system("lpr -P DYMO_LabelWriter_4XL -o media=Custom.4x6in -o page-left=0 -o page-right=0 -o page-top=0 -o page-bottom=0 lab_report.pdf") """
def create_and_fill_pdf_file(news_collection, com_line_args, logger): """ Function for creating and filling in the pdf file with news. """ path_to_directory = com_line_args.to_pdf check_path_to_directory(path_to_directory, logger) pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.set_margins(5, 13.5, 5) pdf.add_page() pdf.set_font('Arial', size=16) pdf.set_text_color(255, 0, 0) if com_line_args.date: pdf.cell(200, 10, txt="RSS news from the local storage", ln=1, align="C") else: pdf.cell(200, 10, txt="RSS news from the internet", ln=1, align="C") pdf.ln(5) pdf.set_text_color(0, 0, 0) for news in news_collection: add_news_to_pdf_file(news, pdf, com_line_args, logger) logger.info("Creating pdf file with news.") path_to_pdf_file = os.path.join(path_to_directory, "rss_news.pdf") pdf.output(path_to_pdf_file, 'F') logger.info("PDF file is created.")
def createpdf(obj): data.append(obj) print(data) pdf = FPDF() pdf.add_page() pdf.add_font('pep', '', r"Montserrat/Montserrat-SemiBold.ttf", uni=True) pdf.add_font('reg', '', r"Montserrat/Montserrat-Regular.ttf", uni=True) pdf.add_font('zhop', '', r"Montserrat/Montserrat-Medium.ttf", uni=True) pdf.set_font("pep", size=28) pdf.image("Logo.png", x=12, y=15, w=70) pdf.cell(200, 65, txt="Indkøbsvogn", ln=1, align="L") pdf.set_font("reg", size=24) col_width = pdf.w / 2.5 row_height = pdf.font_size c = 0 for row in data: if c != 0: pdf.set_font("zhop", size=15) for item in row: print(item) pdf.cell(col_width, row_height * 1, txt=item, border=1) pdf.ln(row_height * 1) c += 1 pdf.image("p.png", x=3, y=250, w=200) pdf.output("demo.pdf")
def generate_salary_list(Hall): """ Print list of all employees and respective salary details for specified hall Take dict of Worker objects as parameter """ pdf = FPDF('P', 'mm', 'A4') pdf.add_page('P') pdf.set_font('Times', 'B', 14) pdf.multi_cell(0, 5, ('Hall Salary List: Hall %s' % Hall.hall_ID)) pdf.ln() worker_list = dbr.rebuild("worker") title = "Role" wage = 0 for key in worker_list: if worker_list[key].hall_ID == Hall.hall_ID: if isinstance(worker_list[key], mess_manager.MessManager): title = "Mess Manager" wage = worker_list[key].monthly_salary elif isinstance(worker_list[key], clerk.Clerk): title = "Clerk" wage = worker_list[key].monthly_salary elif isinstance(worker_list[key], attendant.Attendant): title = "Attendant" wage = worker_list[key].daily_wage pdf.multi_cell(0, 5, ('%s: %s (%s) - Rs. %s' % (worker_list[key].worker_ID, worker_list[key].name, title, wage))) pdf.ln() # Write generated output file to PDF pdf.output(('hall_salary_%s.pdf' % Hall.hall_ID), 'F')
def test_multi_cell_ln_3_table(tmp_path): """ Test rendering of a table with multi-lines cell contents cf. https://github.com/PyFPDF/fpdf2/issues/63 """ pdf = FPDF() pdf.add_page() pdf.set_font("Times", size=10) line_height = pdf.font_size * 2.5 # Set column width to 1/4 of effective page width to distribute content # evenly across table and page col_width = pdf.epw / 4 for row in TABLE_DATA: for datum in row: pdf.multi_cell( col_width, line_height, str(datum), border=1, new_x=XPos.RIGHT, new_y=YPos.TOP, max_line_height=pdf.font_size, ) pdf.ln(line_height) assert_pdf_equal(pdf, HERE / "multi_cell_ln_3_table.pdf", tmp_path)
def dotest(outputname, nostamp): try: from bidi.algorithm import get_display except ImportError: from unittest import SkipTest raise SkipTest("Need python-bidi") pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.compress = False pdf.add_page() pdf.add_font('DejaVu', '', \ os.path.join(common.basepath, 'font/DejaVuSans.ttf'), uni=True) pdf.set_font('DejaVu', '', 14) # this will be displayed wrong as actually it is stored LTR: text = u"این یک متن پارسی است. This is a Persian text !!" pdf.write(8, text) pdf.ln(8) # Reverse the RLT using the Bidirectional Algorithm to be displayed correctly: # (http://unicode.org/reports/tr9/) rtl_text = get_display(text) pdf.write(8, rtl_text) pdf.output(outputname, 'F')
def wrap(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: e_message = [] e_message.append({ 'status': 'Error', 'object': str(type(e)), 'message': '{}'.format(e) }) logger.debug(e_message) #raise BadRequest(e) if request.headers['Accept'] == "application/pdf": pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=14) for key, value in e_message[0].items(): pdf.write(18, txt="{} : {}".format(key, value)) pdf.ln() pdf_byte_str = pdf.output(dest='S').encode('latin-1') buffer_resp = BytesIO(bytes(pdf_byte_str)) buffer_resp.seek(0) response = make_response( send_file(buffer_resp, as_attachment=True, attachment_filename='Error.pdf', mimetype='application/pdf'), 500) else: response = make_response(jsonify(e_message), 500) logger.debug("Response: {}".format(dict(response.headers))) return response
def pdf_generator(path): print("-----------------Generating PDF--------------------------") chalks = [ori for ori in glob.glob("[0-9].jpg")] chalks = chalks + [ori for ori in glob.glob("[0-9][0-9].jpg")] chalks = chalks + [ori for ori in glob.glob("[0-9][0-9][0-9].jpg")] print(chalks) chalks = [s.replace(".jpg", "") for s in chalks] chalks.sort(key=int) with open(path + '/output_summary.txt', 'r') as content_file: content = content_file.read() breaks = content.split('.') pdf = FPDF() final_content = "" print(chalks) for k in breaks: final_content = final_content + k + "." + "\n" #print(final_content) pdf.add_page() pdf.set_font('Times', '', 14) pdf.multi_cell(0, 5, final_content) pdf.ln() for j in chalks: image_path = path + "/" + str(j) + ".jpg" pdf.add_page() pdf.image(image_path, x=10, y=8, w=100) pdf.output("summary.pdf")
def create_pdf_file(cmd_args, all_news): """ Creates and fills in the PDF file with the required data """ path_to_pdf = create_path_to_file(cmd_args.to_pdf, 'RSS_NEWS.pdf') # --- normal cache mode --- set_global("FPDF_CACHE_MODE", 0) pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.set_margins(5, 10, 5) pdf.add_page() # use downloaded unicode font pdf.add_font('dejavu', '', os.path.join(FONT_PATH, 'DejaVuSans.ttf'), uni=True) pdf.set_font('dejavu', size=20) pdf.set_text_color(5, 14, 110) pdf.cell(200, 10, txt=f'RSS News', ln=1, align="C") pdf.ln(10) pdf.set_text_color(0, 0, 0) for new in all_news: add_new_to_pdf(cmd_args, new, pdf) LOGGER.info(f'Download PDF file with required news to the {path_to_pdf}') try: pdf.output(path_to_pdf, 'F') except FileNotFoundError: raise PATHError('Setted PATH is invalid')
def saveFile(filepath, contents): try: ext = os.path.basename(filepath).rsplit(".", 1)[1] except: ext = defaultFileExtension ext = ext.upper() prefs = fullSettings["document"].get( defaultSettings["__extToType"].get(ext), {}) if ext == "DOCX": wordDoc = docx.Document() for para in contents.split("\n\n"): wordDoc.add_paragraph(para) wordDoc.save(filepath) elif ext == "PDF": pdf = FPDF("P", "pt", "A4") # 595pt x 842pt pdf.set_font(prefs["fontName"], size=prefs["fontSize"]) pdf.add_page() for para in contents.encode('latin-1', 'replace').decode('latin-1').split("\n\n"): pdf.multi_cell(prefs["__lineWidth"], prefs["lineHeight"], txt=para) pdf.ln() pdf.output(filepath) else: with open(filepath, "w") as f: f.write(contents)
def report(companyName, buffer, milesOverPercentage, includeBox, includeBar, dayArray, includeReport): reportPdf = FPDF() reportPdf.set_auto_page_break(0) titlePage(companyName, buffer, reportPdf) descriptionPage(reportPdf, 'intro_explain.txt') if includeReport: numericPage(reportPdf, dayArray, companyName) reportPdf.ln(5) if includeBox: chartPage( reportPdf, companyName + ' Fleet Boxplot ' + str(datetime.date.today()) + '.png', 'description_box.txt') if includeBar: chartPage( reportPdf, companyName + ' Fleet Boxplot ' + str(datetime.date.today()) + '.png', 'description_bar.txt') descriptionPage(reportPdf, 'outtro_explain.txt') reportPdf.add_page() reportPdf.set_font('Arial', 'I', 8) with open('citationsList.txt', 'r') as fd: lines = fd.read().splitlines() reportPdf.set_y(-5 - (5 * len(lines))) for line in lines: reportPdf.cell(0, 10, line) reportPdf.ln(5) reportPdf.output(companyName + ' HelloEV analysis.pdf', 'F')
def make_infosheet(planet): #Produce the pdf pdf = FPDF('P', 'in', 'Letter') # pdf.add_font('Kontrapunkt-Light', '', 'Kontrapunkt-Light.ttf', uni=True) # pdf.add_font('Kontrapunkt-Bold', '', 'Kontrapunkt-Bold.ttf', uni=True) pdf.add_page() pdf.set_font('Arial', 'B', 16) text = planet + " System Information" pdf.cell(8.5, .5, text, 0, 1, 'C') pdf.image(fname, y=1, w=7.71259843) pdf.ln(3) #Add plantary output (basic) if moonlocation == 0: text = galaxy._stars[location]['planets'].planets[planetlocation] else: text = galaxy._stars[location]['planets'].planets[ planetlocation].moons[moonlocation] text = repr(text) text = text.split('\n') text = '\n'.join(text) pdf.set_font('Arial', '', 8) pdf.multi_cell(3.856299215, .15, text, border='R', align="L") #3.856299215 #Fun details text = planet + '.pdf' pdf.output(text, 'F')
def create_pdf(title, copyright, description, date, url): try: base_path = os.path.abspath(os.path.dirname(__file__)) photo_path = base_path + "/photos/" pdf_path = base_path + "/pdfs/" if not os.path.exists(photo_path + date + '-photo.jpg'): print("Fazendo o download da imagem...") download_image(url) description = description.encode('latin-1', 'ignore') description = description.decode('UTF-8') pdf_file = FPDF(orientation='P', format='A4') pdf_file.add_page() pdf_file.image(f'{photo_path}{date}-photo.jpg', x=30, w=150, link=url) pdf_file.ln(10) pdf_file.set_font("Arial", size=10) pdf_file.cell(0, 10, f'Title: {title}', ln=1, align="C") pdf_file.cell(0, 10, f'Copyright: {copyright}', ln=1, align="C") pdf_file.multi_cell(0, 5, f'Description: {description}', align="C") pdf_file.cell(0, 10, f'Date: {date}', ln=1, align="C") pdf_file.output(f"{pdf_path}{date}.pdf") print("PDF criado com sucesso!") print(f"Caminho do arquivo:{pdf_path}{date}.pdf", ) except Exception as error: print("Erro ao criar o PDF: ") print(error)
def hourpdf(request): # use to see working of temporary employee. pdf = FPDF('P', 'mm', 'A4') pdf.add_page() ganY = [46, 54] # line bettwen collumn. pdf.add_font('Kinnari', '', 'Kinnari.ttf', uni=True) pdf.set_font('Kinnari', '', 12) gen_single_text(pdf, 60, u'ใบลงเวลาทำงานลูกจ้างชั่วคราวรายชั่วโมง') gen_single_text(pdf, 45, u'มหาวิทยาลัยเทคโนโลยีพระจอมเกล้าพระนครเหนือ') gen_single_text(pdf, 70, u'ชื่อ') pdf.ln(8) pdf.cell(0, 18, u' วัน วันที่ เดือน ปี เวลาทำงาน รวมชั่วโมง ลายมือชื่อ หมายเหตุ') drawAttr2(pdf, ganY[0], ganY[1], True) gen_single_text(pdf, 90, u'รวมจำนวนชั่วโมง ' + u'ชั่วโมง') # call spacial funtion to write a text per line. gen_single_text(pdf, 90, u'อัตรา 45.45 บาท ชั่วโมง') gen_single_text(pdf, 90, u'รวมเป็นเงินทั้งสิ้น' + u'บาท') gen_single_text(pdf, 90, u'( )') gen_single_text(pdf, 90, u'ได้ตรวจสอบถูกต้องแล้ว') gen_single_text(pdf, 75, u'ลงชื่อ.......................................................') gen_single_text(pdf, 80, u'(...................................................)') pdf.output("group3/hour.pdf", 'F') with open('group3/hour.pdf', 'rb') as pdf: # path to pdf in directory views. response = HttpResponse(pdf.read(),content_type='application/pdf') response['Content-Disposition'] = 'filename=hour.pdf' return response pdf.closed
def processing(self): img = qrcode.make(self.qr_text) img.save("./img/qr.png") pdf = FPDF() pdf.add_page() pdf.add_font("Times", "B", "./img/times.ttf", uni=True) pdf.set_font("Times", "B", 16) pdf.image("./img/logo.gif", 10, 10, 33) pdf.image("./img/qr.png", 160, 8, 45) pdf.image("./img/footer.png", 10, 220, 200) for header in self.header: pdf.cell(75) pdf.cell(30, 10, header, 0, 1, "C") pdf.ln(20) pdf.add_font("Times", "", "./img/times.ttf", uni=True) pdf.set_font("Times", "", 14) for t in self.main_text: pdf.cell(0, 10, t, 0, 1) pdf.output("./pdf/" + self.pdf_filename_to_save, "F") self.processed_flag = True
def gerarPDF(qtd_img, Tamanho, qtd_Arq, diretorio): pdf = FPDF(orientation='P', format='A4', unit=u'mm') pdf.set_font(u'Arial', size=18) pdf.set_line_width(0.1) # evita quebra automatica da pagina, ao chegar perto da borda inferior pdf.set_auto_page_break(False) pdf.set_margins(8, 8) pdf.add_page() pdf.text(60, 50, txt=u'Relatório de Contagem de Imagens') pdf.ln("") pdf.set_font_size(size=10) pdf.text(10, 60, txt=u'Total de Imagens = %s' %qtd_img) pdf.text(80, 60, txt=u'Espaço Ocupado = %s' %Tamanho) pdf.text(150, 60, txt=u'Total de Arquivos = %s' %qtd_Arq) pdf.text(10, 70, txt=u'Data = %s às %s' %(datetime.datetime.now().date().__format__(u'%d/%m/%Y'), datetime.datetime.now().time().__format__(u'%H:%M:%S'))) pdf.ln("") pdf.text(10, 80, txt=u'Diretório Raiz= %s' %diretorio) pdf.output(u'./relatório.pdf', u'F') # gerarPDF(0,0,0,0)
def make_pdf(site, MAP, pdf_name, wc_name, wc_name_mask, name1_2d, name2_2d, sim_name, gif_name, img_promo): PROLOG = f'''Web Scraping science papers from site: {site} on the topic - "Connectome".''' EPILOG = "Top Words Cloud" EPILOG2 = "t-SNE" empty = [] # Description pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=15, style="B") #pdf.set_creator("Bonart") pdf.multi_cell(0, 8, txt=PROLOG, align="C") pdf.image( img_promo, x=15, y=50, w=180, link="8.8.8.8", ) # pdf.add_page() # Create pdf-pages with data from dictionary for idx, i in enumerate([x for x in MAP.items()]): try: url = i[0] title = encode_decode(i[1][1]) data = encode_decode(i[1][0][0]) pdf.ln(10) pdf.set_font("Arial", size=12, style="B") pdf.multi_cell(0, 8, txt=title, align="L") pdf.set_text_color(180, 5, 100) pdf.cell(0, 10, txt=url, ln=1, align="L") pdf.set_text_color(0, 0, 0) pdf.set_font("Arial", size=12) pdf.multi_cell(0, 8, txt=data) except: empty.append(idx) continue print("Amount of empty data:", len(empty)) # Epilog pdf.add_page() pdf.set_font("Arial", size=15, style="B") pdf.multi_cell(0, 8, txt=EPILOG, align="C") pdf.image(f'{wc_name}.png', x=15, y=30, w=180, link="8.8.8.8") pdf.add_page() pdf.image(f'{wc_name_mask}.png', x=15, y=10, w=180, link="8.8.8.8") pdf.add_page() pdf.image(f'{name1_2d}.png', x=15, y=10, w=180, link="8.8.8.8") pdf.add_page() pdf.image(f'{name2_2d}.png', x=15, y=10, w=180, link="8.8.8.8") pdf.add_page() pdf.image(f'{sim_name}.png', x=15, y=10, w=180, link="8.8.8.8") pdf.add_page() pdf.image(gif_name, x=15, y=10, w=180, link="8.8.8.8") pdf.output(f"{pdf_name}.pdf")
def create_abfrage_pdf(abfrage, kriterium1, kriterium2, tierhaltungen): fpdf = FPDF() fpdf.t_margin = 20 fpdf.r_margin = 16 fpdf.b_margin = 26 fpdf.l_margin = 10 fpdf.orientation = 'P' fpdf.format = 'A4' fpdf.set_font('Arial', '', 11) fpdf.add_page() spacing = 1.2 width = 184 #210 - (16 + 10) = 184 height = fpdf.font_size fpdf.set_font('Arial', '', 14) topic_height = fpdf.font_size if (kriterium2 and len(kriterium2) > 0): abfrage = "Abfrage " + abfrage + ", " + kriterium1 + " - " + kriterium2 else: abfrage = "Abfrage " + abfrage + ", " + kriterium1 fpdf.cell(width, topic_height * spacing, txt=abfrage, border=0) fpdf.ln(10) fpdf.set_font('Arial', '', 11) write_abfrage_table(fpdf, tierhaltungen, width, height, spacing) byte_string = fpdf.output(dest="S").encode('latin-1') return byte_string
class Document(object): def __init__(self, **kwargs): self.pdf = FPDF(**kwargs) self.pdf.add_page() self.pdf.set_margins(20, 20, 0) self.pdf.ln() self._add_font('DejaVu', 'DejaVuSansCondensed.ttf') self._add_font('DejaVu-Bold', 'DejaVuSansCondensed-Bold.ttf') def _add_font(self, font_name, file_name): self.pdf.add_font(font_name, '', asset_path(file_name), uni=True) def _font(self, size, bold=False): font_name = 'DejaVu' if not bold else 'DejaVu-Bold' self.pdf.set_font(font_name, '', size) def _text_cell(self, w, h, text, size=10, bold=False, align='L', border=BORDER_DEBUG): self._font(size, bold=bold) self.pdf.cell(w, h, text, align=align, border=border) def _multi_cell(self, w, h, text, size=10, bold=False, align='L', border=BORDER_DEBUG): self._font(size, bold=bold) self.pdf.multi_cell(w, h, text, align=align, border=border) def output(self): return self.pdf.output(dest='S')
def generate_pdf(): spacing = 2 title = 'Order Report for Customers' pdf = FPDF(format='letter', unit='in') pdf.add_page() pdf.set_font('Arial', '', 10.0) epw = pdf.w - 4 * pdf.l_margin col_width = epw / 5 data = [[ 'Date', 'Customer Name', 'No of Orders', 'Submitted Orders', 'Incomplete Orders' ], ['04-08-19', 'ZCP', '57', '15', '35'], ['04-08-19', 'ZCP', '59', '32', '23'], ['04-08-19', 'ZCP', '88', '28', '21']] pdf.set_font('Arial', 'B', 14.0) # pdf.cell(w, h = 0, txt = '', border = 0, ln = 0, align = '', fill = False, link = '') pdf.cell(epw, 1.0, 'Order Report', align='C') pdf.set_font('Arial', '', 10.0) pdf.ln(1) row_h = pdf.font_size th = row_h * spacing for row in data: print(row) for datum in row: print(datum) pdf.cell(col_width, th, str(datum), border=1, align='C') pdf.ln(th) # pdf.ln(5*th) pdf.output( 'order_report ' + datetime.datetime.now().strftime("%Y-%m-%d") + '.pdf', 'F')
def convert_TO_pdf(path, ID, book_title, format): a4_width_mm = 210 pt_to_mm = 0.35 fontsize_pt = 10 fontsize_mm = fontsize_pt * pt_to_mm margin_bottom_mm = 10 character_width_mm = 7 * pt_to_mm width_text = a4_width_mm / character_width_mm pdf = FPDF(orientation = 'P', unit = 'mm', format = 'A4') pdf.set_auto_page_break(True, margin = margin_bottom_mm) pdf.add_page() pdf.set_font(family = 'Courier', size = fontsize_pt) myfile = open(path, 'r') text = myfile.read() splitted = text.split('\n') for line in splitted: lines = textwrap.wrap(line, width_text) if len(lines) == 0: pdf.ln() for wrap in lines: pdf.cell(0, fontsize_mm, wrap, ln = 1) pdf.output(path_download + ID + '-' + book_title + format, 'F') myfile.close()
def save_pdf(): if flag == 1: pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'B', size=16) pdf.cell(190, 10, str(word.upper()), 1, 0, 'C') pdf.ln(20) pdf.set_font('Arial', size=13) l = get_pieces(str(ans), 87) for i in l: pdf.cell(0, 7, str(i.replace('\u2013', '')), 0, 1) pdf.output(str(word.title()) + '_info.pdf') lbl = Label(root, text="PDF file saved.", padx=15, pady=3, fg="#099c5c", bg="#043b23") lbl.place(rely=1.0, anchor="sw") lbl.after(4000, lbl.destroy) else: lbl = Label(root, text="Nothing to save.", padx=15, pady=3, fg="#de1814", bg="#360403") lbl.place(rely=1.0, anchor="sw") lbl.after(4000, lbl.destroy)
def add_image(image_path): pdf = FPDF() pdf.add_page() pdf.image(image_path, x=10, y=8, w=100) pdf.set_font("Arial", size=12) pdf.ln(85) pdf.cell(200, 10, txt="{}".format(image_path), ln=1) pdf.output("add_image.pdf")
def create_pdf(day, company, filename='current_twitter_analysis.pdf'): pdf = FPDF() ''' PAGE 1 ''' pdf.add_page() pdf.image('images/header_image.png', 0, 0, WIDTH) create_title(day, company, pdf) # Tweets Over Time pdf.image('images/total_tweets.png', 10, 90, WIDTH - 25) # Engagements vs tweets pdf.image('images/engagements_vs_tweets.png', 10, 190, WIDTH - 20) ''' PAGE 2 ''' pdf.add_page() # Tweets by weekday pdf.image('images/tweets_month_per_day_avg.png', 10, 35, WIDTH - 30) # Mentions Weekdays pdf.image('images/tweets_year_per_day_avg.png', 10, 155, WIDTH - 30) ''' PAGE 3 ''' pdf.add_page() # Mentions Wordcloud pdf.set_font('Arial', 'B', 18) pdf.write(25, f'Twitter Mentions Wordcloud') pdf.image('images/mentions_wordcloud.png', 15, 35, WIDTH - 30) pdf.ln(1) # Hashtags Wordcloud pdf.set_font('Arial', 'B', 18) pdf.write(260, f'Twitter Hashtags Wordcloud') pdf.image('images/hashtags_wordcloud.png', 15, 155, WIDTH - 30) ''' PAGE 4 ''' pdf.add_page() # Mentions Tweets Over Time pdf.image('images/top10_mentions.png', 10, 35, WIDTH - 30) # Mentions Weekdays pdf.image('images/mentions_over_time.png', 10, 165, WIDTH - 30) ''' PAGE 5 ''' pdf.add_page() # Mentions Tweets Over Time pdf.image('images/tweets_over_time.png', 10, 35, WIDTH - 30) # Mentions Weekdays pdf.image('images/tweets_weekday_all.png', 10, 155, WIDTH - 30) ''' PAGE 6 ''' pdf.add_page() # Mentions Tweets Over Time pdf.image('images/engagements_vs_mentions.png', 15, 35, WIDTH - 30) # pdf.ln(155) # pdf.set_font('Arial', '', 12) # conclusion = f'That concludes the twitter tweet analysis. Please see my website for the most up-to-date version of this Twitter Analytics PDF. It is constantly being updated and can be followed on my website at jamesejordan.com' # pdf.multi_cell(WIDTH-15, 5, conclusion, align='L') pdf.output('current_twitter_analysis.pdf', 'F') return
def test_highlighted_over_page_break(tmp_path): pdf = FPDF() pdf.add_page() pdf.set_font("helvetica", size=24) pdf.write(txt=LOREM_IPSUM) pdf.ln() with pdf.add_highlight("Comment", title="Freddy Mercury", modification_time=EPOCH): pdf.write(txt=LOREM_IPSUM) assert_pdf_equal(pdf, HERE / "highlighted_over_page_break.pdf", tmp_path)
def add_image(request, image_path): pdf = FPDF() pdf.add_page() pdf.image(image_path, x=10, y=8, w=100) pdf.set_font("Arial", size=12) pdf.ln(85) # move 85 down pdf.cell(200, 10, txt="{}".format(image_path), ln=1) pdf.output("add_image.pdf") return render(request, "index.html")
def getOutputToFile(): pdf = FPDF('L', 'mm', 'A4') pdf.add_page() pdf.set_font("Arial", size=25) pdf.cell(0, 10, txt="SUMMARY", align="C") pdf.ln(h='') pdf.set_font("Arial", size=12) pdf.multi_cell(0, 10, txt=summaryOutput.get("1.0", tk.END), align="C") pdf.output("output.pdf") pdf.close()
def pdfGen(Input,fontName,Output): pdf = FPDF() pdf.add_page() ttfName=fontName+'.ttf' pdf.add_font(fontName, '', ttfName, uni=True) pdf.set_font(fontName, '', 14) linestring = open(Input, 'r').read() pdf.write(8,linestring) pdf.ln(20) pdf.output(Output, 'F')
def pdfGen(request): pdf = FPDF() pdf.add_page() #pdf.add_font('gargi', '', 'gargi.ttf', uni=True) #pdf.set_font('gargi', '', 14) #pdf.write(8, u'Hindi: एक अमरीकि') pdf.add_font('Kedage-b', '', 'Kedage-b.ttf', uni=True) pdf.set_font('Kedage-b', '', 14) #pdf.add_font('TSCu_SaiIndira', '', 'TSCu_SaiIndira.ttf', uni=True) #pdf.set_font('TSCu_SaiIndira', '', 14) linestring = open('DigiFiles/KannadaInput.txt', 'r').read() pdf.write(8,linestring) pdf.ln(20) pdf.output("DigiFiles/KannadaOutput.pdf", 'F')
def on_bimprimirrepuestos_clicked(self, widgets): listarep = self.interface.get_object("listarep") recorrer = listarep.get_iter_first() pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", "B", size=16) pdf.cell(110, 10, "Listado de repuestos", 0, 0) pdf.cell(25, 10, "Talleres cuspedrinos", 0, 1) pdf.cell(110, 10, "", 0, 0) pdf.cell(25, 10, "Tel. 555555555", 0, 1) pdf.cell(110, 10, " ", 0, 0) now = datetime.datetime.now() fecha = now.strftime("%Y-%m-%d %H:%M") pdf.cell(25, 10, str(fecha), 0, 1) pdf.image('/home/daniel/workspace/taller/img/tallerlogo.jpg', x=70, y=2, w=40, h=50, type='jpg') columnas = ["Cod", "Nombre", "Descripcion", "Stock", "Precio"] cont = 0; for col in columnas: if cont == 0: pdf.cell(12, 10, col, 1, 0, "C") else: if cont == 1: pdf.cell(50, 10, col, 1, 0, "C") else: if cont == 2: pdf.cell(100, 10, col, 1, 0, "C") else: pdf.set_font("Helvetica", "B", size=14) pdf.cell(15, 10, col, 1, 0, "C") cont = cont + 1; pdf.ln() pdf.set_font("Helvetica", size=12) while recorrer != None: cod = str(listarep.get_value(recorrer, 2)) nombre = listarep.get_value(recorrer, 0) descripcion = listarep.get_value(recorrer, 1) stock = str(listarep.get_value(recorrer, 4)) precio = str(listarep.get_value(recorrer, 3)) pdf.cell(12, 10, cod, 1, 0, "R") pdf.cell(50, 10, nombre, 1, 0, "L") pdf.cell(100, 10, descripcion, 1, 0, "L") pdf.cell(15, 10, stock, 1, 0, "R") pdf.cell(15, 10, precio, 1, 0, "R") pdf.ln() recorrer = listarep.iter_next(recorrer) lista = "/home/daniel/workspace/taller/listas/listarepuestos.pdf" pdf.output(lista, "F") os.system('/usr/bin/evince ' + str(lista) + ' &')
def label_with_info(self, serial, f_list, username, old, new): pdf = FPDF(format=(80,65), unit='mm') pdf.add_page() # put barcode here self.create_barcode(serial) pdf.image('barcode.png', x=0, y=0, h=30) # barcodes print out with height of 280px. pdf.set_font('Arial', '', 12) pdf.ln(21) pdf.cell(21, 4, "Added " + time.strftime("%c"),0,2) pdf.cell(80, 4, "Created: " + old,0,2) pdf.cell(80, 4, "Modified: " + new,0,2) #pdf.set_font('Arial', '', 12) #pdf.cell(30, 10, "created: " + old + ", modified: " + new, ln=1) pdf.output('barcodes/label.pdf') self.print_barcode('barcodes/label.pdf')
def group_label(self, group_id, name, location, notes): pdf = FPDF(format=(80,65), unit='mm') pdf.set_margins(5, 5) pdf.add_page() self.create_barcode(group_id) pdf.image('barcode.png', x=0, y=0, h=30) pdf.set_font('Arial', '', 14) pdf.cell(30) pdf.cell(40,0, location, 0, 2) pdf.ln(10) pdf.cell(30) pdf.cell(21, 4, str(group_id) + ": " + name, 0, 1) pdf.ln(10) pdf.set_font('Arial', '', 8) pdf.multi_cell(0, 5, notes, 0, 2) pdf.output('barcodes/group_label.pdf') self.print_barcode('barcodes/group_label.pdf')
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 14) pdf.ln(10) if nostamp: data = "TEST-TEST-TEST" else: data = sys.version #áéíóúüñ # This string converted with errors in py2.x pdf.write(5, ('hello world %s áéíóúüñ' % data)) pdf.output(outputname, 'F')
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 14) pdf.ln(10) if nostamp: data = "TEST-TEST-TEST" else: data = sys.version pdf.write(5, 'hello world %s' % data) pdf.image("../tutorial/logo.png", 50, 50) pdf.image("flower2.jpg", 100, 50) pdf.image("lena.gif", 50, 75) pdf.output(outputname, 'F')
def listarImprimir(request): lineas = TOTAL_LINEAS_PDF fecha = datetime.date.today() now = datetime.datetime.now() nombre = "Carta_Boru_"+str(fecha)+'.pdf' pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'BU', 25) pdf.image(RUTA_PROYECTO + "\\" + STATIC_URL + "img\\boru_logo_pdf.png", 13, 13, 52, 23, type='PNG') pdf.cell(0, 30, 'Carta Boru', 0, 1, 'C') pdf.ln(10) lineas = lineas - 4 secciones = SeccionCarta.objects.filter().order_by("categoria") for seccion in secciones: if not seccion.es_vacia_seccion(): if (lineas - 3) <= 0: pdf.add_page() lineas = TOTAL_LINEAS_PDF lineas = lineas - 3 pdf.set_font('Arial', 'UB', 20) pdf.cell(0, 10, str(seccion.nombre).capitalize(), 0, 1, 'L') pdf.ln() productos = seccion.dame_productos() for p in productos: if p.activo ==True: if (lineas - 2) <= 0: pdf.add_page() lineas = TOTAL_LINEAS_PDF - 3 pdf.set_font('Arial', 'UB', 20) pdf.cell(0, 10, str(seccion.nombre).capitalize(), 0, 1, 'L') pdf.ln() lineas= lineas -2 pdf.set_font('Arial', 'B', 16) pdf.cell(75, 10, str(p.nombre).capitalize(), 0, 0) pdf.set_font('Arial', 'B', 16) pdf.cell(90, 10, "........................................................", 0, 0, "L") pdf.set_font('Arial', 'B', 16) pdf.cell(25, 10, '$' + str(p.importe()), 0, 0, "L") pdf.ln() pdf.ln() lineas = lineas -1 return HttpResponse(pdf.output(name=nombre,dest='S'),content_type='application/pdf')
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 14) pdf.ln(10) if nostamp: data = "TEST-TEST-TEST" else: data = sys.version pdf.write(5, 'hello world %s' % data) path = os.path.join(common.basepath, os.pardir, "tutorial", "logo.png") pdf.image(path, 50, 50) pdf.image(os.path.join(common.basepath, "flower2.jpg"), 100, 50) pdf.image(os.path.join(common.basepath, "lena.gif"), 50, 75) pdf.output(outputname, 'F')
def on_bimprimirclientes_clicked(self, widgets): listaclientes = self.interface.get_object("lista") recorrer = listaclientes.get_iter_first() pdf = FPDF() pdf.add_page() pdf.set_font("Helvetica", "B", size=16) pdf.cell(110, 10, "Listado de clientes", 0, 0) pdf.cell(25, 10, "Talleres cuspedrinos", 0, 1) pdf.cell(110, 10, "", 0, 0) pdf.cell(25, 10, "Tel. 555555555", 0, 1) pdf.cell(110, 10, " ", 0, 0) now = datetime.datetime.now() fecha = now.strftime("%Y-%m-%d %H:%M") pdf.cell(25, 10, str(fecha), 0, 1) pdf.image('/home/daniel/workspace/taller/img/tallerlogo.jpg', x=70, y=2, w=40, h=50, type='jpg') columnas = ["Cod", "Nombre", "NIF", "Telefono"] cont = 0; for col in columnas: if cont == 0: pdf.cell(20, 10, col, 1, 0, "C") else: if cont == 1: pdf.cell(100, 10, col, 1, 0, "C") else: pdf.cell(35, 10, col, 1, 0, "C") cont = cont + 1; pdf.ln() pdf.set_font("Helvetica", size=14) while recorrer != None: cod = str(listaclientes.get_value(recorrer, 0)) nombre = listaclientes.get_value(recorrer, 1) + " " + listaclientes.get_value(recorrer, 2) dni = listaclientes.get_value(recorrer, 3) telefono = listaclientes.get_value(recorrer, 9) pdf.cell(20, 10, cod, 1, 0, "R") pdf.cell(100, 10, nombre, 1, 0, "L") pdf.cell(35, 10, dni, 1, 0, "R") pdf.cell(35, 10, telefono, 1, 0, "R") pdf.ln() recorrer = listaclientes.iter_next(recorrer) lista = "/home/daniel/workspace/taller/listas/listaclientes.pdf" pdf.output(lista, "F") os.system('/usr/bin/evince ' + str(lista) + ' &')
def save_file(): filename = request.values['filename'] contents = request.values['contents'] fname = os.path.join(app.config['UPLOAD_FOLDER'], filename) backup_path = os.path.join(app.config['BACKUP_FOLDER'], filename) shutil.copy2(fname, backup_path) exten = fname.split('.')[1] if exten != 'pdf' : f = open(fname, 'w') f.write(contents) f.close() else: pdf=FPDF('P', 'mm',(500,400)) pdf.add_page() pdf.set_font('Courier','B',16) for line in contents.split("\n"): pdf.cell(40,10,line) pdf.ln(h='') pdf.output(fname,'F') return redirect(url_for('list'))
def test_greek_letters(self): pdf=FPDF() initPDF(pdf) setFontPDF(pdf,'symbol') p = lp.ListParser( lp.CommandParser(lp.ParagraphItemCreator) ) s = r'\alpha\beta\gamma' p.match( s ) self.assertTrue( p.hasMatch() ) res = p[0].docItem.writePDF()+' '+p[1].docItem.writePDF()+' '+p[2].docItem.writePDF() self.assertEquals( res, u'\u03b1 \u03b2 \u03b3') pdf.write(0, res) pdf.add_font('djv','','font/DejaVuSans.ttf',uni=True) pdf.set_font('djv','',12) pdf.write(0, u' \u23a8 \u23a7 \u23a9 \u23aa \u239e \u2320 \u2321 \u23ae') pdf.ln(10) pdf.add_font('smb','','font/Symbola.ttf',uni=True) pdf.set_font('smb','',12) pdf.write(0, u' \u23b7 \u03b1 \u03b2 \u03b3') pdf.ln(10) pdf.add_font('jax','','font/mathjax_amsregular.ttf',uni=True) pdf.set_font('jax','',12) pdf.write(0, u' abc \u23b7 \u03b1 \u03b2 \u03b3') pdf.ln(10) pdf.add_font('jax','','font/MathJax/ttf/mathjax_size1regular.ttf',uni=True) pdf.set_font('jax','',12) pdf.write(0, u' abc \u23b7 \u03b1 \u03b2 \u03b3') pdf.output('out/latex/test_greek_letters.pdf', 'F')
def print_file(title, data): (f, fname) = tempfile.mkstemp(text=True) pdf = FPDF('L', unit='mm', format=(112, 100)) pdf.add_page() pdf.set_font('Arial', '', 8) pdf.cell(0, 10, data['newTicketTime'], 0, 1) pdf.ln() pdf.ln() pdf.set_font('Arial', 'B', 128) pdf.cell(0, 10, data['newTicketValue'], 0, 1, 'C') pdf.set_font('Arial', '', 18) pdf.ln() pdf.cell(0, 10, data['description'].encode('cp1252', 'ignore'), 0, 1, 'C') qr = qrcode.QRCode(box_size=3) link = 'http://q.foi.hr/view?id=' + str(data['id']) qr.add_data(link) qr.make(fit=True) img = qr.make_image() (qf, qfname) = tempfile.mkstemp(suffix='.png') img.save(qfname, 'PNG') pdf.image(qfname) pdf.set_font('Arial', '', 10) pdf.text(47, 87, link) pdf.output(fname) job = CUPS.printFile(PRINTER_NAME, fname, title, {}) while job in CUPS.getJobs(which_jobs='not-completed').keys(): time.sleep(2) os.unlink(fname) os.unlink(qfname)
def dotest(outputname, nostamp): pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.add_font('DejaVu', '', os.path.join(common.basepath, 'font/DejaVuSansCondensed.ttf'), uni = True) pdf.set_font('DejaVu', '', 14) # Note: this line cause syntax error in Python 3.0-3.2 text = u""" Veľké písmená A Á Ä B C Č D Ď DZ DŽ E É F G H CH I Í J K L Ĺ Ľ Malé písmená a á ä b c č d ď dz dž e é f g h ch i í j k l ĺ ľ Veľké písmená M N Ň O Ó Ô P Q R Ŕ S Š T Ť U Ú V W X Y Ý Z Ž Malé písmená m n ň o ó ô p q r ŕ s š t ť u ú v w x y ý z ž """ pdf.write(8, text) pdf.ln(8) pdf.output(outputname, 'F')
def issue_cheque(name, amount): """ Print salary and payment cheques with worker_ID Print hall payment cheques with hall_ID """ pdf = FPDF('P', 'mm', 'A4') pdf.add_page('P') pdf.set_font('Times', 'B', 14) pdf.multi_cell(0, 5, 'Cheque Payment System') pdf.ln() pdf.multi_cell(0, 5, ('Pay: %s' % name)) pdf.ln() pdf.multi_cell(0, 5, ('The amount of: Rs. %s' % str(amount))) pdf.ln() pdf.multi_cell(0, 5, ('Issued on: %s' % str(time.strftime("%d/%m/%Y")))) pdf.ln() # Write generated output file to PDF pdf.output(('cheque_%s.pdf' % name), 'F')
def pdf(query, title): pdf=FPDF(format='letter', unit='in') pdf.add_page() pdf.set_font('Times','',7.0) epw = pdf.w - 2*pdf.l_margin col_width = epw/4 pdf.set_font('Times','B',14.0) pdf.cell(epw, 0.0, title, align='C') pdf.set_font('Times','',10.0) pdf.ln(0.5) th = pdf.font_size for row in query: for datum in row: pdf.cell(col_width, th, str(datum), border=1) pdf.ln(th) pdf.ln(4*th) return pdf.output('reporte.pdf','F')
def create_qc_pdf(**kwargs): try: kwargs['company'] = kwargs.get('company', u'台茂化工儀器原料行') kwargs['product'] = kwargs.get('product', u'product name?') kwargs['ASE_pn'] = kwargs.get('ASE_pn', u'ASE PN?') if not kwargs.get('lot_no'): kwargs['make_date'] = date.today() kwargs['test_date'] = date.today() kwargs['lot_no'] = u'lot number?' else: year = 2000 + int(kwargs['lot_no'][1:3]) month = int(kwargs['lot_no'][3:5]) day = int(kwargs['lot_no'][5:7]) kwargs['make_date'] = date(year, month, day) kwargs['test_date'] = date(year, month, day) kwargs['exp_period'] = kwargs.get('exp_period', u'一年') kwargs['amount'] = kwargs.get('amount', u'amount?') kwargs['tester'] = kwargs.get('tester', u'tester?') kwargs['test_params'] = kwargs.get('test_params', []) except Exception as e: print e return # Set placement and style of values tm_branch = dict(x=30, y=25, w=178-30, h=10, align='C') product_name = dict(x=31, y=50, w=104-31, h=15, align='L') product_ASE_pn = dict(x=105, y=50, w=104-31, h=15, align='L') make_date = dict(x=31, y=65, w=104-31, h=8, align='L') test_date = dict(x=31, y=73, w=104-31, h=8, align='L') exp_period = dict(x=31, y=81, w=104-31, h=9, align='L') lot_no = dict(x=105, y=65, w=104-31, h=8, align='L') amount = dict(x=105, y=73, w=104-31, h=8, align='L') tester = dict(x=105, y=81, w=104-31, h=9, align='L') # Create PDF FPDF = myPDF('P','mm','A4') FPDF.set_compression(False) FPDF.set_creator('TM_2014') FPDF.set_title(u'Quality inspection report for lot# {}'.format(kwargs['lot_no'])) FPDF.set_author(u'Taimau Chemicals') FPDF.set_subject(kwargs['lot_no']) # FPDF.set_subject(u'{} {}'.format(kwargs['product'], kwargs['lot_no']), isUTF8=True) FPDF.alias_nb_pages() FPDF.add_page() # Adding a page also creates a page break from last page FPDF.add_font(family=u'SimHei', style='', fname=font, uni=True) # Only .ttf and not .ttc FPDF.set_font(family=u'SimHei', style='', size=16) FPDF.xycell(txt=kwargs['company'], **tm_branch) FPDF.set_font(family=u'SimHei', style='B', size=13) FPDF.xycell(txt=u'產品: {}'.format(kwargs['product']), **product_name) FPDF.xycell(txt=u'料號: {}'.format(kwargs['ASE_pn']), **product_ASE_pn) FPDF.xycell(txt=u'製造日期: {}'.format(kwargs['make_date']), **make_date) FPDF.xycell(txt=u'檢驗日期: {}'.format(kwargs['test_date']), **test_date) FPDF.xycell(txt=u'保存期間: {}'.format(kwargs['exp_period']), **exp_period) FPDF.xycell(txt=u'批號: {}'.format(kwargs['lot_no']), **lot_no) FPDF.xycell(txt=u'生產數量: {}'.format(kwargs['amount']), **amount) FPDF.xycell(txt=u'取樣人員: {}'.format(kwargs['tester']), **tester) FPDF.set_left_margin(30) FPDF.set_xy(x=30, y=105) for (a, b, c) in kwargs['test_params']: if a+b+c == u'': break FPDF.cell(49, 10, txt=a, align='C') FPDF.cell(49, 10, txt=b, align='C') FPDF.cell(49, 10, txt=c, align='C') FPDF.ln() FPDF.cell(49) FPDF.cell(49, 10, txt=u'以下空白', align='C') initialfilename = u'QC_{}_{}'.format(kwargs['product'], kwargs['lot_no']) FILE_OPTS = dict( title = u'PDF name and location.', defaultextension = '.pdf', initialdir = os.path.expanduser('~') + '/Desktop/', initialfile = initialfilename, ) if settings.load().get(u'pdfpath'): FILE_OPTS['initialdir'] = settings.load()[u'pdfpath'] outfile = os.path.normpath(tkFileDialog.asksaveasfilename(**FILE_OPTS)) if os.path.exists(outfile): os.remove(outfile) if outfile and not os.path.exists(outfile): FPDF.output(name=outfile) try: subprocess.call(['start', outfile], shell=True) return except: pass try: print u'Trying alternate subprocess command.' subprocess.call(['start', '/D'] + list(os.path.split(outfile)), shell=True) return except UnicodeEncodeError: pass try: os.startfile(outfile) return except: pass print u'Failed to autoload PDF after creation.' return else: head = u'Cancelled' body = u'Canceled PDF creation.' tkMessageBox.showinfo(head, body)
pdf.add_page() #Adicionando configurações de Fonte pdf.set_font('Arial','B',16) #Inserindo linhas cell by cell. pdf.cell(0,10,'CONTRATO DE LOCAÇÃO RESIDENCIAL', 1,1 , 'C') #Locador pdf.set_font('Arial','I',8) pdf.cell(33,5,'LOCADOR(A):',1,1 , 'L') pdf.cell(0,5,'..................................., brasileiro, solteiro, comerciante,', 0,1 , 'J') pdf.cell(0,5,'portador da cédula de identidade RG ....................../SSP.SP e inscrito no CPFMF sob nº ................', 0,1 , 'J') #Locatario pdf.cell(33,5,'LOCATÁRIO(A):',1,1 , 'L') pdf.cell(0,5,'................................................, brasileiro, casado, autônomo,', 0,1 , 'J') pdf.cell(0,5,', portador da cédula de identidade RG .................SSP/SP e inscrito no CPFMF sob nº ................... ', 0,1 , 'J') pdf.ln(5) #Objeto pdf.set_font('Arial','B',8) pdf.cell(0,5,'OBJETO:',1,1 , 'L') pdf.set_font('Arial','',9) pdf.cell(0,5,'A CASA SOB Nº ....., DA RUA ............................., ou A UNIDADE RESIDENCIAL SOB N ....., SITIO NA RUA', 0,1 ,'') pdf.cell(0,5,' ............. N ...,,0,1,'') pdf.ln(5) #-- pdf.set_font('Arial','I',8) pdf.cell(0,5,'Por este particular instrumento, as partes supraqualificadas resolvem, de comum acordo e de livre e espontânea',0,1,'L') pdf.cell(0,5,' vontade, firmar um Contrato de Locação, tendo por objeto o imóvel declinado no preâmbulo, a reger-se pelas se',0,1,'L') pdf.cell(0,5,'guintes cláusulas e condições',0,1,'L') pdf.ln(1) #Primeira pdf.set_font('Arial','',8)
layout = device.get_result() print str(page.doc._cached_objs) data2 = [] images = [] for obj in layout: sub_data, sub_images = parse_lt_objs(obj, page_count) data2 += sub_data images += sub_images print "Page " + str(page_count) + ", images: " + str(len(images)) print " got return: \n" + "\n".join(data2) pdf.add_page() pdf.write(14, "PAGE: " + str(page_count)) pdf.ln(2) new_page = data2 # filter_lines(data2) # print "Page " + str(page_count) # print "Result: " + "\n".join(new_page) for line in new_page: pdf.write(font_size, line) pdf.ln(font_size / 2) page_count += 1 if page_count == 3: break device.close() pdf.output(options.out_file, "F")
from fpdf import FPDF #font_file_name = 'font/mathjax_amsregular.ttf' font_file_name = 'font/MathJax/ttf/mathjax_size4regular.ttf' size = 10 pdf = FPDF() pdf.add_page() pdf.add_font('jax','',font_file_name,uni=True) lb = 0 for n in range(0xeffc): c = unichr(n) pdf.set_font('jax','',size) w = pdf.get_string_width(c) if w > 0: pdf.set_font('times','',size) pdf.cell(13, 10, hex(n) + ': ' ) pdf.set_font('jax','',size) pdf.cell(10, 10, c) if lb == 6: pdf.ln(10) lb = 0 else: lb += 1 #print unichr(i) pdf.output('out/latex/font_view.pdf', 'F') print 'done'
def novoVenda( nomeVend, naturalidadeVend, estadoCivilVend, profissaoVend, rgVend, cpfVend, ruaVend, numVend, bairroVend, cepVend, cidadeVend, estadoVend, nomeComp, naturalidadeComp, estadoCivilComp, profissaoComp, rgComp, cpfComp, ruaComp, numComp, bairroComp, cepComp, cidadeComp, estado, area, registro, valor, ): # Definindo o formato do PDF pdf = FPDF("P", "mm", "A4") # Definindo as margens pdf.set_margins(10, 10, 10) # Adicionando página pdf.add_page() # Adicionando configurações de Fonte pdf.set_font("Arial", "B", 16) # Inserindo linhas cell by cell. contrato = "CONTRATO E COMPROMISSO DE COMPRA E VENDA DE IMÓVEL" utxt1 = unicode(contrato, "UTF-8") stxt1 = utxt1.encode("iso-8859-1") pdf.cell(0, 10, stxt1, 1, 1, "C") pdf.ln(10) # Dados pessoais das partes interessadas pdf.set_font("Arial", "", 8) vendedor = ( "PROMITENTE VENDEDOR: " + nomeVend + ", nascido em " + naturalidadeVend + ", " + estadoCivilVend + "," + profissaoVend + ",portador do R.G. nº " + rgVend + " ," ) vendedor += ( " e CPF/MF nº " + cpfVend + " residente e domiciliado à " + ruaVend + ", " + numVend + ", " + bairroVend + ", " + cepVend + ", " + cidadeVend + ", " + estadoVend + "." ) utxt2 = unicode(vendedor, "UTF-8") stxt2 = utxt2.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt2, 0, "J") pdf.ln(1) comprador = ( "PROMITENTE COMPRADOR: " + nomeComp + ", " + naturalidadeComp + ", " + estadoCivilComp + ", " + profissaoComp + ", portador do R.G. nº " + rgComp + "," ) comprador += ( " e CPF/MF nº " + cpfComp + " residente e domiciliado à " + ruaComp + ", " + numComp + ", " + bairroComp + ", " + cepComp + ", " + cidadeComp + ", " + estado + "." ) utxt3 = unicode(comprador, "UTF-8") stxt3 = utxt3.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt3, 0, "J") pdf.ln(5) pdf.set_font("Arial", "B", 10) clausulas = "Têm entre os mesmos, de maneira justa e acordada, o presente contrato particular de compromisso de compra e venda de bem imóvel, ficando desde já aceito, pelas cláusulas abaixo descritas:" utxt4 = unicode(clausulas, "UTF-8") stxt4 = utxt4.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt4, 0, "J") pdf.ln(3) pdf.set_font("Arial", "", 8) pdf.ln(1) primeira = "CLÁUSULA PRIMEIRA:" utxt5 = unicode(primeira, "UTF-8") stxt5 = utxt5.encode("iso-8859-1") pdf.cell(33, 5, stxt5, 1, 1, "L") pdf.ln(1) clausulaPrimeira = ( "Que a PROMITENTE VENDEDORA é legítima possuidora do imóvel composto por área privativa de " + area + " metros quadrados, " ) clausulaPrimeira += ( "inscrito no livro de registro de imóveis sob nº " + registro + ", com as seguintes confrontações:" ) utxt6 = unicode(clausulaPrimeira, "UTF-8") stxt6 = utxt6.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt6, 0, "J") pdf.ln(2) segunta = "CLÁUSULA SEGUNDA:" utxt7 = unicode(segunta, "UTF-8") stxt7 = utxt7.encode("iso-8859-1") pdf.cell(33, 5, stxt7, 1, 1, "L") pdf.ln(1) clausulaSegunda = ( "O valor da presente transação é feita pelo preço de R$ " + valor + ", que serão pagos de acordo com o que as partes acharem cabíveis." ) utxt8 = unicode(clausulaSegunda, "UTF-8") stxt8 = utxt8.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt8, 0, "J") pdf.ln(2) terceira = "CLÁUSULA TERCEIRA:" utxt9 = unicode(terceira, "UTF-8") stxt9 = utxt9.encode("iso-8859-1") pdf.cell(33, 5, stxt9, 1, 1, "L") pdf.ln(1) clausulaTerceira = "Que o PROMITENTE VENDEDOR se compromete a entregar o imóvel livre e desembaraçado de todos os débitos até esta data, junto ao Agente Financeiro" clausulaTerceira += ", ficando daí a responsabilidade do PROMITENTE COMPRADORE o pagamento mensal da prestação." utxt10 = unicode(clausulaTerceira, "UTF-8") stxt10 = utxt10.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt10, 0, "J") pdf.ln(2) quarta = "CLÁUSULA QUARTA:" utxt11 = unicode(quarta, "UTF-8") stxt11 = utxt11.encode("iso-8859-1") pdf.cell(33, 5, stxt11, 1, 1, "L") pdf.ln(1) clausulaQuarta = "Fica acordado entre o PROMITENTE VENDEDOR e PROMITENTE COMPRADOR que o imóvel transacionado permanecerá em nome do PROMITENTE VENDEDOR por " clausulaQuarta += "prazo indeterminado, ficando o PROMITENTE VENDEDOR obrigado a apresentar os documentos necessários para transrência a partir do momento em que " clausulaQuarta += "o mesmo for notificado pelo PROMITENTE COMPRADOR a qualquer época. " utxt12 = unicode(clausulaQuarta, "UTF-8") stxt12 = utxt12.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt12, 0, "J") pdf.ln(2) quinta = "CLÁUSULA QUINTA:" utxt13 = unicode(quinta, "UTF-8") stxt13 = utxt13.encode("iso-8859-1") pdf.cell(33, 5, stxt13, 1, 1, "L") pdf.ln(1) clausulaQuinta = "Todos os compromissos assumidos neste contrato são de caráter irrevogável e irrefratével, obrigado as partes, seus herdeiros e sucessores a qualquer" clausulaQuinta += "título fazer sempre boa e valiosa a presente cessão, ficando sujeito às penalidades da lei." utxt14 = unicode(clausulaQuinta, "UTF-8") stxt14 = utxt14.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt14, 0, "J") pdf.ln(2) sexta = "CLÁUSULA SEXTA:" utxt15 = unicode(sexta, "UTF-8") stxt15 = utxt15.encode("iso-8859-1") pdf.cell(33, 5, stxt15, 1, 1, "L") pdf.ln(1) clausulaSexta = "Fica ainda acordando, que caso haja necessidade de se beneficiar do seguro referente ao imóvel,os beneficiados será o PROMITENTE COMPRADOR,ou filhos." utxt16 = unicode(clausulaSexta, "UTF-8") stxt16 = utxt16.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt16, 0, "J") pdf.ln(2) setima = "CLÁUSULA SÉTIMA:" utxt17 = unicode(setima, "UTF-8") stxt17 = utxt17.encode("iso-8859-1") pdf.cell(33, 5, stxt17, 1, 1, "L") pdf.ln(1) clausulaSetima = "Em caso de falecimento do PROMITENTE VENDEDOR ,fica acordando entre as partes que todo e qualquer benefício oriundo deste fato,transfere-se" clausulaSetima += "para o PROMITENTE COMPRADOR." utxt18 = unicode(clausulaSetima, "UTF-8") stxt18 = utxt18.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt18, 0, "J") pdf.ln(2) oitava = "CLÁUSULA OITAVA:" utxt19 = unicode(oitava, "UTF-8") stxt19 = utxt19.encode("iso-8859-1") pdf.cell(33, 5, stxt19, 1, 1, "L") pdf.ln(1) clausulaOitava = "Caso haja manifestação pública por parte do Agente Financeiro, quando à transferência do imóvel citado neste instrumento particular de compra" clausulaOitava += "venda, sem que haja o aumento das prestações fica acordo entre as partes a sua transferência." utxt20 = unicode(clausulaOitava, "UTF-8") stxt20 = utxt20.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt20, 0, "J") pdf.ln(2) nona = "CLÁUSULA NONA:" utxt21 = unicode(nona, "UTF-8") stxt21 = utxt21.encode("iso-8859-1") pdf.cell(33, 5, stxt21, 1, 1, "L") pdf.ln(1) clausulaNona = "O foro deste contrato é da Comarca de, renunciando as partes quaisquer outro por mais privilegiado que seja.E por estarem assim juntos e" clausulaNona += ( "contra assinam o presente em 03 (Três) vias de igual teor e forma, na presença das testemunhas abaixo." ) utxt22 = unicode(clausulaNona, "UTF-8") stxt22 = utxt22.encode("iso-8859-1") pdf.multi_cell(0, 5, stxt22, 0, "J") pdf.ln(3) pdf.cell(0, 10, "____________________________________________ _____ , _____ , _________", 0, 1, "C") pdf.ln(10) pdf.cell(0, 5, "PROMITENTE COMPRADOR:", 0, 1, "C") pdf.cell(0, 5, "__________________________________________________", 0, 1, "C") pdf.cell(0, 5, "PROMITENTE VENDEDOR:", 0, 1, "C") pdf.cell(0, 5, "__________________________________________________", 0, 1, "C") pdf.cell(0, 5, "TESTEMUNHA:", 0, 1, "C") pdf.cell(0, 5, "__________________________________________________", 0, 1, "C") pdf.cell(0, 5, "R.G.:", 0, 1, "C") pdf.cell(0, 5, "__________________________________________________", 0, 1, "C") pdf.cell(0, 5, "TESTEMUNHA:", 0, 1, "C") pdf.cell(0, 5, "__________________________________________________", 0, 1, "C") pdf.cell(0, 5, "R.G.:", 0, 1, "C") pdf.cell(0, 5, "__________________________________________________", 0, 1, "C") pdf.output("numero%s.pdf" % (registro), "F")
#Creo la pagina pdf.add_page() imgBandera = "Bandera.JPG" imgFondo = "FONDOCARNET.jpg" imgLogo = "HOSPITALC.JPG" imgFoto = '/media/serv_coromoto/NominaShc/FotosE/F0011951.jpg' apellidos = 'GARCIA DIAZ' nombres = 'CARLOS ALBERTO' #Agrego las Imagenes pdf.image(imgFondo, 0,0,55,85) pdf.image(imgBandera,0,10,60,10.5) pdf.ln(13) #Primer Texto y tipo de letra pdf.set_font('Arial', 'B', 7) pdf.set_text_color(255,0,0) pdf.cell(w=0,h=0,txt='REPUBLICA BOLIVARIANA DE VENEZUELA',border=0,ln=1,align='C') #Segundo Texto y tipo de letra pdf.set_font('Arial', 'B', 9) pdf.set_text_color(255,0,0) pdf.cell(w=0,h=7,txt='PDV SERVICIOS DE SALUD S.A.',border=0,ln=1,align='C') #Imagen del Logo pdf.image(imgLogo,5, 29, w=9, h=12) #Tercer Texto y tipo de letra pdf.set_font('Arial', 'B', 12)
for dato in data: if dato['classificazione'] == "Alberghi 2 stelle": denominazione = dato['denominazione_struttura'] if 'indirizzo' in dato: indirizzo = dato['indirizzo'] if 'cap' in dato: comune = dato['cap'] + " " + dato['nome_comune'] + "(" + dato['provincia'] + ")" print(denominazione) if 'indirizzo' in dato: print(indirizzo) if 'cap' in dato: print(comune) print("") pdf.add_page() ## generate pages from loop pdf.set_font('Arial', 'B', 16) pdf.cell(200, 20, "Spett.le:") pdf.ln(7) pdf.cell(200, 20, denominazione) if 'indirizzo' in dato: if dato['indirizzo'].decode('utf8'): pdf.ln(7) pdf.cell(200, 20, indirizzo, 'L') if 'cap' in dato: pdf.ln(7) pdf.cell(200, 20, comune, 'L') # save pdf pdf.output('Alberghi_2_stelle.pdf', 'F')
files.sort() for file in files: if os.path.islink("out/switches/" + file) or file.endswith("~"): continue with open("out/switches/" + file, "r") as f: label = f.read().strip() label = label.replace("TenGigabitEthernet", "Te") label = label.replace("GigabitEthernet", "Gi") label = label.replace("FastEthernet", "Fa") label = label.replace("Ethernet", "Eth") col += 1 if (col >= cols): pdf.ln() col = 0 row += 1 if (row >= rows): pdf.add_page() row = 0 cellx = leftmargin + (col * (cellwidth + cellgapx)) celly = topmargin + (row * (cellheight + cellgapy)) pdf.set_font('Helvetica', '', 8.5) if debug: pdf.set_xy(cellx, celly) pdf.cell(cellwidth, cellheight, "", border=1, align="C")
def dotest(outputname, nostamp): plane = genbar() palette = (0,0,0, 255,255,255) + (128,128,128)*254 try: img = Image.frombytes("P", plane.size, plane.tobytes()) except AttributeError: # note: https://github.com/python-pillow/Pillow/issues/63 img = Image.fromstring("P", plane.size, plane.tostring()) img.putpalette(palette) with tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") as f: gif1 = f.name with tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") as f: gif2 = f.name img.save(gif1, "GIF", optimize = 0) img.save(gif2, "GIF", transparency = 1, optimize = 0) pdf = FPDF() if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.add_page() pdf.set_font('Arial', '', 16) pdf.write(8, "Transparency") pdf.ln() pdf.write(8, " Transparency") pdf.ln() pdf.write(8, " Transparency") pdf.ln() pdf.image(gif1, x = 15, y = 15) pdf.write(8, "Transparency") pdf.ln() pdf.write(8, " Transparency") pdf.ln() pdf.write(8, " Transparency") pdf.ln() pdf.image(gif2, x = 15, y = 39) pdf.output(outputname, 'F') os.unlink(gif1) os.unlink(gif2)