# ./gen-switch.py --generate --template labels # Then generate the labels: # ./gen-labels.py import os from fpdf import FPDF pdf = FPDF(orientation='P', unit='mm', format='A4') leftmargin = 4.75 rightmargin = 4.75 topmargin = 6 pdf.set_margins(leftmargin, topmargin, rightmargin) pdf.set_auto_page_break(False) rows=5 cols=2 cellwidth=99 cellheight=57 cellgapx=2.5 cellgapy=0 col = -1 row = 0 debug = False pdf.add_page() files = os.listdir("out/switches/")
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 makecards(cards): pdf = FPDF('P', 'mm', (WIDTH, HEIGHT)) pdf.set_left_margin(3.0) pdf.set_right_margin(3.0) pdf.set_top_margin(3.0) # Load our font and then use it pdf.add_font('BebasNeue', 'B', os.path.expanduser('~/gangserver-assets/BebasNeue.ttf'), uni=True) pdf.set_auto_page_break(auto=False) for card in cards: pdf.add_page() # Logo pdf.set_y(10) pdf.image(os.path.expanduser('~/gangserver-assets/logo.png'), w=LOGO, x=((WIDTH - LOGO) / 2)) # Name, in a bigger font pdf.set_font('BebasNeue', 'B', 20) pdf.set_y(LOGO + 15) if card['Preferred name'] != '': pdf.multi_cell(w=0, h=6, border=0, align='C', txt=card['Preferred name']) else: pdf.multi_cell(w=0, h=6, border=0, align='C', txt=card['Firstname']) pdf.set_y(LOGO + 23) pdf.multi_cell(w=0, h=6, border=0, align='C', txt=card['Last name']) # Team, in a smaller font pdf.set_y(LOGO + 35) pdf.set_font('BebasNeue', 'B', 12) pdf.multi_cell(w=0, h=6, border=0, align='C', txt=card['Team']) # Icons if card['Health'] == 'Yes': pdf.image( os.path.expanduser('~/gangserver-assets/icon_medical.png'), w=8, x=(WIDTH - 8) / 2, y=75) handle, filename = tempfile.mkstemp(dir='gangserver/local', suffix='.pdf') os.close(handle) pdf.output(filename, 'F') return filename
def chaptersToPDF(manga, mangaPath, mapPath): Paths = ast.literal_eval(open(mapPath, 'r').read()) errorPages = [] map = [] # the manga's folder on the desktop if False if os.path.isdir(mangaPath + 'ch/') else True: os.mkdir(mangaPath + 'ch/') for chapter in Paths: chapterwidth = [] chapterheight = [] for image in chapter[1:]: chapterwidth.append(Image.open(image).size[0]) chapterheight.append(Image.open(image).size[1]) pdf = FPDF('P', 'mm', (statistics.median(chapterwidth), statistics.median(chapterheight))) pdf.set_auto_page_break(0) for image in chapter[1:]: if path.exists(image): pdf.add_page() try: pdf.image(image, 0, 0, statistics.median(chapterwidth), statistics.median(chapterheight)) except: print(image) else: errorPages.append(image) pdf.output(mangaPath + 'ch/' + chapter[0][0] + '.pdf', 'F') map.append(mangaPath + 'ch/' + chapter[0][0] + '.pdf') print( str(int(chapter[0][1] / Paths[-1][0][1] * 100)) + '% ' + chapter[0][0] + '.pdf') open(mapPath, 'w').write(str(map))
def CreatePDF(copy_count): file_name = "question.txt" nameval_file = "NameVal.txt" header_data = ReadNameValFile(nameval_file) q_list = ReadQFile(file_name) for i in range(0, copy_count): pdf = FPDF() count = 1 pdf.add_page() pdf.set_title("Ranbir Roshan") #no effect pdf.set_subject("Ranbir Subject") #no effect pdf.set_author("Author Ranbir") pdf.set_auto_page_break('auto') pdf.set_creator("Ranbir Creator") PrintHeader(pdf, header_data) pdf.set_font("Arial", size=header_data.NormalLineFontSize) if (header_data.RandomQuestionOrder == "TRUE"): random.shuffle(q_list) if (header_data.PickQuestionCount < len(q_list) and header_data.PickQuestionCount > 0): list = random.sample(q_list, k=header_data.PickQuestionCount) else: list = q_list for question in q_list: #PrintQuestion(question, pdf, count, header_data) question.Print(pdf, header_data, "", count) count = count + 1 name = "sample_" + str(i) + ".pdf" pdf.output(name)
def generate_labels(self): conn = pyodbc.connect('DSN=QDSN_10.0.0.1;UID=username;PWD=password') cursor = conn.cursor() cursor.execute( "select ODITEM, ODQORD from HDSDATA.OEORDT where ODORD# = " + self.order_value.get()) parts_list = [] # [part number, quantity] for rows in cursor: parts_list.append([rows.ODITEM.rstrip(), int(rows.ODQORD)]) # 72 pts in an inch l_width = 162 l_height = 54 label = FPDF(orientation='P', unit='pt', format=(l_width, l_height)) label.set_margins(0, 0) # we don't want margins label.set_auto_page_break(0) # turn off page breaks label.set_font('Courier', 'B', 22) for p in parts_list: for i in range(0, p[1]): label.add_page() label.cell(l_width, l_height, p[0], 0, 0, 'C') label.output(temp_pdf_file)
def create_cv_pdf(input_data, image_name): pdf = FPDF('P', 'mm', 'A4') pdf.set_auto_page_break(auto=True, margin = 15) pdf.add_page() pdf.set_font('helvetica', '', 16) pdf.image(f'uploads/{image_name}', 20, 10, 40) pdf.set_font('helvetica', 'B', 18) pdf.cell(0,10, '- CV -', border=False, ln=True, align='C') pdf.set_font('helvetica', '', 16) pdf.cell(0,8, f'{input_data["personal"]["name"]} {input_data["personal"]["surname"]}', border=False, ln=True, align='C') pdf.cell(0,8, f'E-mail: {input_data["personal"]["email"]}', border=False, ln=True, align='C') pdf.cell(0,8, f'Phone number: {input_data["personal"]["phone"]}', border=False, ln=True, align='C') pdf.cell(0,15, f'Birth date: {input_data["personal"]["birthday"]}', border=False, ln=True, align='C') pdf.cell(0,0, f'City: {input_data["personal"]["city"]}', border=False, ln=True, align='C') pdf.cell(0,10, '', border=False, ln=True, align='C') pdf.cell(0,10, 'EXPERIENCE', border=False, ln=True, align='C') pdf.cell(0,0, '', border=True, ln=True, align='C') for experience in input_data['experiences']: # Experience - 1'st company pdf.cell(0,5, '', border=False, ln=True, align='C') pdf.cell(0,8, f'{input_data["experiences"][experience]["startdate"]} - {input_data["experiences"][experience]["enddate"]}', border=False, ln=True) pdf.cell(0,8, f'{input_data["experiences"][experience]["position"]} | {input_data["experiences"][experience]["name"]} | {input_data["experiences"][experience]["place"]}', border=False, ln=True) pdf.cell(0,10, 'Description:', border=False, ln=True) pdf.cell(0,8, f'{input_data["experiences"][experience]["description"]}', border=False, ln=True) pdf.cell(0,10, 'EDUCATION', border=False, ln=True, align='C') pdf.cell(0,0, '', border=True, ln=True, align='C') # Education for education in input_data['education']: pdf.cell(0,5, '', border=False, ln=True, align='C') pdf.set_font('helvetica', 'B', 14) pdf.cell(0,8, f'{input_data["education"][education]["startdate"]} - {input_data["education"][education]["enddate"]}', border=False, ln=True) pdf.set_font('helvetica', '', 16) pdf.cell(0,8, f'{input_data["education"][education]["name"]} | {input_data["education"][education]["subject"]}', border=False, ln=True) pdf.set_font('helvetica', 'B', 14) pdf.cell(0,10, 'Description:', border=False, ln=True) pdf.set_font('helvetica', '', 16) pdf.cell(0,8, f'{input_data["education"][education]["description"]}', border=False, ln=True) try: random_number = str(random.randint(0, 99999)) while (len(random_number) < 5): random_number = '0' + random_number file_name = 'cv-' + random_number pdf.output(f'cv/{file_name}.pdf') return file_name except: print('Błąd: otwaty pdf')
def main(): directory = sys.argv[1] no_images = int(sys.argv[2]) img_names = [] try: os.stat(directory) except: os.mkdir(directory) # download and label images for i in range(0, no_images): print("Saving image #{0}".format(i)) text = bs_txt() img = bs_img() draw = ImageDraw.Draw(img) draw.rectangle([0, 0, 1280, 100], fill=(255, 255, 255, 70)) font = ImageFont.truetype('/Library/Fonts/Arial Bold.ttf', 36) draw.text((0, 30), text, (50, 50, 50), font=font) font = ImageFont.truetype('/Library/Fonts/Arial Bold.ttf', 100) draw.text((1150, 630), str(i + 1), (255, 255, 255), font=font) name = directory + '/' + '{0}.jpg'.format(i) img.save(name) img_names.append(name) # create pdf from image directory folder pdf = FPDF(orientation='L') pdf.set_auto_page_break(0) for image in img_names: pdf.add_page() pdf.image(image, h=210 * 0.9, w=297 * 0.93) pdf.output("{0}.pdf".format(directory), "F")
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 generate_pdf(): pdf = FPDF('P', 'in', 'A5') font_height = 0.16 pdf.add_page() pdf.set_margins(1.0, 1.0) pdf.set_auto_page_break(True, margin=0.25) pdf.set_font('Courier', "", 10) pdf.set_xy(1.0, 1.0) f = open('doc.txt') for line in f: pdf.write(font_height, line) f.close() #Hash function to generate unique file name using datetime module uniq_filename = 'Jarvis_' + str(datetime.datetime.now().date()) uniq_filename = uniq_filename + '_' + str( datetime.datetime.now().time()).replace(':', '_')[0:8] uniq_filename = uniq_filename + '.pdf' with open("name.txt", "w") as f: f.write(uniq_filename) pdf.output(uniq_filename)
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 export_customer_tags(query): pdf = FPDF(orientation ='P', unit = 'mm', format='Letter') pdf.set_margins(left=4, top=8, right=5) pdf.set_auto_page_break(auto = True, margin = 10) pdf.add_page() pdf.set_font('Arial', '', 10) x_ref = pdf.get_x() width_tag = 69.6 count = 0 y_ref = pdf.get_y() count_tag = 0 for customer in query: if count_tag % 30 == 0 and count_tag > 0: pdf.add_page() #text = 'Prezado Alisson Barbosa\nRua das Orquídeas, 57\nJardim das Plantas\nCampina Grande - PB\n58415-000' text = '{}\n{}, {}\n{}\n{}\n{}'.format(customer.name, customer.street, customer.number, customer.neighborhood, customer.city, customer.cep) if count == 0: x_ref = pdf.get_x() y_ref = pdf.get_y() count += 1 elif count == 1: x_ref += width_tag count += 1 elif count == 2: x_ref += width_tag count = 0 pdf.set_xy(x = x_ref, y = y_ref) pdf.multi_cell(width_tag, 5.195, text, 0, 'L') count_tag += 1 response = HttpResponse(pdf.output(dest='S').encode('latin-1')) response['Content-Disposition'] = 'attachment;filename="Etiquetas.pdf"' return response
def create_pdf(wordlist, title, num_pages): ''' Generates a PDF. Doesn't return anything. Parameters: wordlist -> A list of words in the English Language. title -> The title of the PDF. num_pages -> The number of pages in the PDF. ''' pdf = FPDF() pdf.set_font('Arial', size=15) pdf.set_auto_page_break(False) has_byline = bool(random.randint(0, 1)) for i in range(num_pages): pdf.add_page() if i == 0: pdf.set_font('Arial', 'B', 18) pdf.cell(0, 20, title, ln=1, align='C') if has_byline: pdf.set_font('Arial', 'B', 16) pdf.cell(0, 20, "By - {}".format(generate_name(wordlist)), ln=1, align='C') pdf.set_font('Arial', size=15) text = generate_text(wordlist) pdf.multi_cell(w=0, h=8, txt=text) pdf.output('Output/{}.pdf'.format(title))
class PDFGridGenerator(): """A pdf grid generator. To use: >>> g = PDFGridGenerator() >>> g.generate('filename.pdf') """ def __init__(self): self.pdf = FPDF() self.pdf.add_page() self.pdf.set_auto_page_break(False) self.pdf.set_margins(0, 0) self.pdf.set_draw_color(191, 187, 187) self.pdf.set_line_width(0.35) def save(self, filename): self.pdf.output(filename) def generate_grid(self): # Fonts must be set before writing text self.pdf.set_font('Arial', 'B', 8) self.pdf.set_text_color(0, 0, 0) self.generate_vertical_lines(5) self.generate_horizontal_lines(5) self.left_numbers(5) self.top_numbers(5) def generate_vertical_lines(self, spacing): lines = 42 for i in range(1, lines): x = i * 5 self.pdf.line(x, 5, x, 290) def generate_horizontal_lines(self, spacing): lines = 59 for j in range(1, lines): y = j * 5 self.pdf.line(5, y, 205, y) def left_numbers(self, spacing): lines = 58 for i in range(0, lines): self.pdf.set_xy(0, i * 5 + 3) self.pdf.write(5, str(i)) def top_numbers(self, spacing): lines = 41 for i in range(0, lines): self.pdf.set_xy(i * 5 + 3, 1) self.pdf.write(5, str(i)) def text(self, x, y, txt, font_size=13): self.pdf.set_font('Arial', '', font_size) self.pdf.set_text_color(0, 0, 0) self.pdf.set_xy(x * 5 + 4, y * 5 + 5) self.pdf.write(5, txt)
def convert_to_pdf(text, path): path = change_format_to_pdf(path) pdf = FPDF(orientation='P', format='A4') pdf.add_page() pdf.set_font("Arial", size=12) pdf.set_auto_page_break(auto=True) pdf.multi_cell(w=200, h=10, txt=text) pdf.output(path)
def _renderPdf(self): pdf = FPDF(orientation='P', format='A4', unit='mm') pdf.add_page() pdf.set_margins(left=0, top=0, right=0) pdf.set_auto_page_break(auto=False, margin=0.0) filename = os.path.join(self.data['wdir'], self.data['name']) pdf.image(filename + ".png", w=210) pdf.output(filename + ".pdf") return (0)
def print_one_label(self): # no database query, just print a label for a manually entered part # # 72 pts in an inch l_width = 162 l_height = 54 label = FPDF(orientation='P', unit='pt', format=(l_width, l_height)) label.set_margins(0, 0) # we don't want margins label.set_auto_page_break(0) # turn off page breaks label.set_font('Courier', 'B', 22) label.add_page() label.cell(l_width, l_height, self.single_value.get(), 0, 0, 'C') label.output(temp_pdf_file)
def _get_pdf_obj(self): if self.bookletize: # The bookletize option is for those who don't have, don't want to use, or don't # know how to use the "booklet" option on their printer. It does the hard work of # arranging the booklet pages on paper in a landscape orientation. pdf = FPDF(orientation='L', format=self.paper_size) else: # This produces booklet pages as single pdf pages. They're designed to be printed # using the "booklet" option on a printer, meaning two per page. For this reason, # we're dividing the specified paper size by 2. pdf = FPDF(format=(self.paper_size[1] / 2, self.paper_size[0])) pdf.set_margins(5, 5) pdf.set_auto_page_break(0, 5) return pdf
def main(): jl_path = "./resources/cards_data.jl" data_names = ["cards_data", "items_data", "hidden_secrets"] pdf = FPDF() pdf.set_auto_page_break(auto=False) pdf.add_page() for file_name in data_names: with open("./resources/" + file_name + ".jl") as f: for line in f: data = json.loads(line) n = int(data['amnt']) for i in range(n): place_card(pdf, data['id']) pdf.output('./out/out.pdf', 'F')
def createExercices(problems): exercises_per_column = 28 columns = 5 column_width = 50 cell_height = 7 number_width = 6 spacer = 2 pdf = FPDF(orientation="L") pdf.set_top_margin(5) pdf.set_auto_page_break(True, 1) pdf.add_page() pdf.set_font("Arial", size=12) start_x = pdf.get_x() start_y = pdf.get_y() for i in range(len(problems)): problem = problems[i] pdf.set_xy(start_x + int(i / exercises_per_column) * column_width, start_y + (i % exercises_per_column) * cell_height) border = "R" if (int(i / exercises_per_column) == columns - 1): border = 0 if (problem.unknown == UnknownElement.Z): pdf.cell(spacer, cell_height) pdf.cell(number_width, cell_height, txt=str(problem.x), align="C") pdf.cell(number_width, cell_height, txt=str(problem.operator), align="C") pdf.cell(number_width, cell_height, txt=str(problem.y), align="C") pdf.cell(number_width, cell_height, "=", align="C") pdf.cell(column_width - 4 * number_width - spacer, cell_height, border=border) elif (problem.unknown == UnknownElement.X): pdf.cell(column_width - 4 * number_width - spacer, cell_height) pdf.cell(number_width, cell_height, txt=str(problem.operator), align="C") pdf.cell(number_width, cell_height, txt=str(problem.y), align="C") pdf.cell(number_width, cell_height, "=", align="C") pdf.cell(number_width, cell_height, str(problem.z), align="C") pdf.cell(spacer, cell_height, border=border) pdf.output("simple_demo.pdf")
def merge_jpg_in_one_pdf_file(): images = askopenfiles(mode='r', filetypes=[('Image Files', '*.jpg')]) imagelist = [] for image in images: imagelist.append(image.name) pdf = FPDF() pdf.set_auto_page_break(0) # imagelist is the list with all image filenames for image in imagelist: pdf.add_page() pdf.image(image, w=190, h=297) # for A4 page pdf.output("mergedfile.pdf", "F") tmsg.showinfo( 'PDF created', 'JPG files are merged and is saved into the current working directory')
def createPDF(self): pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'B', 18) # header pdf.image("images/ImagLogo.GIF", 170, 3, 25) pdf.cell(0, 10, "Report", border=False, ln=1, align="C") pdf.ln() #####General Information pdf.set_font('Arial', 'B', 12) pdf.set_fill_color(213, 201, 239) pdf.cell(0, 9, 'General Information', 0, 1, 'L', 1) pdf.ln(3) pdf.line(8, 20, 150, 20) pdf.set_font('Arial', 'IB', 13) pdf.cell( 130, 10, txt="Paitant ID : " + self.P_ID + " ", ln=1, align='E', ) pdf.set_font('Arial', 'B', 12) pdf.cell(130, 10, txt="Check up No:", align="W") pdf.cell(100, 10, txt=" Test Result Data: " + datetime.date.today().strftime("%d-%m-%y"), ln=1, align="E") ##Result pdf.ln() pdf.set_font('Arial', 'B', 12) pdf.set_fill_color(213, 201, 239) pdf.cell(0, 9, ' Result Infromation', 0, 1, 'L', 1) pdf.image(self.imagePa, 90, 100, 100) pdf.ln() pdf.set_font('Arial', 'B', 16) pdf.cell(0, 10, txt=" The disease is " + self.result + "", align="W") # footer pdf.set_font('Arial', '', 13) pdf.set_auto_page_break(auto=True, margin=15) pdf.set_y(270) pdf.cell(0, 10, f'Page {pdf.page_no()}/nb', align="C") pdf.alias_nb_pages(alias='nb') # add another cell pdf.output("results/" + self.P_ID + ".pdf")
def generate_pdf(images, sheet_name, url_root, orientation="P", progress=None, show_name=True): pdf = FPDF(orientation=orientation, unit="mm", format="A4") pdf.set_font("Helvetica", size=12) pdf.set_auto_page_break(False) for image in images: pdf.add_page() pdf.set_x(0) if orientation == "P": page_width = 210 page_height = 297 else: page_width = 297 page_height = 210 response = requests.get(url_root + image.path) filename = image.path.split("/", 1)[1] with Image.open(BytesIO(response.content)) as im: width, height = fit_image(im, page_width, page_height) x, y = center_image(page_width, page_height, width, height) im.save(filename, format=im.format) pdf.image(filename, x=x, y=y, w=width, h=height) # Clean-up os.remove(filename) pdf.set_xy((page_width - 180) / 2, page_height - 20) if show_name: pdf.cell(180, 15, txt=image.name, align="C") if progress: progress.update_progress() pdf_name = secure_filename(sheet_name + ".pdf") pdf.output(name=pdf_name) return pdf_name
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 get_centered_start_y(text_width, text): test_pdf = FPDF('P', METRIC, DOCUMENT_SIZE) test_pdf.add_font(FONT_NAME, '', FONT_LOCATION, uni=True) test_pdf.set_font(FONT_NAME, size=FONT_SIZE) test_pdf.set_auto_page_break(False) test_pdf.add_page() initial_y = test_pdf.get_y() test_pdf.multi_cell( text_width, TEXT_HEIGHT, text, 0, 'C', ) multi_cell_height = test_pdf.get_y() - initial_y start_y = int(round(0.5 * (DOCUMENT_SIZE[1] - multi_cell_height))) return int(round(0.5 * (DOCUMENT_SIZE[1] - multi_cell_height)))
def __pdf_diploma(diploma, params): locale.setlocale(locale.LC_TIME, '') __setup_default_params(params) pdf = FPDF('L', 'mm', 'A4') pdf.set_margins(params['margin'], params['margin']) pdf.set_auto_page_break(False) pdf.add_font('Arial', '', 'arial.ttf', uni=True) pdf.set_font('Arial', '', 12) pdf.add_page() params['header'](diploma, pdf, params) params['body'](diploma, pdf, params) params['footer'](diploma, pdf, params) return pdf
def natives_to_pdf(confidential, prefix, vol_num, prod_num): prod_fol, vol_fol, n_path, i_path, t_path, m_path = start( prefix, vol_num, prod_num) dirs = [f for f in listdir(n_path) if isfile(join(n_path, f))] for filer in dirs: pre, ext = os.path.splitext(filer) if ext != ".msg": pdf = FPDF() pdf.l_margin = 10 pdf.t_margin = 2 pdf.add_page() pdf.set_auto_page_break(True, margin=0.25) pdf.set_font('arial', 'B', 13.0) if confidential: pdf.cell( ln=0, h=5.0, align='C', w=0, txt= "CONFIDENTIAL " + pre, border=0) else: pdf.cell( ln=0, h=5.0, align='C', w=0, txt= " " + pre, border=0) pdf.set_font('arial', 'B', 20.0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="", border=0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="", border=0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="", border=0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="", border=0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="FILE PRODUCED NATIVELY", border=0) pdf.output(f"{t_path}\\{pre}.pdf", 'F') pdf_to_image(pre, t_path, i_path)
def read_comic(selection): data = get_readlist() comic = data[selection] if comic['read'] == comic['total']: print('There are no more issues to read for this comic!') main() soup = get_soup(comic['url']) issues = soup.find_all("tr")[comic['total'] - comic['read'] - 1] print('Loading ' + issues.find("td").a.text + '...') url = issues.find("td").a['href'] + '/full' soup = get_soup(url) pages = soup.find_all('img', class_='chapter_img') if not os.path.exists('images'): os.mkdir('images') pdf = FPDF() pdf.set_auto_page_break(0) for i, page in enumerate(pages): urllib.request.urlretrieve(page['src'], "images/" + str(i) + ".jpg") # for i in range(len(os.listdir('images'))): image = 'images/' + str(i) + '.jpg' img = cv2.imread(image) if img.shape[0] < img.shape[1]: pdf.add_page(orientation='L') pdf.image(image, x=0, y=0, h=210, w=297) else: pdf.add_page(orientation='P') pdf.image(image, x=0, y=0, w=210, h=297) os.remove(image) pdf.output('comic.pdf', 'F') update_item(selection, comic['title'], comic['url'], comic['read'] + 1, comic['total'], comic['status']) webbrowser.open(r'comic.pdf') clear() comic_detail_view(selection)
def convert_to_pdf(session, user_id, upload_dir, filename): """ convert text file to PDF :return: None """ is_success = False database_file_query = session.query(File).filter(File.user_id == user_id).filter(File.filename == filename) if database_file_query.first().status == "local": pdf = FPDF('P', 'in', 'Letter') # set the font size font_height = 0.16 # add a page , set margin and enable autyo page break pdf.add_page() pdf.set_margins(0.25, 0.25) pdf.set_auto_page_break(True, margin=0.25) # set the font and where the cursor starts pdf.set_font('Arial', '', 10) pdf.set_xy(0.25, 0.25) # open the text filen abd line by line, read from file and write to pdf with open(os.path.join(upload_dir, filename), "r") as txt_file: line = 1 while line: line = txt_file.readline() pdf.write(font_height, line) # write out pdf file, use 'latin-1' encoding to avoid unicode issues pdf.output(os.path.join(upload_dir, filename.replace('txt', 'pdf'))).encode('latin-1') # delete the original file if os.path.exists(os.path.join(upload_dir, filename.replace('txt', 'pdf'))): os.remove(os.path.join(upload_dir, filename)) # upload DB with new status database_file_query.update({'status':"local_converted"}) session.commit() is_success = True return is_success
def img2pdf(images, output, orientation="P", units="cm", size=(10, 15)): """ Takes a list of images (as file paths), and creates a pdf document with an image per page. NOTE: Requires fpdf to be installed Args: images: (list of strings) List of file paths to images to use. output: Path to output file orientation: (string) (default="P") "P" = Protrait "L" = Landscape units: (string) (default="cm") Units of measurement to pass on to FPDF "cm" = Centimeters "mm" = Milimeters size: (tuple) dimensions of the page (in the specified units) (width, height) """ # ========================================================================== from fpdf import FPDF # Initialize PDF document pdf = FPDF(orientation = orientation, unit = units, format = size) # Margin around image pdf.set_margins(left=0.0, top=0.0, right=0.0) # prevent the full page images trigering a new page break pdf.set_auto_page_break(auto=False, margin = 0.0) # Use each image as a page for image in images: pdf.add_page(orientation = orientation) pdf.image(image, x=None, y=None, w=size[0], h=size[1]) # Save the pdf doc pdf.output(name = output) print "Created PDF document: {}".format(output)
def create_pdf_page(codes_array, start, stop, pdf=None): """creates a single pdf page from codes_array[start:stop] Arguments: codes_array {[list]} -- [list of codes] start {[int]} -- [starting index] stop {[int]} -- [stop index] Keyword Arguments: pdf {[filepath]} -- [path to pdf to be appended to] (default: {None = new one will be created}) """ if not pdf: pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.set_font('Arial') pdf.set_font_size(16) pdf.set_margins(3, 3.5, 3) pdf.set_auto_page_break(False) pdf.add_page() # two rows i = start for y in range(3, 149, 145): # 4 per row for x in range(3, 157, 51): if i > stop: return offset = (x, y + 0.5) # ticket offset_padding = (offset[0] + 1.5, offset[1] + 1.5) pdf.set_xy(offset[0], offset[1]) pdf.set_fill_color(150, 10, 10) pdf.cell(51, 145, "", 1, 1, 'c', True) code = codes_array[i] image_tempfile = create_qr(code) pdf.image(image_tempfile.name, offset_padding[0], offset_padding[1], 48, 48, 'PNG') os.unlink(image_tempfile.name) image_tempfile.close() pdf.set_xy(offset_padding[0], offset[1] + 51) pdf.set_fill_color(10, 150, 10) pdf.cell(48, 6, str(code), 1, 1, 'C', True) pdf.set_xy(offset_padding[0], offset[1] + 58.5) pdf.cell(48, 85, fill=True) i += 1
def image_to_pdf(filer, index, confidential, prefix, vol_num, prod_num): prod_fol, vol_fol, n_path, i_path, t_path, m_path = start( prefix, vol_num, prod_num) _, ext = os.path.splitext(filer) if ext == ".png": n_ext = ".jpg" else: n_ext = ext mn_index = format(index, '08d') dest = f"{prefix}{mn_index}" pdf = FPDF() pdf.l_margin = 30 pdf.add_page() pdf.set_auto_page_break(True, margin=0.25) pdf.set_font('arial', 'B', 10.0) if confidential: pdf.cell( ln=0, h=5.0, align='C', w=0, txt= f"CONFIDENTIAL {dest}", border=0) else: pdf.cell( ln=0, h=5.0, align='C', w=0, txt= f" {dest}", border=0) pdf.set_font('arial', 'B', 20.0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="", border=0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="", border=0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="", border=0) pdf.cell(ln=1, h=10.0, align='C', w=0, txt="", border=0) name = f"{t_path}\\{dest}{n_ext}" typer = n_ext[1:] pdf.image(name, x=45, y=None, w=120, type=typer, link='') pdf.output(f"{t_path}\\{dest}.pdf", 'F') pdf_to_image(dest, t_path, i_path)
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 createCertificate( workshop_name, workshop_day, workshop_month, workshop_year, workshop_speaker, student_name, student_mail, chair_IEEE ): l_name = unicode( student_name, "utf-8" ) w_name = unicode( workshop_name, "utf-8" ) c_name = unicode( chair_IEEE, "utf-8" ) s_name = unicode( workshop_speaker, "utf-8" ) # PDF File Properties pdf=FPDF('L','mm','A4') pdf.set_margins(left=0,top=0,right=0) pdf.set_auto_page_break(False,margin=0) pdf.add_page() # ISEPinIEEE Logo pdf.set_font('Arial','',30) pdf.cell(297,40,'',0,1,'C')#fill=True pdf.image('logos/isepinieee_logo.jpg',190,5, 0,35,'','') # Workshop Title pdf.set_text_color(0,102,153) pdf.cell(293,20,w_name,0,1,'R') # Cetificate Bar pdf.set_fill_color(0,102,153) pdf.set_text_color(255,255,255) pdf.set_font('Arial','',48) pdf.cell(297,35,'Certificate',0,1,'C',fill=True) pdf.cell(297,10,'',0,1,'C') # Certificate Text pdf.set_font('Arial','',20) pdf.set_text_color(0,0,0) # This pdf element is used to center ( Note: (297-240)/2 = 28.5) pdf.cell(19,20,'',0,0,'C') pdf.multi_cell(259,12.5, 'We certifiy that '+l_name+' participated in the talk \"'+w_name+'\", organized by the ISEPinIEEE.',0,1,'C') #MultiCell( 200, 40, $reportSubtitle, 1); # Certificate Date pdf.cell(297,10,'',0,1,'C') pdf.cell(19,15,'',0,0,'C') pdf.cell(240,10,'Porto, '+workshop_month+' '+str(workshop_day)+', '+str(workshop_year),0,1,'L') #Speaker & Chair Signature pdf.image(workshop_name+'/signatures/speaker.jpg',167.5,170, 0, 17,'','') pdf.image(workshop_name+'/signatures/chair.jpg',240.5,170, 0, 17,'','') #Speaker & Chair pdf.set_font('Arial','',18) pdf.cell(150,20,'',0,0,'C') pdf.cell(73.5,20,'Speaker',0,0,'C') pdf.cell(73.5,20,'Chair',0,1,'C') pdf.cell(150,35,'',0,0,'C') pdf.cell(73.5,35,s_name,0,0,'C') pdf.cell(73.5,35,c_name,0,1,'C') #SpeakerLine & ChairLine pdf.line(155, 180, 218, 180) pdf.line(228, 180, 292, 180) # IEEE and ISEP logos pdf.image('logos/ieee_logo.jpg',20,175, 0, 17,'','') pdf.image('logos/isep_logo.jpg',85,175, 0, 17,'','') # Save PDF File certificate_name = hashlib.md5(student_mail) pdf.output(workshop_name+'/'+certificate_name.hexdigest()+'.pdf','F')