def save_file(): option = request.form['action'] texts = request.form.getlist("message[]") if option == "word": document = Document() for text in texts: document.add_paragraph(text.replace("\n", "")) document.save('extracted_text.docx') return send_file("extracted_text.docx", as_attachment=True, cache_timeout=0) elif option == "pdf": texts = "\n".join(texts) pdf = FPDF() pdf.alias_nb_pages() pdf.add_page() pdf.set_font('Times', '', 10) for text in texts.split("\n"): pdf.cell(0, 8, text.encode('utf-8').decode('latin-1'), 0, 1) pdf.output('extracted_text.pdf', 'F') return send_file("extracted_text.pdf", as_attachment=True, cache_timeout=0) elif option == "txt": with open("extracted_text.txt", "w", encoding='utf-8') as f: for text in texts: f.write(text.replace("\n", "")) return send_file("extracted_text.txt", as_attachment=True, cache_timeout=0) return ""
def pdf_creator(dataset): pdf = FPDF() pdf.alias_nb_pages() pdf.add_page() pdf.add_font('FreeSans', '', './static/fonts/FreeSans.ttf', uni=True) pdf.add_font('FreeSans', 'B', './static/fonts/FreeSansBold.ttf', uni=True) pdf.add_font('FreeSans', 'I', './static/fonts/FreeSansOblique.ttf', uni=True) pdf.image('./static/images/logo_small.png', 10, 8, 33) pdf.set_font('FreeSans', 'B', 16) pdf.cell(80) pdf.cell(30, 10, 'Report', 1, 0, 'C') pdf.ln(20) pdf.set_font('FreeSans', '', 12) for key, values in dataset.items(): pdf.multi_cell(0, 5, key.static_text) pdf.ln('0.1') for ls in values: for item in ls: if (hasattr(item, "url")): pdf.multi_cell(0, 5, "• " + item.url) if (hasattr(item, "title")): pdf.multi_cell(0, 5, "• " + item.title) pdf.ln('0.3') pdf_file = pdf.output(dest='S').encode('latin-1') return pdf_file
def export_transactions(self): pdf = FPDF() pdf.alias_nb_pages() pdf.add_page() pdf.set_font('Arial', '', 12) for i, trans in enumerate(self.accounting): output = 'Id: ' + str(trans.transactionId) + ' | Type: ' + str( trans.get_type()) + ' | Beløb: ' + str(trans.amount) pdf.cell(1, 10, output, 0, 1) pdf.output('transaktioner.pdf')
def generate_template(): pdf = FPDF() pdf.set_font('Times', '', 15) pdf.alias_nb_pages() pdf.add_page() pdf.ln(0) pdf.cell(0, 10, 'Name: ', 0, 1) pdf.cell(0, 10, 'PID: ', 0, 1) pdf.cell(0, 10, 'ieng6 username: '******'Grade: ', 0, 1) # for i in range(1, 41): # pdf.cell(0, 10, 'Printing line number ' + str(i), 0, 1) pdf.output('template.pdf', 'F')
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_grade_pdf(stList,stMarks): pdf = FPDF() pdf.set_font('Times', '', 15) pdf.alias_nb_pages() for i in stMarks: if(i not in stList): print("userid::"+i+"not found in student list") exit() pdf.add_page() pdf.ln(0) ieng6_uname=i uName=stList[i][2]+" "+stList[i][1] pid=stList[i][0] grade=stMarks[i] pdf.cell(0, 10, 'Name: '+uName, 0, 1) pdf.cell(0, 10, 'PID: '+pid, 0, 1) pdf.cell(0, 10, 'ieng6 username: '******'Grade: '+grade, 0, 1) pdf.output('grade.pdf', 'F')
def create_pdf_news(path, News): if os.path.isdir(path) is False: raise RssException("Error. It isn't a folder") path = os.path.join(path, "News.pdf") pdf = FPDF() try: pdf.add_font('DejaVuSans', '', 'DejaVuSans.ttf', uni=True) pdf.set_font("DejaVuSans") except RuntimeError: raise RssException("fonts file not found") pdf.alias_nb_pages() pdf.add_page() for item_news in News: text = item_news.news # remove links in the text and add pictures start = text.find(']', 0, len(text)) text = text[start + 1:] pdf.set_font_size(26) pdf.write(11, item_news.title + '\n\n') pdf.set_font_size(14) pdf.write(11, f"Date: {item_news.date}\n") this_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.append(this_dir) if len(item_news.links) > 0: try: pdf.image(f'{this_dir}/images/{correct_title(item_news.title)}.jpg', w=75, h=75) except RuntimeError: pass pdf.write(10, "\n") pdf.write(10, text + "\n\n\n\n") pdf.output(path, 'F') try: pdf.output(path, 'F') except FileNotFoundError: raise RssException("Error. No such folder") print("file News.pdf created")
def get_quiz_in_pdf(request, quiz_pk): quiz = get_object_or_404(Quiz, pk=quiz_pk, owner=request.user) pdf = FPDF() pdf.alias_nb_pages() pdf.add_page() pdf.set_font('Times', 'B', 16) pdf.cell(0, 10, txt=quiz.name, ln=1) pdf.set_font('Times', '', 14) questions = Quiz.objects.prefetch_related('questions').get(pk=quiz_pk, owner=request.user).questions.all() question_lines = 1 for question in questions: pdf.cell(0, 10, txt='', ln=1) pdf.set_font('Times', 'B', 14) pdf.cell(0, 10, txt=f'{question_lines}. {question.text}', ln=1) pdf.set_font('Times', '', 14) pdf.cell(0, 10, txt='', ln=1) question_lines += 1 answer_lines = 1 for answer in question.answers.all(): pdf.cell(0, 10, txt=f'{answer_lines}. {answer.text}', ln=1) answer_lines += 1 pdf.output(f'{quiz.name}.pdf') response = FileResponse(open(f'{quiz.name}.pdf', 'rb'), as_attachment=True) return response
def create_pdf(self): """Build the PDF file from user-supplied information""" # Dictionary of variables collected from gui, to be passed to method_graf() self.variabledic = {"methodofservice": self.methodText.get(), "documents": self.docsservedText.get().upper(), "target": self.targetText.get(), "dateandtime": self.monthText.get() + " " + self.dayText.get() + ", " + self.yearText.get() + ", at " + self.hourText.get() + ":" + self.minuteText.get() + " " + self.ampmText.get(), "location": self.locationText.get(), "subperson": self.subpersonText.get(), "subrelation": self.subrelationText.get(), "parentname": self.parentText.get(), "tempguard": self.tempText.get(), "committed": self.committedBool.get(), "adminname": self.adminText.get(), "agentname": self.agentText.get(), "sex": self.sexText.get() } pdf=FPDF("P", "pt", "Letter") pdf.set_margins(36,36) pdf.alias_nb_pages() pdf.add_page() # State, County & Court pdf.set_font("Times", "", 12) pdf.multi_cell(h = 18, w = 540, align = "L", txt = ( "IN THE "+self.courtText.get().upper()+" COURT OF\n"+ self.countyText.get().upper()+" COUNTY, "+self.stateText.get().upper())) pdf.ln(30) # Plaintiff pcursor = pdf.get_y() pdf.multi_cell(h=18, w=400, align = "L", txt=self.plaintiffEntry.get(0.0,'end').upper()) newpcursor = pdf.get_y() pdf.set_xy(400, pcursor) pdf.cell(w = 0, align = "R", txt = "PLAINTIFF") pdf.set_xy(0, newpcursor) pdf.ln(18) # Case Number pdf.cell(h = 18, w = 20, align = "L", txt = "V.") pdf.cell(h = 18, w = 500, align = "C", txt = "CASE NO. "+self.caseNoText.get().upper()) pdf.ln(30) # Defendant pcursor = pdf.get_y() pdf.multi_cell(h=18, w=400, align = "L", txt=self.defendantEntry.get(0.0,'end').upper()) newpcursor = pdf.get_y() pdf.set_xy(400, pcursor) pdf.cell(h = 18, w = 0, align = "R", txt = "DEFENDANT") pdf.set_xy(0, newpcursor) pdf.ln(18) # Title pdf.set_font("Times", "U", 12) pdf.cell(h = 24, w = 0, align = "C", txt = "AFFIDAVIT OF SERVICE") pdf.ln(36) # Commencement pdf.set_font("Times", "", 12) pdf.multi_cell(h = 30, w = 540, align = "L", txt = ( " Comes now " + self.serverText.get() + ", who, being duly " "sworn, deposes and says:")) # Paragraph with details of service (multi-line), called from method_graf() function pdf.multi_cell(h = 30, w = 540, align = "L", txt = self.method_graf(**self.variabledic)) # Comments if len(self.commentsText.get()) > 0: pdf.multi_cell(h = 30, w = 540, align = "L", txt = " " + self.commentsText.get()) # Not a party/No interest/Further affiant sayeth not, etc. pdf.multi_cell(h = 30, w = 540, align = "L", txt = ( " I am not a party to this action, and I have no interest in it. \n" " Further affiant sayeth not.")) pdf.ln(40) # Signature/Notary section pdf.line(270,pdf.get_y(),540,pdf.get_y()) pdf.set_x(270) pdf.cell(h = 24, w = 0, align = "L", txt = self.serverText.get()) pdf.ln(24) pdf.set_x(270) pdf.multi_cell(h = 18, w = 0, align = "L", txt = self.servaddrEntry.get(0.0,"end")) pdf.ln(24) pdf.set_x(36) pdf.cell(h = 18, w = 270, align = "L", txt = "Subscribed and sworn to before me this date:") pdf.line(270,pdf.get_y()+18,540,pdf.get_y()+18) pdf.ln(40) pdf.line(270,pdf.get_y()+18,540,pdf.get_y()+18) pdf.ln(24) pdf.set_x(270) pdf.cell(h = 18, w = 270, align = "L", txt = "Notary Public") pdf.ln(36) pdf.set_x(270) pdf.cell(h = 18, w = 270, align = "L", txt = "My commission expires:") pdf.line(400,pdf.get_y()+18,540,pdf.get_y()+18) # write PDF pdf.output(self.filenameText.get()+".pdf", "F") return None
def ui_func(topic, user_name, psswd, txt_pdf): options = Options() options.headless = True driver = webdriver.Firefox(options=options) driver.get("https://medium.com/") driver.implicitly_wait(10) #action = webdriver.ActionChains(driver) time.sleep(2) login = driver.find_element_by_link_text('Sign in').click() try: login_google = driver.find_element_by_xpath( '/html/body/div[4]/div/div/section/div[1]/div/button[1]').click() except TimeoutException: pass # You can log-in using google only print(" Logging in to Medium by using Google ") time.sleep(3) assert "Sign in – Google accounts" in driver.title user = driver.find_element_by_xpath('//*[@id="identifierId"]') # Enter your email or phone number as registered in Medium user.send_keys( user_name) # Provide your email or registered phone number here nextButton = driver.find_element_by_xpath( '//*[@id="identifierNext"]/content') nextButton.click() time.sleep(2) user = driver.find_element_by_xpath( '//*[@id="password"]/div[1]/div/div[1]/input') # Place just your password in the pass.txt file user.send_keys(psswd) LOG = driver.find_element_by_xpath( '//*[@id="passwordNext"]/content').click() print('LOGIN SUCCESSFUL \n') topics = { 0: 'Home', 1: 'Technology', 2: 'Culture', 3: 'Entrepreneurship', 4: 'Creativity', 5: 'Self', 6: 'Productivity', 7: 'Design', 8: 'Popular' } if topic == 0: t = driver.get("https://medium.com/") elif topic < 9: t = driver.get("https://medium.com/topic/" + topics[topic]) else: print('Please select a correct topic.') # To Scroll to the bottom/ a portion of page last_height = 1000 while True: driver.execute_script( "window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) new_height = driver.execute_script("return document.body.scrollHeight") if new_height >= last_height: break tag = driver.find_elements_by_tag_name('h3') tag_len = len(tag) links = [ i.get_attribute('href') for i in driver.find_elements_by_xpath("//a[@data-action-source]") ] unique_list = list(OrderedDict(zip( links, repeat(None)))) # To remove duplicates from list if txt_pdf == 1: title = 'Medium Grabber' pdf = FPDF() pdf.alias_nb_pages() pdf.add_page() pdf.set_title(title) pdf.set_font('Times', 'B', 24) pdf.cell(0, 10, 'Medium Grabber Links: ', 0, 1) pdf.set_font('Times', '', 12) if topic == 0: # Different structure of Home and other topic pages. if tag_len > 0: for i, l in zip(range(tag_len), unique_list): pdf.set_text_color(r=0, g=0, b=0) pdf.cell(0, 6, str(time.strftime("%Y-%m-%d %H:%M")), 0, 1) # Writing the Article text text = tag[i].text.encode( 'latin-1', 'ignore') # Eliminates any non-ASCII charachters text = text.decode( 'latin-1') # Again decodes the string into byte-form pdf.cell(0, 6, text, 0, 1) pdf.set_text_color(r=0, g=0, b=250) # Writing the Article link pdf.multi_cell(0, 6, str(l), 0) pdf.cell(0, 6, ' ', 0, 1) else: for i in range(tag_len): pdf.set_text_color(r=0, g=0, b=0) pdf.cell(0, 6, time.strftime("%Y-%m-%d %H:%M"), 0, 1) text = tag[i].text.encode('latin-1', 'ignore') text = text.decode('latin-1') pdf.cell(0, 6, text, 0, 1) l = tag[i].find_element_by_css_selector('a').get_attribute( 'href') pdf.set_text_color(r=0, g=0, b=250) pdf.multi_cell(0, 6, str(l), 0) pdf.cell(0, 6, ' ', 0, 1) pdf.output('output.pdf', 'F') print( 'FINISHED! Please check the output.pdf file for the links. Happy reading. :) ' ) elif txt_pdf == 2: f = open("output.txt", "a+", encoding='utf8' ) # Stores ouput in output.txt in the same file directory if topic == 0: # Different structure of Home and other topic pages. if tag_len > 0: for i, l in zip(range(tag_len), unique_list): f.write(time.strftime("%Y-%m-%d %H:%M") + '\n') f.write(tag[i].text) f.write('\nLink is --> ' + str(l) + '\n\n') else: for i in range(tag_len): f.write(time.strftime("%Y-%m-%d %H:%M") + '\n') f.write(tag[i].text) l = tag[i].find_element_by_css_selector('a').get_attribute( 'href') f.write('\nLink is --> ' + str(l) + '\n\n') f.close() else: print('Invalid input.') print('Finished') driver.close() duration = 2500 # millisecond freq = 440 # Hz if platform.system() == 'Windows': winsound.Beep(freq, duration)
def get(self, data = None): out_type = self.get_argument('type', 'html') components = [] components = self.get_query_arguments('action[]', []) multiply = int(self.get_argument('multiply', 5)) layout = self.get_argument('template', '70x40_simple') skip = int(self.get_argument('skip', 0)) #print("Soucastky..",components) if len(components) > 0: comp = list(self.mdb.stock.find({'_id' : {'$in' : components}})) else: comp = list(self.mdb.stock.find().sort([("category", 1), ("_id",1)])) page = 0 #print("Budeme tisknout:", comp) if layout == 'souhrn_01': autori = self.get_query_argument('autor', None) if not autori: autori = ['autory vlozite pridanim autoru do adresy s parametrem "autor"', 'autoru muze byt vice, pouzijte vice parametru', 'Například pridanim tohoto na konec adresy: &autor=Tester První'] datum = self.get_argument('datum', ">>pro specifikovani pridejte parametr 'datum' do GET parametru<<") page = 1 money_sum = 0 Err = [] print ("pozadovany format je:", layout) pdf = FPDF('P', 'mm', format='A4') pdf.set_auto_page_break(False) pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True) pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True) pdf.set_font('pt_sans', '', 12) pdf.add_page() pdf.set_xy(0, 40) pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2) pdf.set_xy(0, 46) pdf.cell(pdf.w, 0, 'Universal Scientific Technologies s.r.o.', align='C', ln=2) pdf.set_xy(20, 200) pdf.cell(1,0, 'Inventuru provedli:', ln=2) for x in autori: pdf.cell(1,20, x, ln=2) pdf.set_font('pt_sans', '', 8) pdf.set_xy(120, 288) pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) ) pdf.add_page() data = self.mdb.stock.aggregate([ {'$addFields': {'count': {'$sum': '$history.bilance'}}} ]) gen_time = datetime.datetime(2018, 10, 1) lastOid = ObjectId.from_datetime(gen_time) for i, component in enumerate(data): #for i, component in enumerate(list(data)[:30]): print(i, "=============================") print(component['_id']) try: ## Pokud je konec stránky if pdf.get_y() > pdf.h-20: pdf.line(10, pdf.get_y()+0.5, pdf.w-10, pdf.get_y()+0.5) pdf.set_font('pt_sans', '', 10) pdf.set_xy(150, pdf.get_y()+1) pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum)) pdf.add_page() ## Pokud je nová strana if page != pdf.page_no(): pdf.set_font('pt_sans', '', 8) page = pdf.page_no() pdf.set_xy(120, 288) pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) ) pdf.set_font('pt_sans', '', 11) pdf.set_xy(10, 10) pdf.cell(100, 5, 'Skladová položka') pdf.set_x(95) pdf.cell(10, 5, "Počet kusů", align='R') pdf.set_x(120) pdf.cell(10, 5, "Cena za 1ks", align='R') pdf.set_x(180) pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2) pdf.line(10, 15, pdf.w-10, 15) pdf.set_y(18) page_sum = 0 pdf.set_font('pt_sans', '', 10) count = component['count'] if count >0: price = 0 price_ks = 0 first_price = 0 pdf.set_x(10) pdf.cell(100, 5, component['_id']) pdf.set_x(95) pdf.cell(10, 5, "%5.d" %(count), align='R') pdf.set_x(10) pdf.cell(100, 5, "{:5.0f} {}".format(i, component['_id'])) inventura = False for x in reversed(component.get('history', [])): if x.get('operation', None) == 'inventory': print("inventura", x) if x['_id'].generation_time > lastOid.generation_time: print("#############") inventura = True count = x['absolute'] pdf.set_x(110) pdf.cell(1, 5, "i") break; pdf.set_font('pt_sans', '', 10) pdf.set_x(95) pdf.cell(10, 5, "{} j".format(count), align='R') rest = count for x in reversed(component.get('history', [])): if x.get('price', 0) > 0: if first_price == 0: first_price = x['price'] if x['bilance'] > 0: if x['bilance'] <= rest: price += x['price']*x['bilance'] rest -= x['bilance'] else: price += x['price']*rest rest = 0 print("Zbývá", rest, "ks, secteno", count-rest, "za cenu", price) if(count-rest): price += rest*first_price money_sum += price page_sum +=price if price == 0.0 and x.get('count', 0) > 0: Err.append('Polozka >%s< nulová cena, nenulový počet' %(component['_id'])) pdf.set_x(120) if count > 0: pdf.cell(10, 5, "%6.2f Kč" %(price/count), align='R') else: pdf.cell(10, 5, "%6.2f Kč" %(0), align='R') pdf.set_font('pt_sans-bold', '', 10) pdf.set_x(180) pdf.cell(10, 5, "%6.2f Kč" %(price), align='R') except Exception as e: Err.append('Err' + repr(e) + component['_id']) print(e) pdf.set_y(pdf.get_y()+4) pdf.line(10, pdf.get_y(), pdf.w-10, pdf.get_y()) pdf.set_font('pt_sans', '', 8) pdf.set_x(180) pdf.cell(10, 5, "Konec souhrnu", align='R') pdf.set_font('pt_sans', '', 10) pdf.set_xy(150, pdf.get_y()+3) pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum)) pdf.page = 1 pdf.set_xy(20,175) pdf.set_font('pt_sans', '', 12) pdf.cell(20,20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %(datum, money_sum)) if len(Err) > 0: pdf.set_xy(30,80) pdf.cell(1,6,"Pozor, chyby ve skladu:", ln=2) pdf.set_x(32) for ch in Err: pdf.cell(1,5,ch,ln=2) pdf.page = page print(autori) if layout == '105x74_simple': page = 0 page_cols = 2 page_rows = 4 page_cells = page_cols * page_rows cell_w = 105 cell_h = 75 print ("pozadovany format je:", layout) pdf = FPDF('P', 'mm', format='A4') pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True) pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True) pdf.set_font('pt_sans-bold', '', 12) pdf.set_auto_page_break(False) pdf.add_page() for i, component in enumerate(comp): i += skip id = component['_id'].strip().replace('/', '') code128.image(component['_id']).save("static/barcode/%s.png"%(id)) if i != 0 and i%(page_cells) == 0: page += 1 pdf.add_page() print("New PAGE --- ", i, i%page_cells) row = int(i/page_cols)-page*page_rows column = i%page_cols cell_x = column*cell_w cell_y = row*cell_h print(component) pdf.set_font('pt_sans-bold', '', 14) pdf.set_xy(cell_x+5, cell_y+5) pdf.cell(cell_w-10, 0, component['_id']) pdf.set_xy(cell_x, cell_y+10) pdf.image('static/barcode/%s.png'%(id), w = cell_w, h=10) pdf.set_font('pt_sans', '', 11) pdf.set_xy(cell_x+5, cell_y+23) try: pdf.multi_cell(cell_w-10, 5, component['description']) except Exception as e: pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e)) pdf.set_xy(cell_x+5, cell_y+cell_h-15) pdf.set_font('pt_sans', '', 8) pdf.cell(cell_w-10, 10, ', '.join(component['category']) + " | " + str(datetime.datetime.now()) + " | " + "UST") if layout == '70x42-3_simple': page = 0 page_cols = 3 page_rows = 7 page_cells = page_cols * page_rows cell_w = 210/page_cols cell_h = 297/page_rows print ("pozadovany format je:", layout) pdf = FPDF('P', 'mm', format='A4') pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True) pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True) pdf.set_font('pt_sans-bold', '', 12) pdf.set_auto_page_break(False) pdf.add_page() for i, component in enumerate(comp): i += skip id = component['name'].strip().replace('/', '_') code128.image(component['_id']).save("static/barcode/%s.png"%(id)) if i != 0 and i%(page_cells) == 0: page += 1 pdf.add_page() print("New PAGE --- ", i, i%page_cells) row = int(i/page_cols)-page*page_rows column = i%page_cols cell_x = column*cell_w cell_y = row*cell_h pdf.set_xy(cell_x+5, cell_y+6.75) if len(component['name'])<23: pdf.set_font('pt_sans-bold', '', 14) else: pdf.set_font('pt_sans-bold', '', 10) pdf.cell(cell_w-10, 0, component['name'][:35]) pdf.set_xy(cell_x+2.5, cell_y+9) pdf.image('static/barcode/%s.png'%(id), w = cell_w-5, h=7) pdf.set_font('pt_sans', '', 11) pdf.set_xy(cell_x+4, cell_y+20) try: pdf.multi_cell(cell_w-8, 4, component['description'][:185]) except Exception as e: pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e)) pdf.set_xy(cell_x+5, cell_y+cell_h-7) pdf.set_xy(cell_x+5, cell_y+13) pdf.set_font('pt_sans', '', 7.5) pdf.cell(cell_w-10, 10, ', '.join(component['category']) + " |" + str(datetime.date.today()) + "| " + component['_id']) if layout == '105x48_simple': page = 0 page_cols = 2 page_rows = 6 page_cells = page_cols * page_rows #cell_w = 105 #cell_h = 48 cell_w = 210/page_cols cell_h = 297/page_rows print ("pozadovany format je:", layout) pdf = FPDF('P', 'mm', format='A4') pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True) pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True) pdf.set_font('pt_sans-bold', '', 12) pdf.set_auto_page_break(False) pdf.add_page() for i, component in enumerate(comp): i += skip id = component['_id'].strip().replace('/', '') code128.image(component['_id']).save("static/barcode/%s.png"%(id)) if i != 0 and i%(page_cells) == 0: page += 1 pdf.add_page() print("New PAGE --- ", i, i%page_cells) row = int(i/page_cols)-page*page_rows column = i%page_cols cell_x = column*cell_w cell_y = row*cell_h print(component) pdf.set_font('pt_sans-bold', '', 14) pdf.set_xy(cell_x+5, cell_y+5) pdf.cell(cell_w-10, 0, component['_id']) pdf.set_xy(cell_x, cell_y+10) pdf.image('static/barcode/%s.png'%(id), w = cell_w, h=10) pdf.set_font('pt_sans', '', 10) pdf.set_xy(cell_x+5, cell_y+20) try: pdf.multi_cell(cell_w-10, 4, component['description'][:275]) except Exception as e: pdf.multi_cell(cell_w-10, 4, "ERR" + repr(e)) pdf.set_xy(cell_x+5, cell_y+cell_h-10) pdf.set_font('pt_sans', '', 8) pdf.cell(cell_w-10, 10, ', '.join(component['category']) + " | " + str(datetime.datetime.now()) + " | " + "UST") elif layout == '105x48_panorama': page = 0 page_cols = 6 page_rows = 2 page_cells = page_cols * page_rows cell_w = 48 cell_h = 105 print ("pozadovany format je:", layout) pdf = FPDF('L', 'mm', format='A4') pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True) pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True) pdf.set_font('pt_sans-bold', '', 12) pdf.set_auto_page_break(False) pdf.add_page() for i, component in enumerate(comp): i += skip id = component['_id'].strip().replace('/', '') code128.image(component['_id']).save("static/barcode/%s.png"%(id)) if i != 0 and i%(page_cells) == 0: page += 1 pdf.add_page() print("New PAGE --- ", i, i%page_cells) row = int(i/page_cols)-page*page_rows column = i%page_cols cell_x = column*cell_w cell_y = row*cell_h print(component) pdf.set_font('pt_sans-bold', '', 14) pdf.set_xy(cell_x+5, cell_y+5) pdf.cell(cell_w-10, 0, component['_id']) pdf.set_xy(cell_x, cell_y+cell_h) pdf.rotate(90) pdf.image('static/barcode/%s.png'%(id), w = cell_h-5, h=10) pdf.rotate(0) pdf.set_font('pt_sans', '', 11) pdf.set_xy(cell_x+8, cell_y+20) try: pdf.multi_cell(cell_w-10, 5, component['description']) except Exception as e: pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e)) pdf.set_xy(cell_x+5, cell_y+cell_h-15) pdf.set_font('pt_sans', '', 8) pdf.cell(cell_w-10, 10, ', '.join(component['category']) + " | " + str(datetime.datetime.now()) + " | " + "UST") pdf.output("static/tmp/sestava.pdf") with open('static/tmp/sestava.pdf', 'rb') as f: self.set_header("Content-Type", 'application/pdf; charset="utf-8"') self.set_header("Content-Disposition", "inline; filename=UST_tiskova_sestava.pdf") self.write(f.read()) f.close()
#!/usr/bin/env python "Simple test to check alias_nb_pages replacement under unicode fonts" from fpdf import FPDF pdf=FPDF() # set default alias: {nb} that will be replaced with total page count pdf.alias_nb_pages() # Add a Unicode font (uses UTF-8) pdf.add_font('DejaVu','','DejaVuSansCondensed.ttf',uni=True) pdf.set_font('DejaVu','',14) for i in range(5): pdf.add_page() pdf.set_font('Arial','B',16) pdf.cell(40,10,'Hello World! {nb}') pdf.set_font('DejaVu','',14) pdf.cell(40,10,'Hello World! unicode {nb}') fn = 'nb_pages.pdf' pdf.output(fn, 'F') import os try: os.startfile(fn) except: os.system("xdg-open \"%s\"" % fn)
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)
__author__ = 'pierangelo orizio' import json import urllib from connection import * from fpdf import FPDF data = connessione("https://myshopfurniture.com/api/moduli/") print(data) pdf = FPDF() pdf = FPDF('L', 'mm', 'A4') pdf.alias_nb_pages() pdf.add_page() pdf.set_font('Times', '', 12) pdf.cell(150, 10, "Descrizione", 1) pdf.cell(50, 10, "Misure", 1, 1) for d in data: pdf.cell(150, 10, d["fields"]["name"], 1) pdf.cell(50, 10, d["fields"]["size"], 1, 1) pdf.output('tuto2.pdf', 'F') for d in data: print(d["fields"]["name"])
def grab(): browser = request.user_agent.browser topic = request.form.get("topic") txt_pdf = request.form.get("format") if browser == "Firefox": options = Options() options.headless = True driver = webdriver.Firefox(options=options) else: options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) options.add_argument('--disable-gpu') options.add_argument('--headless') options.add_argument('--incognito') driver = webdriver.Chrome(chrome_options=options) driver.get("https://medium.com/") driver.implicitly_wait(10) #action = webdriver.ActionChains(driver) time.sleep(2) login = driver.find_element_by_link_text('Sign in').click() try: login_google = driver.find_element_by_xpath('/html/body/div[4]/div/div/section/div[1]/div/button[1]').click() except TimeoutException: pass # You can log-in using google only__name__ print(" Logging in to Medium by using Google ") time.sleep(3) #assert "Sign in – Google accounts" in driver.title user = driver.find_element_by_xpath('//*[@id="identifierId"]') # fetch your email or phone number as registered in Medium user.send_keys(username) # Provide your email or registered phone number here nextButton = driver.find_element_by_xpath('//*[@id="identifierNext"]/content') nextButton.click() time.sleep(2) user = driver.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input') # fetch your password to login user.send_keys(password) LOG = driver.find_element_by_xpath('//*[@id="passwordNext"]/content').click() print('LOGIN SUCCESSFUL \n') if topic == "Home": t = driver.get("https://medium.com/") else: t = driver.get("https://medium.com/topic/"+topic) print('The list of articles under this topic are saved in output file : ') # print('Just scan through the file and open the link whichever you want to read :) \n') print('The program is crawling down the webpage to gather links of around past 50 atricles. This may take around a minute or two.') # To Scroll to the bottom/ a portion of page last_height = 1000 while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) new_height = driver.execute_script("return document.body.scrollHeight") if new_height >= last_height: break tag = driver.find_elements_by_tag_name('h3') tag_len = len(tag) links = [i.get_attribute('href') for i in driver.find_elements_by_xpath("//a[@data-action-source]")] unique_list = list(OrderedDict(zip(links, repeat(None)))) # To remove duplicates from list if txt_pdf == "PDF": title = 'Medium Grabber' pdf = FPDF() pdf.alias_nb_pages() pdf.add_page() pdf.set_title(title) pdf.set_font('Times', 'B', 24) pdf.cell(0, 10, 'Medium Grabber Links: ', 0, 1) pdf.set_font('Times', '', 12) if topic == "Home": # Different structure of Home and other topic pages. if tag_len > 0: for i,l in zip(range(tag_len), unique_list): pdf.set_text_color(r=0, g=0, b=0) pdf.cell(0, 6, str(time.strftime("%Y-%m-%d %H:%M")), 0, 1) # Writing the Article text text = tag[i].text.encode('latin-1', 'ignore') # Eliminates any non-ASCII charachters text = text.decode('latin-1') # Again decodes the string into byte-form pdf.cell(0, 6, text , 0, 1) pdf.set_text_color(r=0, g=0, b=250) # Writing the Article link pdf.multi_cell(0, 6, str(l), 0) pdf.cell(0, 6, ' ', 0, 1) else: for i in range(tag_len): pdf.set_text_color(r=0, g=0, b=0) pdf.cell(0, 6, time.strftime("%Y-%m-%d %H:%M"), 0, 1) text = tag[i].text.encode('latin-1', 'ignore') text = text.decode('latin-1') pdf.cell(0, 6,text, 0, 1) l = tag[i].find_element_by_css_selector('a').get_attribute('href') pdf.set_text_color(r=0, g=0, b=250) pdf.multi_cell(0, 6, str(l), 0) pdf.cell(0, 6, ' ', 0, 1) pdf.output('static/output.pdf', 'F') print('FINISHED! Please check the output.pdf file for the links. Happy reading. :) ') else: f= open("static/output.txt","w+", encoding='utf-8') # Stores ouput in output.txt in the same file directory if topic == "Home": # Different structure of Home and other topic pages. if tag_len > 0: for i,l in zip(range(tag_len), unique_list): f.write(time.strftime("%Y-%m-%d %H:%M") + '\n') f.write(tag[i].text) f.write('\nLink is --> ' + str(l) + '\n\n') else: for i in range(tag_len): f.write(time.strftime("%Y-%m-%d %H:%M") + '\n') f.write(tag[i].text) l = tag[i].find_element_by_css_selector('a').get_attribute('href') f.write('\nLink is --> ' + str(l) + '\n\n') f.close() print('FINISHED! Please check the output.txt file for the links. Happy reading. :) ') driver.close() duration = 2500 # millisecond freq = 440 # Hz if platform.system()=='Windows': winsound.Beep(freq, duration) return txt_pdf
def setava_01(self, stock_taking): comp = list(self.mdb.stock.find().sort([("category", 1), ("_id",1)])) autori = stock_taking['author'].strip().split(',') datum = str(stock_taking['closed'].date()) filename = "{}_{}.pdf".format(stock_taking['_id'], ''.join(stock_taking['name'].split())) page = 1 money_sum = 0 Err = [] pdf = FPDF('P', 'mm', format='A4') pdf.set_auto_page_break(False) pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True) pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True) pdf.set_font('pt_sans', '', 12) pdf.add_page() pdf.set_xy(0, 40) pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2) pdf.set_xy(0, 46) pdf.cell(pdf.w, 0, 'Universal Scientific Technologies s.r.o.', align='C', ln=2) pdf.set_xy(20, 200) pdf.cell(1,0, 'Inventuru provedli:', ln=2) for x in autori: pdf.cell(1,20, x, ln=2) pdf.set_font('pt_sans', '', 8) pdf.set_xy(120, 288) pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) ) pdf.add_page() ref = self.get_argument('ref') value = self.get_argument('value') c_name = self.get_argument('name') package = self.get_argument('package') ust_id = self.get_argument('ust_id') price_predicted = self.get_argument('price_predicted', 0.0) price_store = self.get_argument('price_store', 0.0) price_final = self.get_argument('price_final', 0.0) description = self.get_argument('description', '') print(ref.split(',')) data = self.mdb.stock.aggregate([ {'$addFields': {'count': {'$sum': '$history.bilance'}}} ]) if exist.count() > 0: update = self.mdb.production.update( { '_id': bson.ObjectId(name), "components.Ref": c },{ "$set": { "components.$.Ref": c, "components.$.Value": value, "components.$.Package": package, "components.$.UST_ID": ust_id, "components.$.price_predicted": price_predicted, "components.$.price_store": price_store, "components.$.price_final": price_final, "components.$.Note": description, } }, upsert = True) else: print("NOVA POLOZKA") update = self.mdb.production.update( { '_id': bson.ObjectId(name) },{ "$push": {'components': { "Ref": c, "Package": package, "Value": value, "UST_ID": ust_id, "price_predicted": price_predicted, "price_store": price_store, "price_final": price_final, "Note": description } } }) gen_time = datetime.datetime(2018, 10, 1) lastOid = ObjectId.from_datetime(gen_time) for i, component in enumerate(data): #for i, component in enumerate(list(data)[:30]): #print(i, "=============================") print(component['_id']) try: ## Pokud je konec stránky if pdf.get_y() > pdf.h-20: pdf.line(10, pdf.get_y()+0.5, pdf.w-10, pdf.get_y()+0.5) pdf.set_font('pt_sans', '', 10) pdf.set_xy(150, pdf.get_y()+1) pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum)) pdf.add_page() ## Pokud je nová strana if page != pdf.page_no(): pdf.set_font('pt_sans', '', 8) page = pdf.page_no() pdf.set_xy(120, 288) pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) ) pdf.set_font('pt_sans', '', 11) pdf.set_xy(10, 10) pdf.cell(100, 5, 'Skladová položka') pdf.set_x(95) pdf.cell(10, 5, "Počet kusů", align='R') #pdf.set_x(120) #pdf.cell(10, 5, "Cena za 1ks", align='R') pdf.set_x(180) pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2) pdf.line(10, 15, pdf.w-10, 15) pdf.set_y(18) page_sum = 0 pdf.set_font('pt_sans', '', 10) count = component['count'] price = 0 price_ks = 0 first_price = 0 ref = self.get_argument('Ref') val = self.get_argument('Val') package = self.get_argument('Package') posx = self.get_argument('PosX') posy = self.get_argument('PosY') rot = self.get_argument('Rot') side = self.get_argument('Side') tstep = self.get_argument('Tstep') inventura = False for x in reversed(component.get('history', [])): if x.get('operation', None) == 'inventory': #TODO: tady porovnávat, jesti to patri do stejne kampane. Ne na zaklade casu ale ID if x['_id'].generation_time > lastOid.generation_time: inventura = True count = x['absolute'] #pdf.set_x(110) #pdf.cell(1, 5, "i") break; if count > 0: rest = count for x in reversed(component.get('history', [])): if x.get('price', 0) > 0: if first_price == 0: first_price = x['price'] if x['bilance'] > 0: if x['bilance'] <= rest: price += x['price']*x['bilance'] rest -= x['bilance'] else: price += x['price']*rest rest = 0 print("Zbývá", rest, "ks, secteno", count-rest, "za cenu", price) if(count-rest): price += rest*first_price money_sum += price page_sum +=price if price == 0.0 and x.get('count', 0) > 0: Err.append('Polozka >%s< nulová cena, nenulový počet' %(component['_id'])) #pdf.set_x(120) #if count > 0: pdf.cell(10, 5, "%6.2f Kč" %(price/count), align='R') #else: pdf.cell(10, 5, "%6.2f Kč" %(0), align='R') pdf.set_font('pt_sans', '', 10) pdf.set_x(95) pdf.cell(10, 5, "{} j".format(count), align='R') pdf.set_x(10) pdf.cell(100, 5, "{:5.0f} {}".format(i, component['_id'])) pdf.set_font('pt_sans-bold', '', 10) pdf.set_x(180) pdf.cell(10, 5, "%6.2f Kč" %(price), align='R') except Exception as e: Err.append('Err' + repr(e) + component['_id']) print(e) if count > 0: pdf.set_y(pdf.get_y()+4) pdf.line(10, pdf.get_y(), pdf.w-10, pdf.get_y()) pdf.set_font('pt_sans', '', 8) pdf.set_x(180) pdf.cell(10, 5, "Konec souhrnu", align='R') #pdf.set_font('pt_sans', '', 10) #pdf.set_xy(150, pdf.get_y()+3) #pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum)) pdf.page = 1 pdf.set_xy(20,175) pdf.set_font('pt_sans', '', 12) pdf.cell(20,20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %(datum, money_sum)) if len(Err) > 0: pdf.set_xy(30,80) pdf.cell(1,6,"Pozor, chyby ve skladu:", ln=2) pdf.set_x(32) for ch in Err: pdf.cell(1,5,ch,ln=2) pdf.page = page pdf.output("static/tmp/sestava.pdf") year = datum[:4] filename = "{}.pdf".format(''.join(stock_taking['name'].split(' '))) foldername = os.path.join(tornado.options.options.owncloud_root, 'accounting', year, 'stocktaking', filename) foldername = save_file(self.mdb, foldername) return upload_file(self.oc, 'static/tmp/sestava.pdf', foldername)
class PDF_Gen(FPDF): dirpath = os.getcwd() #find script's root # #Addapted PHP code from https://gist.github.com/benshimmin/4088493. #Scale to fit and centre-align images #I teaked to A4 @ 300 dpi - 3507x2480 pix DPI = 300 MM_IN_INCH = 25.4 A4_HEIGHT = 210 A4_WIDTH = 297 #tweak these values (in pixels) MAX_WIDTH = 3507 MAX_HEIGHT = 2480 def pixelsToMM(self, val): #funct to convert pixels to mm val = (val * self.MM_IN_INCH) / self.DPI return val def footer(self): #sets pages footers with page number self.set_y(-15) self.set_font('Arial', 'I', 9) self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'R') def get_imgs_path( self, lista, img_path): #returns the list of image_files in book _id directory for file in os.listdir(img_path): if file.endswith(".png"): lista.append(file) return lista def resizeToFit(self, imgFilename ): #funct to return 'new' image sizes for centralization im = Image.open(imgFilename) sizes = list(im.size) width = sizes[0] height = sizes[1] widthScale = self.MAX_WIDTH / width heightScale = self.MAX_HEIGHT / height scale = min(widthScale, heightScale) return [ round(self.pixelsToMM(scale * width)), round(self.pixelsToMM(scale * height)) ] def centreImage(self, img_file): #function to centralize images in pdf page newsizes = list(self.resizeToFit(img_file)) width = newsizes[0] height = newsizes[1] #sets image withing right coordenates self.pdf.image(img_file, (self.A4_HEIGHT - width) / 2, (self.A4_WIDTH - height) / 2, width, height) def img_to_pdf(self, book_title, book_id): #creates the pdf lista = [] img_path = os.path.join(self.dirpath, book_id, "") lista = self.get_imgs_path( lista, img_path) #get the list of imgs in book_id directory if len(lista) != 0: self.pdf = FPDF() for i in range(len(lista)): #FPDF options print("Writing page nº: {page} of {total}".format( page=i + 1, total=len(lista))) self.pdf.set_font('Times', '', 12) self.pdf.add_page('P') self.centreImage(str(os.path.join(img_path, lista[i]))) self.pdf.alias_nb_pages() print( "Saving file, please wait. It can take some time if it is a big book!" ) self.pdf.output(book_title + '_IMG.pdf', 'F') #saves pdf_IMG file print("PDF '{book_title}' saved in script's root!".format( book_title='{title}(...)'.format(title=book_title[:20]))) print("Deleting %i temporary image page files from root." % (len(lista) + 1)) # shutil.rmtree(img_path) #delestes book_id directory def main(self, book_title, book_id): self.img_to_pdf(book_title, book_id)
def setava_01(self, stock_taking): comp = list(self.mdb.stock.find().sort([("category", 1), ("_id", 1)])) autori = stock_taking['author'].strip().split(',') datum = str(stock_taking['closed'].date()) filename = "{}_{}.pdf".format(stock_taking['_id'], ''.join(stock_taking['name'].split())) print("Generovani prehledu inventury") print("Od:", autori) print("Kdy:", datum) print("Soubor,", filename) page = 1 money_sum = 0 Err = [] pdf = FPDF('P', 'mm', format='A4') pdf.set_auto_page_break(False) pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True) pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True) pdf.set_font('pt_sans', '', 12) pdf.add_page() pdf.set_xy(0, 40) pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2) pdf.set_xy(0, 46) pdf.cell(pdf.w, 0, 'Universal Scientific Technologies s.r.o.', align='C', ln=2) pdf.set_xy(20, 200) pdf.cell(1, 0, 'Inventuru provedli:', ln=2) for x in autori: pdf.cell(1, 20, x, ln=2) pdf.set_font('pt_sans', '', 8) pdf.set_xy(120, 288) pdf.cell( 10, 0, "Vytvořeno %s, strana %s z %s" % (datetime.datetime.now().strftime("%d. %m. %Y, %H:%M:%S"), page, pdf.alias_nb_pages())) pdf.add_page() data = self.mdb.stock.aggregate([{ '$addFields': { 'count': { '$sum': '$history.bilance' } } }]) query = [ { "$group": { '_id': '$pid', 'operations': { "$push": "$$ROOT" } } }, { "$addFields": { "packet_count": { "$sum": "$operations.count" }, "packet_reserv": { "$sum": "$operations.reserv" }, "packet_ordered": { "$sum": "$operations.ordered" }, "packet_price": { "$function": { "body": '''function(prices, counts) { let total_counts = Array.sum(counts); var tmp_count = total_counts; var total_price = 0; var c = counts.reverse(); var p = prices.reverse(); for(i in c){ if(c[i] > 0){ if(c[i] < tmp_count){ total_price += (c[i]*p[i]); tmp_count -= c[i] } else{ total_price += (tmp_count*p[i]); tmp_count = 0; } } } return total_price; }''', "args": ["$operations.unit_price", "$operations.count"], "lang": "js" } } } }, #{"$addFields": {"comp": "$pid"}}, { "$lookup": { "from": "stock", "let": { "pid": "$_id" }, "pipeline": [ { "$match": { "$expr": { "$in": ["$$pid", "$packets._id"] } } }, { "$unwind": "$packets" }, { "$match": { "$expr": { "$eq": ["$packets._id", "$$pid"] } } }, ], "as": "component" } }, { "$set": { "component": { "$first": "$component" } } }, { "$lookup": { "from": "store_positions_complete", "localField": "component.packets.position", "foreignField": "_id", "as": "position_info", } }, { "$set": { "position_info": { "$first": "$position_info" } } }, { "$group": { '_id': '$component._id', 'packets': { "$push": "$$ROOT" }, #'component': { "$push": "$component" } } }, { "$sort": { "_id": 1 } } #{ "$sort": {"position_info.warehouse.code": 1, "position_info.path_string": 1, "position_info.name": 1, "component.name":1}}, #{ "$project": { "packet_count": 1, "packet_reserv": 1, "packet_price": 1, "packet_ordered": 1, "_id": 0} }, # { "$group": { # '_id': 'null', # 'count': {"$sum": '$packet_count'}, # 'price': {"$sum": '$packet_price'}, # 'reserv': {"$sum": '$packet_reserv'}, # 'ordered': {"$sum": '$packet_ordered'}, # } # } ] data = self.mdb.stock_operation.aggregate(query) gen_time = datetime.datetime(2018, 10, 1) lastOid = ObjectId.from_datetime(gen_time) number_components = 0 number_packets = 0 for i, component in enumerate(data): print(" ") number_components += 1 # print(component['_id'], component) component['packets_count'] = [] component['packets_prices'] = [] try: ## Pokud je konec stránky if pdf.get_y() > pdf.h - 20: pdf.line(10, pdf.get_y() + 0.5, pdf.w - 10, pdf.get_y() + 0.5) pdf.set_font('pt_sans', '', 10) pdf.set_xy(150, pdf.get_y() + 1) pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum)) pdf.add_page() ## Pokud je nová strana if page != pdf.page_no(): pdf.set_font('pt_sans', '', 8) page = pdf.page_no() pdf.set_xy(120, 288) pdf.cell( 10, 0, "Vytvořeno %s, strana %s z %s" % (datetime.datetime.now().strftime("%d. %m. %Y, %H:%M:%S"), page, pdf.alias_nb_pages())) pdf.set_font('pt_sans', '', 11) pdf.set_xy(10, 10) pdf.cell(100, 5, 'Skladová položka') pdf.set_x(105) pdf.cell(10, 5, "Počet kusů", align='R') #pdf.set_x(120) #pdf.cell(10, 5, "Cena za 1ks", align='R') pdf.set_x(180) pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2) pdf.line(10, 15, pdf.w - 10, 15) pdf.set_y(18) page_sum = 0 pdf.set_font('pt_sans', '', 10) count = 0 price = 0 packets = "" for j, packet in enumerate(component['packets']): number_packets += 1 pcount = packet['packet_count'] pprice = round(packet['packet_price'], 2) component['packets_count'].append(pcount) component['packets_prices'].append(pprice) count += pcount price += pprice packets += " {},".format(pprice) #pac_info = get_packet_count(self.mdb, packet['_id']) #print("C: {}, {}, ".format(pcount-pac_info['packet_count'], pprice-pac_info['packet_price'])) price_ks = 0 first_price = 0 inventura = False if count > 0: money_sum += price page_sum += price if price == 0.0: # and x.get('count', 0) > 0: Err.append( 'Polozka >%s< nulová cena, nenulový počet (%s)' % (component['_id'], component.get('name', '---'))) pdf.set_x(10) pdf.cell( 100, 5, "{:5.0f} {} ({})".format(i, packet['component']['name'], len(component['packets']))) pdf.set_font('pt_sans', '', 10) pdf.set_x(105) pdf.cell(10, 5, "{} j".format(count), align='R') # pdf.set_x(107) # pdf.cell(10, 5, repr(component['packets_count']) + " " +repr(component['packets_prices']), align='L') pdf.set_font('pt_sans-bold', '', 10) pdf.set_x(180) pdf.cell(10, 5, "%6.2f Kč" % (price), align='R') except Exception as e: Err.append('Err' + repr(e) + repr(component['_id'])) print(e) if count > 0: pdf.set_y(pdf.get_y() + 4) pdf.line(10, pdf.get_y(), pdf.w - 10, pdf.get_y()) pdf.set_font('pt_sans', '', 8) pdf.set_x(180) pdf.cell(10, 5, "Konec souhrnu", align='R') print("Celková cena", money_sum) print("Probematicke", len(Err)) print("Polozek:", number_components) print("Pocet sacku:", number_packets) pdf.page = 1 pdf.set_xy(20, 175) pdf.set_font('pt_sans', '', 12) pdf.cell( 20, 20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" % (datum, money_sum)) if len(Err) > 0: pdf.set_xy(30, 80) pdf.cell(1, 6, "Pozor, chyby ve skladu:", ln=2) pdf.set_x(32) for ch in Err: pdf.cell(1, 5, ch, ln=2) pdf.page = page pdf.output("static/tmp/sestava.pdf") year = datum[:4] filename = "{}.pdf".format(''.join(stock_taking['name'].split(' '))) foldername = os.path.join(tornado.options.options.owncloud_root, 'accounting', year, 'stocktaking', filename) foldername = save_file(self.mdb, foldername) return upload_file(self.oc, 'static/tmp/sestava.pdf', foldername)
def create_pdf(**kwargs): """Build the PDF file from user-supplied information""" # Dictionary of variables collected from gui, to be passed to method_graf() variabledic = {"methodofservice": kwargs['servicemethod'], "documents": kwargs['docserved'].upper(), "target": kwargs['personserved'], "dateandtime": kwargs['dateserved'] + ", at " + kwargs['timeserved'], "location": kwargs['servelocation'], "subperson": kwargs['subname'], "subrelation": kwargs['subrelation'], "parentname": kwargs['parentname'], "tempguard": kwargs['guardname'], "committed": kwargs['committed'], "adminname": kwargs['adminname'], "agentname": kwargs['agentname'], } pdf=FPDF("P", "pt", "Letter") pdf.set_margins(36,36) pdf.alias_nb_pages() pdf.add_page() # State, County & Court pdf.set_font("Times", "", 12) pdf.multi_cell(h = 18, w = 540, align = "L", txt = ( "IN THE "+kwargs['court'].upper()+" COURT OF\n"+ kwargs['county'].upper()+" COUNTY, "+kwargs['state'].upper())) pdf.ln(30) # Plaintiff pcursor = pdf.get_y() pdf.multi_cell(h=18, w=400, align = "L", txt=kwargs['plaintiff'].upper()) newpcursor = pdf.get_y() pdf.set_xy(400, pcursor) pdf.cell(w = 0, align = "R", txt = "PLAINTIFF") pdf.set_xy(0, newpcursor) pdf.ln(18) # Case Number pdf.cell(h = 18, w = 20, align = "L", txt = "V.") pdf.cell(h = 18, w = 500, align = "C", txt = "CASE NO. "+kwargs['caseno'].upper()) pdf.ln(30) # Defendant pcursor = pdf.get_y() pdf.multi_cell(h=18, w=400, align = "L", txt=kwargs['defendant'].upper()) newpcursor = pdf.get_y() pdf.set_xy(400, pcursor) pdf.cell(h = 18, w = 0, align = "R", txt = "DEFENDANT") pdf.set_xy(0, newpcursor) pdf.ln(18) # Title pdf.set_font("Times", "U", 12) pdf.cell(h = 24, w = 0, align = "C", txt = "AFFIDAVIT OF SERVICE") pdf.ln(36) # Commencement pdf.set_font("Times", "", 12) pdf.multi_cell(h = 30, w = 540, align = "L", txt = ( " Comes now " + kwargs['servername'] + ", who, being duly " "sworn, deposes and says:")) # Paragraph with details of service (multi-line), called from method_graf() function pdf.multi_cell(h = 30, w = 540, align = "L", txt = method_graf(**variabledic)) # Comments if len(kwargs['comments']) > 0: pdf.multi_cell(h = 30, w = 540, align = "L", txt = " " + kwargs['comments']) # Not a party/No interest/Further affiant sayeth not, etc. pdf.multi_cell(h = 30, w = 540, align = "L", txt = ( " I am not a party to this action, and I have no interest in it. \n" " Further affiant sayeth not.")) pdf.ln(40) # Signature/Notary section pdf.line(270,pdf.get_y(),540,pdf.get_y()) pdf.set_x(270) pdf.cell(h = 24, w = 0, align = "L", txt = kwargs['servername']) pdf.ln(24) pdf.set_x(270) pdf.multi_cell(h = 18, w = 0, align = "L", txt = kwargs['serveraddress']) pdf.ln(24) pdf.set_x(36) pdf.cell(h = 18, w = 270, align = "L", txt = "Subscribed and sworn to before me this date:") pdf.line(270,pdf.get_y()+18,540,pdf.get_y()+18) pdf.ln(40) pdf.line(270,pdf.get_y()+18,540,pdf.get_y()+18) pdf.ln(24) pdf.set_x(270) pdf.cell(h = 18, w = 270, align = "L", txt = "Notary Public") pdf.ln(36) pdf.set_x(270) pdf.cell(h = 18, w = 270, align = "L", txt = "My commission expires:") pdf.line(400,pdf.get_y()+18,540,pdf.get_y()+18) # write PDF pdf.output("app/static/pdfs/your.pdf", "F")
class Report(object): """ PDF report for plots generated on the basis of raw eye-tracking data. """ def __init__(self, file_handler, report_file_name, open_after_download_flag, properties): self.file_handler = file_handler self.open_after_download = open_after_download_flag self.properties = properties self.font_path = join(self.file_handler.fonts_dir, 'DejaVuSans.ttf') # unicode font self.pdf = FPDF(orientation='P', unit='mm', format='A4') fpdf.set_global("FPDF_CACHE_MODE", 1) # get date & time current_date = datetime.now().strftime("%d.%m.%Y %H:%M") current_timestamp = str(time.time()).replace('.', '') self.title = properties.report_title self.subtitle = properties.report_subtitle self.subtitle_date = properties.subtitle_with_date.format(current_date) self.subtitle_rec_dir = properties.subtitle_with_rec_dir_path.format( self.file_handler.recording_dir) self.subtitle_export_dir = properties.subtitle_with_exported_dir_path.format( self.file_handler.exports_dir) self.pdf_file_name = properties.pdf_report_file_name.format( current_timestamp ) if report_file_name == "" else report_file_name + ".pdf" # table with fixation_report.csv data self.fixation_detector_table_description = properties.fixation_detector_table_description self.parameter_table_header_name = properties.fixation_detector_settings_values_param self.value_table_header_name = properties.fixation_detector_settings_values_val self.target_file_path = join(self.file_handler.downloads_dir, self.pdf_file_name) self.title_font_size = 25 self.subtitle_font_size = 20 self.subsection_title_fontsize = 25 self.paragraph_fontsize = 14 def add_first_page(self): """ Creates report first page with: title, date, # recording_directory # and exports_directory """ title_line_break_value = 90 self.pdf.add_page() # add first report page self.pdf.ln(title_line_break_value) self.pdf.alias_nb_pages() # Create the special value {nb} self.pdf.set_margins(left=10.00, top=10.00, right=10.00) self.pdf.set_font("Courier", 'B', size=self.title_font_size) self.pdf.cell(w=190, h=15, txt=self.title, ln=1, align="C") self.pdf.set_font("Courier", 'B', size=self.subtitle_font_size) self.pdf.cell(w=190, h=10, txt=self.subtitle, ln=1, align="C") self.pdf.set_font("Arial", size=10) self.pdf.cell(w=190, h=10, txt=self.subtitle_date, ln=1, align="C") left = self.pdf.l_margin right = self.pdf.r_margin top = self.pdf.t_margin bottom = self.pdf.b_margin # Effective page width and height epw = self.pdf.w - left - right eph = self.pdf.h - top - bottom self.pdf.rect(left, top, w=epw, h=eph) # draw margins def add_subsection(self, title, description): self.pdf.add_page() self.pdf.set_font("Courier", 'B', size=self.subsection_title_fontsize) self.pdf.cell(w=190, h=15, txt=title, ln=1, align="L") self.add_unicode_font(14) self.pdf.multi_cell(w=190, h=10, txt=self.pdf.normalize_text(description)) def add_fixation_report(self, fixation_report_obj): self.add_unicode_font(14) epw = self.pdf.w - 2 * self.pdf.l_margin # effective page width, or just epw col_width = epw / 2 # distribute columns content evenly across table and page data = { self.parameter_table_header_name: self.value_table_header_name, "max_dispersion": fixation_report_obj.max_dispersion, "min_duration": fixation_report_obj.min_duration, "max_duration": fixation_report_obj.max_duration, "fixation_count": fixation_report_obj.fixation_count } th = self.pdf.font_size self.pdf.multi_cell(w=190, h=8, txt=self.fixation_detector_table_description, align="L") counter = 0 for key, value in data.items(): counter += 1 if counter == 1: self.pdf.cell(w=col_width, h=(2 * th), txt=self.pdf.normalize_text(str(key)), border=1, align="C") self.pdf.cell(w=col_width, h=(2 * th), txt=self.pdf.normalize_text(str(value)), border=1, align="C") self.pdf.set_font(family="font", size=10) else: self.pdf.cell(col_width, 2 * th, self.pdf.normalize_text(str(key)), border=1, align="C") self.pdf.cell(col_width, 2 * th, self.pdf.normalize_text(str(value)), border=1, align="C") self.pdf.ln(2 * th) def add_plot(self, plot): self.pdf.add_page() try: self.pdf.image(plot.image_path, w=190) except FileNotFoundError as exception: logger.error(f"NOT FOUND file {plot.image_path}") print(exception) self.add_unicode_font(plot.fontsize) self.pdf.multi_cell(w=190, h=10, txt=self.pdf.normalize_text(plot.description)) def save_report(self): """ Saves report in /exports/../downloads directory """ logger.info(f'Save report into {self.target_file_path}') self.pdf.output(self.target_file_path) logger.info(f"Report '{self.pdf_file_name}' saved") logger.info(f"Report directory: {self.file_handler.downloads_dir}") if self.open_after_download: try: startfile(self.target_file_path) except: system("xdg-open \"%s\"" % self.target_file_path) def add_unicode_font(self, fontsize): print("FONT PATH: \n", self.font_path) self.pdf.add_font(family="font", fname=self.font_path, uni=True) self.pdf.set_font(family="font", size=fontsize)
def get(self, name): info = list(self.mdb.production.aggregate([ {'$match': {'_id': bson.ObjectId(name)}}, # {'$sort': {'components.Ref': 1}}, # # {"$lookup":{ # # "from": 'stock', # # "localField": 'UST_ID', # # "foreignField": '_id', # # "as": 'stock' # # }} ]))[0] print(info) out = list(self.mdb.production.aggregate([ {'$match': {'_id': bson.ObjectId(name)}}, {'$unwind': '$components'}, {'$project': {'components': 1}}, {'$sort': {'components.Ref': 1}}, {'$group':{ '_id': {'UST_ID': '$components.UST_ID', 'Value': '$components.Value', 'Footprint': '$components.Footprint', 'Distributor': '$components.Distributor', 'Datasheet': '$components.Datasheet', 'stock_count': '$components.stock_count', 'note': '$components.note'}, 'Ref': {'$push': '$components.Ref'}, 'category': {'$push': '$components.category'}, 'count': {'$sum': 1}, }}, {"$addFields":{"cUST_ID": {"$convert":{ "input": '$_id.UST_ID', "to": 'objectId', "onError": "Err", "onNull": "null" }}}}, {"$lookup":{ "from": 'stock', "localField": 'cUST_ID', "foreignField": '_id', "as": 'stock' }} ])) pdf = FPDF('P', 'mm', format='A4') pdf.set_auto_page_break(False) pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True) pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True) pdf.add_page() pdf.set_font('pt_sans', '', 12) pdf.set_xy(10, 9) pdf.cell(0,5, info.get('name', name)) pdf.set_font('pt_sans', '', 8) pdf.set_y(20) pdf.cell(0,5, info.get('description', name)) pdf.set_font('pt_sans', '', 8) pdf.set_xy(170, 3) pdf.cell(0, 5, "Strana "+str(pdf.page_no())+"/{nb}", border=0) pdf.set_xy(170, 6) pdf.cell(0, 5, str(datetime.datetime.now())[:16], border=0) if pdf.page_no() == 1: pdf.set_xy(170, 9) pdf.cell(0, 5, str("Sklad: {}".format('nazev')), border=0) pdf.set_xy(10, 13) pdf.cell(0, 5, str(name), border=0) pdf.set_xy(10, 3) pdf.cell(0, 5, "Universal Scientific Technologies s.r.o.") row = [] used = [] rowh = 9+8 first_row = 28 pdf.set_xy(10, 28) out = [{ '_id': { 'UST_ID': 'UST_ID', 'Value': 'Value', 'Footprint': 'FootPrint', 'Distributor': 'Distributor', 'Datasheet': 'Datasheet', 'note': "Poznámka" }, 'Ref': ['Ref'], 'count': '', 'cUST_ID': "UST_ID", 'stock': [{'name': 'Název', 'category': ['Kategorie']}]} ]+out j = 0 last = 10 for i, component in enumerate(out): print("Component", i, component) item_places = self.component_get_positions(component['cUST_ID'], stock = bson.ObjectId(self.get_cookie('warehouse', False))) #print("Places:", item_places) try: name = component.get('stock')[0]['name'] category = component.get('stock')[0]['category'] except Exception as e: name = '' category = [] j += 1 if j > 28-14: j = 0 first_row = 10 print("New page...") pdf.add_page() pdf.set_font('pt_sans', '', 8) pdf.set_xy(170, 3) pdf.cell(0, 5, "Strana "+str(pdf.page_no())+"/{nb}", border=0) pdf.set_xy(170, 6) pdf.cell(0, 5, str(datetime.datetime.now())[:16], border=0) pdf.line(10,first_row, 200, first_row ) pdf.set_xy(10, 3) pdf.cell(0, 5, info.get('name', name), border=0) if type(component['count']) == 'String' and ['count'] > 5.0: last += 15 else: last += 10 pdf.set_font('pt_sans', '', 8) pdf.set_xy(10, first_row+j*rowh) pdf.cell(0, 5, str(i)+'.', border=0) pdf.set_xy(15, first_row+j*rowh + 11) pdf.cell(0, 5, str(', '.join(component['Ref'])), border=0) pdf.set_xy(163, first_row+j*rowh) pdf.cell(0, 5, str(component['_id'].get('UST_ID', '--'))) pdf.set_xy(90, first_row+j*rowh + 3.5) pdf.cell(0, 5, component['_id'].get('Footprint', '--')[:30]) pdf.set_xy(90, first_row+j*rowh + 7.5) pdf.cell(0, 5, str(component['_id'].get('note', '--'))) pdf.set_font('pt_sans-bold', '', 7.5) pdf.set_xy(90, first_row+j*rowh) pdf.cell(0, 5, component['_id'].get('Value', '--')[:30]) pdf.set_font('pt_sans-bold', '', 9) pdf.set_xy(15, first_row+j*rowh) pdf.cell(0, 5, name) pdf.set_xy(10, first_row+j*rowh + 3.5) pdf.cell(0, 5, str(component['count'])+'x', border=0) pdf.set_font('pt_sans', '', 8) pdf.set_xy(15, first_row+j*rowh + 7) pdf.cell(0, 5, str(', '.join(category)), border=0) for k, place in enumerate(item_places): pdf.set_xy(15, first_row+j*rowh + 3.5) pdf.cell(0, 5, place['info'][0]['name']) pdf.line(10,first_row+j*rowh + 16, 200, first_row+j*rowh + 16) print("===================Value==========================================") pdf.alias_nb_pages() pdf.output("static/production.pdf") with open('static/production.pdf', 'rb') as f: self.set_header("Content-Type", 'application/pdf; charset="utf-8"') self.set_header("Content-Disposition", "inline; filename=UST_osazovaci_list.pdf") self.write(f.read()) f.close()