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 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 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 write_to_pdf(data: dict, filename: str): pdf = FPDF() effective_page_width = pdf.w - 2 * pdf.l_margin pdf.compress = False pdf.add_page() pdf.add_font("TimesNewRoman", '', 'TimesNewRoman.ttf', uni=True) pdf.set_font("TimesNewRoman", size=30) pdf.cell(w=0, txt=data['title']) pdf.ln(30) pdf.set_line_width(1) pdf.set_draw_color(255, 0, 0) for index_news, news_dict in enumerate(data['items']): pdf.set_font("TimesNewRoman", size=20) pdf.line(20, pdf.get_y() - 10, effective_page_width, pdf.get_y() - 10) pdf.multi_cell(effective_page_width, 10, news_dict['title']) if news_dict['contain_image']: download_image_and_paste_in_pdf(pdf, news_dict, index_news) pdf.multi_cell(effective_page_width, 10, news_dict['published']) pdf.multi_cell(effective_page_width, 10, news_dict['summary'][news_dict['summary'].rfind(']') + 1:]) pdf.set_font("TimesNewRoman", size=15) pdf.ln(5) pdf.multi_cell(effective_page_width, 10, 'Link on news:\n' + news_dict['link']) if news_dict['contain_image']: pdf.multi_cell(effective_page_width, 10, 'Link on image:\n' + news_dict['link_on_image']) pdf.ln(40) try: pdf.output(filename, 'F') except PermissionError: raise RssReaderException.FileException(f'close file:\n{filename}')
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 generate_fidb_pdf(yt_video_title, yt_link, captions_blanks, solutions, RTL): ''' @summary: creates exercise pdf including link to video_title, exercise, and solution TODO: Handle language specific fonts https://pyfpdf.readthedocs.io/en/latest/Unicode/index.html ''' # create pdf alignment = "L" if RTL is False else "R" pdf = FPDF() # default: Portrait, A4, millimeter unit pdf.compress = 0 # pdf.set_right_margin(20) pdf.add_page() pdf.add_font('DejaVu', '', '{}/fonts/DejaVuSansCondensed.ttf'.format( os.path.dirname(os.path.realpath(__file__)) ), uni=True) # video title and fill in blanks on first page pdf.set_font('Arial', 'B', 14) pdf.cell(w=200, h=10, txt="Fill-in-the-blanks exercise!", ln=1, align="C") pdf.cell(w=200, h=10, txt="Watch the following video and fill in the blanks:", ln=1, align="C") # important!! keep dejavu font so that title can be outputted correctly! # dejavu has no bold style pdf.set_font("DejaVu", size=14) pdf.set_text_color(0, 0, 255) title_to_print = yt_video_title # todo: erase this fix, which limits to n letters if len(title_to_print) > 30: title_to_print = title_to_print[:30] + "..." print(yt_video_title) print(yt_video_title[:30]) # todo: add fix- cell should provide error if string width > cell width; can't use multicell, because multicell does not support http link pdf.cell(w=200, h=10, txt=title_to_print, link=yt_link, ln=1, align="C") pdf.set_text_color(0, 0, 0) pdf.set_font("DejaVu", size=12) pdf.multi_cell(w=0, h=10, border=1, txt=captions_blanks, align=alignment) # solutions on second page pdf.add_page() pdf.set_font("Arial", "B", size=14) pdf.cell(w=200, h=10, txt="Solution:", ln=1, align="C") pdf.set_font("DejaVu", size=12) pdf.multi_cell(w=0, h=10, border=1, txt=solutions, align=alignment) return pdf
def dotest(outputname, nostamp): pdf = FPDF(orientation="L", format="A5") pdf.compress = False if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.set_font('Arial', '', 14) for i in range(10): o = ["p", "L", "P", "l"][i % 4] page(pdf, "Page %d from 10\nOrientation: %s" % (i + 1, o), o) pdf.output(outputname, 'F')
def dotest(outputname, nostamp): pdf = FPDF(orientation = "L", format = "A5") pdf.compress = False if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.set_font('Arial', '', 14) for i in range(10): o = ["p", "L", "P", "l"][i % 4] page(pdf, "Page %d from 10\nOrientation: %s" % (i + 1, o), o) pdf.output(outputname, 'F')
def dotest(outputname, nostamp): pdf = FPDF(orientation = "L", format = (100, 250)) pdf.compress = False if nostamp: pdf._putinfo = lambda: common.test_putinfo(pdf) pdf.set_font('Arial', '', 14) for i in range(16): o = ["p", "l"][i % 2] f = ["a3", "a4", "a5", "letter", "legal", "", (100, 250), (320, 240)][i % 8] page(pdf, "Page %d from 16\nFormat: %s\nOrientation: %s" % (i + 1, f, o), o, f) pdf.output(outputname, 'F')
def group_imgs_by_name(file_name): # list_of_images = ["img/topic1-1.jpg", "img/topic1-2.jpg"] print("reading images:" + os.path.join(folder_img, file_name, '*.*')) list_of_images = sorted(glob(os.path.join(folder_img, file_name + '*.*')), key=os.path.getmtime) print(list_of_images) path = "" if len(list_of_images) > 0: pdf = FPDF(orientation='L') pdf.compress = False for image in list_of_images: pdf.add_page() pdf.image(image, w=250) path = os.path.join(folder_pdf, file_name + ".pdf") pdf.output(path, "F") print(folder_pdf + "/" + file_name + ".pdf" + ' converted') return path
def convert2PDF(image): img = Image.open(image) pdf = FPDF() # compression is not yet supported in py3k version pdf.compress = False pdf.add_page('L') pdf.image('images/imagens-de-amor-textos-romanticos-8.jpg', x=0, y=0, w=298, h=0) pdf.add_page('P') pdf.image('images/ex02.jpg', x=0, y=0, w=210, h=0) pdf.add_page() pdf.image(image, 0, 0) pdf.output('py3k.pdf', 'F')
def Output2PDF(PrunedParas, PDFFilePre): """ Function to convert the list of strings into PDF file """ Headline = TrimHeadLine(PrunedParas[0]) Time = PrunedParas[1] PDFFile = TrimHeadLine(PDFFilePre + Headline + ".pdf") 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', '', 12) pdf.ln(10) for l in range(len(PrunedParas)): pdf.write(5, PrunedParas[l]) pdf.write(5, "\n\n") # To pdf pdf.output(PDFFile, 'F') pdf.close() return Headline, Time, "Writing to PDF Good"
def merge_images_to_pdf(path_to_folder): #page_height = 3508 #height of A4 page page_height = 3508 #height of A4 page file_list = [] for image in os.listdir(path_to_folder): if "jpg" in image.split(".")[-1]: file_path = path_to_folder + "\\" + image img = cv2.imread(file_path) height, width, channels = img.shape file_list.append([file_path, height]) number_of_full_page = 1 number_of_pdf = 1 whole_pdf_file = FPDF() while (len(file_list)): actuall_len = 0 single_page = np.zeros((1, 2480, 3), np.uint8) while (len(file_list) and ((actuall_len + file_list[0][1]) < page_height)): actual_image = cv2.imread(file_list[0][0]) single_page = np.vstack((single_page, actual_image)) actuall_len += file_list[0][1] file_list = file_list[1:] tmp_img = path_to_folder + "\\" + str(number_of_full_page) + "tmp.jpg" cv2.imwrite(tmp_img, single_page) number_of_full_page += number_of_full_page #creating empty pdf file pdf_bytes = img2pdf.convert([tmp_img]) os.remove(tmp_img) whole_pdf_file.compress = False whole_pdf_file.add_page(orientation="Portrait") whole_pdf_file.output( path_to_folder + "\\" + os.path.basename(path_to_folder) + str(number_of_pdf) + ".pdf", "F") #fill above empty pdf with image file = open( path_to_folder + "\\" + os.path.basename(path_to_folder) + str(number_of_pdf) + ".pdf", "wb") file.write(pdf_bytes) number_of_pdf += number_of_pdf file.close()
def createPdf(): def randomString(): import string, secrets nonlocal password """Generate a random string of fixed length """ password_characters = string.ascii_letters + string.digits + string.punctuation password = ''.join( secrets.choice(password_characters) for _ in range(10)) from fpdf import FPDF message = request.get_json(force=True) pdf = FPDF() pdf.compress = True pdf.add_page() pdf.set_font('Arial', '', 14) pdf.ln(10) pdf.write(25, message['prediction']) print(pdf.output('py3k.pdf', 'F')) pdf.close() from PyPDF2 import PdfFileReader, PdfFileWriter with open("py3k.pdf", "rb") as in_file: password = 0 input_pdf = PdfFileReader(in_file) output_pdf = PdfFileWriter() output_pdf.appendPagesFromReader(input_pdf) email = des_ofb.ofb_decrypt(current_user.email, current_user.password_hash[:8], current_user.password_hash[24:32]) randomString() output_pdf.encrypt(password) out_file = open('encrypted_output.pdf', 'wb') out_file.seek(0) output_pdf.write(out_file) out_file.close() sender.SendMail().preapare_attatched_mail( email, "The password", "Open the file to see the password for pdf", password) return send_file("../encrypted_output.pdf", mimetype='application/pdf', as_attachment=True)
#!/usr/bin/env python # -*- coding: latin-1 -*- "Basic example to test py3k conversion" import sys from fpdf import FPDF pdf = FPDF() # compression is not yet supported in py3k version pdf.compress = False pdf.add_page() # unicode is not yet supported in py3k version, use windows-1252 standards font pdf.set_font('Arial','',14) pdf.ln(10) pdf.write(5, 'hello world %s αινσϊόρ' % sys.version) fn='py3knew.pdf' pdf.output(fn,'F') #import os #try: # os.startfile(fn) #except: # os.system("evince %s" % fn)
def print_Pdf(): obj_myDB = myDB() time_stamp, car_no, loc_name, fine_amount, email_id, verbose_string = "" mob_number = request.form['mob_number'] selected_function = request.form['number_code'] if (selected_function == "generate-pdf"): result = obj_myDB.fetch_record(mob_number) if (result == "Error while fetching record"): verbose_string = result return render_template('verbose-page.html', verbose_string) else: for row in result: time_stamp = row["TIME_STAMP"] car_no = row["CAR_NO"] loc_name = row["LOC_NAME"] fine_amount = row["FINE_AMOUNT"] violation_image = row["VIOLATION_IMAGE"] email_id = row["EMAIL_ID"] pdf_name = time_stamp, ".pdf" verbose_string = "PDF sent to Email Address:'", email_id, "," 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("Time Stamp/Unique Id: ", time_stamp, "\n") pdf.write("Car Number: ", car_no, "\n") pdf.write("Location: ", loc_name, "\n") pdf.write("Fine Amount: ", fine_amount, "\n") pdf.write("Image:\n", violation_image) pdf.image("pyfpdf/tutorial/logo.png", 50, 50) pdf.output(pdf_name, 'F') return render_template('verbose-page.html', verbose_string) elif (selected_function == "payment"): if (result == "Error while fetching record"): verbose_string = result return render_template('verbose-page.html', verbose_string) else: result = obj_myDB.fetch_record(mob_number) return render_template('payment.html', result)
f = tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") gif1 = f.name f.close() f = tempfile.NamedTemporaryFile(delete = False, suffix = ".gif") gif2 = f.name f.close() img.save(gif1, "GIF") img.save(gif2, "GIF", transparency = 1) pdf=FPDF() pdf.compress = False 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")
#!/usr/bin/env python # -*- coding: utf-8 -*- "Basic example to test py3k conversion" import sys from fpdf import FPDF pdf = FPDF() # compression also supported in py3k version pdf.compress = True pdf.add_page() # unicode is not yet supported in py3k version, use windows-1252 standards font pdf.set_font('Arial','',14) pdf.ln(10) pdf.write(5, u'hello world %s áéíóúüñ' % sys.version) pdf.image("../tutorial/logo.png", 50, 50) pdf.image("flower2.jpg", 100, 50) pdf.image("lena.gif", 50, 75) # Add a DejaVu Unicode font (uses UTF-8) # Supports more than 200 languages. For a coverage status see: # http://dejavu.svn.sourceforge.net/viewvc/dejavu/trunk/dejavu-fonts/langcover.txt pdf.add_font('DejaVu','','DejaVuSansCondensed.ttf',uni=True) pdf.set_font('DejaVu','',14) pdf.ln(10) pdf.write(8, u"Hello world in Russian: Здравствуй, Мир") fn='py3k.pdf' pdf.output(fn,'F') import os
#!/usr/bin/env python # -*- coding: utf-8 -*- "Basic example to test py3k conversion" import sys from fpdf import FPDF pdf = FPDF() # compression also supported in py3k version pdf.compress = True pdf.add_page() # unicode is not yet supported in py3k version, use windows-1252 standards font pdf.set_font('Arial', '', 14) pdf.ln(10) pdf.write(5, u'hello world %s áéíóúüñ' % sys.version) pdf.image("../tutorial/logo.png", 50, 50) pdf.image("flower2.jpg", 100, 50) pdf.image("lena.gif", 50, 75) # Add a DejaVu Unicode font (uses UTF-8) # Supports more than 200 languages. For a coverage status see: # http://dejavu.svn.sourceforge.net/viewvc/dejavu/trunk/dejavu-fonts/langcover.txt pdf.add_font('DejaVu', '', 'DejaVuSansCondensed.ttf', uni=True) pdf.set_font('DejaVu', '', 14) pdf.ln(10) pdf.write(8, u"Hello world in Russian: Здравствуй, Мир") fn = 'py3k.pdf' pdf.output(fn, 'F') import os