def render_image(self, view='', bg=False, width=500, **kwargs): from config import TEMPLATES_ROOT, DATA_ROOT, DATA_URL # files and url tpl_file = path.join(TEMPLATES_ROOT, f'{view}.mako') img_file = path.join(DATA_ROOT, f'{view}.jpg') css_file = path.join(TEMPLATES_ROOT, 'css/bootstrap.min.css') img_url = DATA_URL + f'/{view}.jpg' # render template view = Template(filename=tpl_file, input_encoding='utf-8', output_encoding='utf-8', lookup=self.template_lookup) kwargs.update({'data_url': DATA_URL, 'cover': bg}) html_str = view.render(**kwargs).decode('utf-8') logger.debug(f"image_available: {self.image_available}") if self.image_available: # output config = imgkit.config( wkhtmltoimage=file_config.wkhtmltoimage_path) # imgkit.from_string(html_string, output_file, config=config) imgkit.from_string(html_str, output_path=img_file, css=css_file, options={'crop-w': width}, config=config) # return cq code return f'[CQ:image,cache=0,file={img_url}]' else: soup = BeautifulSoup(html_str, 'html5lib') msg = re.sub(r'\n+', '\n', soup.body.text.strip().replace(' ', '')) return msg
def ranking_table(df): """ Create table of median predicted WS by league providing a ranking of overall strength to compare across leagues. Args: df (DataFrame): Dataframe containing all player/season predictions. Returns: None """ # Aggregate player/season WS prediction to league-level, calculate median # prediction for each league and sort by overall league value. # Style pandas dataframe and save output for documentation. ranking = (df.groupby('LEAGUE').median()['PREDICTION'].sort_values( ascending=False).reset_index().round(3).style.set_table_styles([{ 'selector': 'tr:nth-of-type(odd)', 'props': [('background', '#eee')] }, { 'selector': 'tr:nth-of-type(even)', 'props': [('background', 'white')] }, { 'selector': 'th, td', 'props': [('text-align', 'center')] }]).set_properties(subset=['LEAGUE'], **{ 'text-align': 'left' }).hide_index()) html = ranking.render() imgkit.from_string(html, 'plots/ranking.png', {'width': 1})
async def call(self, ctx, iracing_id): async with ctx.typing(): user_id = str(ctx.author.id) guild_id = str(ctx.guild.id) if not iracing_id: iracing_id = get_user_iracing_id(user_id, guild_id) if not iracing_id: await ctx.send( 'Please send an iRacing ID after the command or link your own with `!saveid <iRacing' ' ID>`') return guild_dict = get_guild_dict(guild_id) career_stats = await self.update_user.update_career_stats( user_id, guild_dict, iracing_id) if career_stats: career_stats_html = get_career_stats_html( career_stats, iracing_id) filename = f'{iracing_id}_career_stats.jpg' display = Display(visible=0, size=(600, 600)) display.start() imgkit.from_string(career_stats_html, filename) await ctx.send(file=discord.File(filename)) cleanup_file(filename) display.stop() else: await ctx.send('No career stats found for user: ' + str(iracing_id))
def getTableImg(champ): # conn = psycopg2.connect(dbname='soccer_stat', user='******', password=dbpass, host='127.0.0.1', # port='5432') # curConf = conn.cursor() # curConf.execute("SELECT * FROM " + champ + ";") # table_list = curConf.fetchall() # conn.close() table_list = data table = PrettyTable() table.field_names = ["#", "Команда", "И", "В", "Н", "П", "МЗ", "МП", "О"] for i in table_list: table.add_row(i) html = table.get_html_string() tf = tempfile.NamedTemporaryFile(dir='tmp', mode='w+b', delete=False, suffix='.png') css = ['css.css'] options = { 'width': 320, 'disable-smart-width': '', 'encoding': "UTF-8", 'format': 'png' } imgkit.from_string(html, tf.name, config=config, options=options, css=css) return print(tf.name)
async def call(self, ctx, category, type): delete_missing_users(ctx.guild) async with ctx.typing(): if type not in ['career', 'yearly']: await ctx.send( 'Please try again with one of these types: `career`, `yearly`' ) return if category not in ['road', 'oval', 'dirtroad', 'dirtoval']: await ctx.send( 'Please try again with one of these categories: `road`, `oval`, `dirtroad`, `dirtoval`' ) return is_yearly = (type != 'career') guild_dict = get_guild_dict(ctx.guild.id) leaderboard_data = get_relevant_leaderboard_data( guild_dict, category) table_html_string = self.get_leaderboard_html_string( leaderboard_data, ctx.guild, category, self.log, is_yearly) filename = f'{ctx.guild.id}_leaderboard.jpg' display = Display(visible=0, size=(600, 600)) display.start() imgkit.from_string(table_html_string, filename) await ctx.send(file=discord.File(filename)) display.stop() cleanup_file(filename)
def simple_example(): #imgkit.from_url('http://google.com', './out.jpg') #imgkit.from_file('./test.html', './out.jpg') imgkit.from_string('Hello!', './out.jpg') #imgkit.from_string(html_code_str, './out.jpg') input_filepath, output_filepath = './file.html', './file.jpg' try: with open(input_filepath) as fd: imgkit.from_file(fd, output_filepath) except UnicodeDecodeError as ex: print('Unicode decode error in {}: {}.'.format(input_filepath, ex)) except FileNotFoundError as ex: print('File not found, {}: {}.'.format(input_filepath, ex)) #-------------------- # Use False instead of output path to save PDF to a variable. #img_bytes = imgkit.from_url('http://google.com', False) #img_bytes = imgkit.from_file('./test.html', False) img_bytes = imgkit.from_string('Hello!', False) #img_bytes = imgkit.from_string(html_code_str, False) img = PIL.Image.open(io.BytesIO(img_bytes)) plt.figure() plt.imshow(img) plt.tight_layout() plt.axis('off') plt.show()
def exportSSImage(soup): tableData = soup.select("#main > article > div > table") html_string = (""" <html> <head> <meta content="png"/> <meta content="Landscape"/> </head> {tableString} </html> """).format(tableString=tableData) output_file = destop_path + "screenshot.png" config = imgkit.config( wkhtmltoimage=r"H:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltoimage.exe" ) try: exist_file = os.path.exists(output_file) if exist_file: os.remove(output_file) imgkit.from_string(html_string, output_file, config=config) print("截图成功") except IOError as e: print("截图失败:", e)
def GenerateTickets(num, imagePath, ticketPath, dbPath, corner, conf): if not os.path.exists(imagePath): print("Image Folder Dont exists : {0}".format(imagePath)) if not os.path.exists(ticketPath): os.makedirs(ticketPath) if not os.path.exists(dbPath): os.makedirs(dbPath) cand = getCandidates(imagePath) ticketMap = {} for i in range(num): t = createGoodTicket(cand, corner) ticketMap[i] = t renderedTicket = renderTicket(t, i + 1, imagePath) imgkit.from_string(renderedTicket, "{0}/{1}.png".format(ticketPath, str(i + 1)), config=conf) dataBase = {} dataBase["ImagePath"] = imagePath dataBase["Tickets"] = ticketMap dataBase["Candidates"] = cand dataBase["BoardSize"] = [ 10, len(cand) // 10 if len(cand) % 10 == 0 else (len(cand) // 10) + 1 ] with open("{0}/data.db".format(dbPath), 'wb') as file: pickle.dump(dataBase, file)
def table(self, data, month): # Set CSS properties for th elements in dataframe th_props = [('font-size', '25px'), ('text-align', 'center'), ('font-weight', 'bold'), ('color', '#0A0202'), ('background-color', '87ceeb')] # Set CSS properties for td elements in dataframe td_props = [('font-size', '15px'), ('text-align', 'left'), ('color', '#000000')] # Set table styles styles = [ dict(selector="th", props=th_props), dict(selector="td", props=td_props) ] cm = sns.light_palette("orange", as_cmap=True) cap = 'This is your performance for the month of ' + month + '.' data = (data.style.set_properties(**{ 'background-color': 'orange', 'border-color': 'white' }).background_gradient(cmap=cm).highlight_max( subset=["Percentage"], color='yellow').set_caption(cap).set_table_styles(styles)) path_wkthmltoimage = r'C:\Program Files\wkhtmltox\bin\wkhtmltoimage.exe' config = imgkit.config(wkhtmltoimage=path_wkthmltoimage) imgkit.from_string(data.render(), self.file_loc + "styled_table.jpg", config=config)
def save_pic(s, directory: str, pic_name: str, flag: str) -> Union[str, None]: if s is None: return None html = s.render() options = {'encoding': "UTF-8"} if flag == 'marathon': # дополнительные настройки для сохранения картинкой - размеры в пикселях options.update({ 'width': str(450 + int(s.ctx[(0, 3)][0][:-2].split()[-1])), 'height': str(24 * s.data.shape[0] + 36) }) if flag == 'calendar': # проверка, если в стайл-объекте есть цвет - то применить if s.ctx[(0, 0)]: options.update({ 'width': str(200 + s.data.shape[1] * int(s.ctx[(0, 0)][1][:-2].split()[-1])) }) if not os.path.isdir(directory): os.makedirs(directory) path = directory + pic_name + ".png" imgkit.from_string(html, path, config=IMGKIT_CONFIG, options=options) logging.info('{}: картинка сохранена'.format(pic_name)) return path
def semantic_base(self, model, image_array): semantic_segmentation = edgeiq.SemanticSegmentation(model) semantic_segmentation.load(engine=edgeiq.Engine.DNN) # Build legend into image, save it to a file and crop the whitespace legend_html = semantic_segmentation.build_legend() config = imgkit.config( wkhtmltoimage="wkhtmltopdf/bin/wkhtmltoimage.exe") options = {"quiet": ""} imgkit.from_string(legend_html, "data/legend.png", config=self.config, options=options) legend_image = Image.open("data/legend.png") width, height = legend_image.size legend_image.crop((0, 0, 0.61 * width, height)).save("data/legend.png") # Apply the semantic segmentation mask onto the given image results = semantic_segmentation.segment_image(image_array) mask = semantic_segmentation.build_image_mask(results.class_map) image = edgeiq.blend_images(image_array, mask, 0.5) return image, results
async def call(self, ctx, all_series): road, oval, dirt_road, dirt_oval = [], [], [], [] for season in all_series: if season.cat_id == 2: road.append(season) if season.cat_id == 1: oval.append(season) if season.cat_id == 4: dirt_road.append(season) if season.cat_id == 3: dirt_oval.append(season) html_strings = [ build_series_html_string(road, 'Road Series'), build_series_html_string(oval, 'Oval Series'), build_series_html_string(dirt_road, 'Dirt Road Series'), build_series_html_string(dirt_oval, 'Dirt Oval Series') ] for string in html_strings: filename = f'{ctx.guild.id}_series.jpg' display = Display(visible=0, size=(600, 600)) display.start() imgkit.from_string(string, filename) await ctx.send(file=discord.File(filename)) cleanup_file(filename) display.stop()
def exportar_a_imagen(self): hoy = datetime.date.today().strftime("%Y-%m-%d") ayer = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d") html = '<meta charset="UTF-8">' + self.styled_table.render() config = imgkit.config(wkhtmltoimage='/usr/bin/wkhtmltopdf') #BackUp imgkit.from_string( html, "/home/rulicering/Datos_Proyecto_Ozono/Imagenes/BackUp/PAI-" + hoy + ".png") imgkit.from_string( html, "/home/rulicering/Datos_Proyecto_Ozono/Imagenes/PAI-" + hoy + ".png") print("[INFO] - PAI-" + hoy + ".png --- Generated successfully") #Borrar la de ayer try: os.remove("/home/rulicering/Datos_Proyecto_Ozono/Imagenes/PAI-" + ayer + ".png") print("[INFO] - PAI-" + ayer + ".png --- Removed successfully") except: print("[ERROR] - PAI-" + ayer + ".png --- Could not been removed")
async def call(self, ctx, category, type): await self.delete_user_guild_relationships(ctx.guild) async with ctx.typing(): if type not in ['career', 'yearly']: await ctx.send('Please try again with one of these types: `career`, `yearly`') return if category not in ['road', 'oval', 'dirtroad', 'dirtoval']: await ctx.send('Please try again with one of these categories: `road`, `oval`, `dirtroad`, `dirtoval`') return is_yearly = (type != 'career') try: guild = await Guild.get(discord_id=str(ctx.guild.id)) except: await ctx.send('Looks like no one in this discord has data yet. ' 'Try `!saveid` and `!update` to make sure at least one person is saved.') return drivers = await guild.drivers.all() table_html_string = await self.get_leaderboard_html_string(drivers, ctx.guild, Category.from_name(category), is_yearly) filename = f'{ctx.guild.id}_leaderboard.jpg' imgkit.from_string(table_html_string, filename) await ctx.send(file=discord.File(filename)) cleanup_file(filename)
def screenshot(twit_url, twit_id): options = { 'encoding': "UTF-8", 'javascript-delay': '1000', 'crop-h': 600, 'xvfb': '' } imgfile = twit_id + '.png' try: f = urllib.request.urlopen(twit_url) page = BeautifulSoup(f, 'html.parser') tweet = page.find("div", class_="permalink-tweet") if tweet: head = page.head css_hack = BeautifulSoup( "<style>.icon { background: transparent }</style>", "html.parser") head.append(css_hack) imgkit.from_string(str(head) + str(tweet), imgfile, options=options) else: imgkit.from_url(twit_url, imgfile, options=options) except Exception as e: logging.debug(traceback.format_exception(*sys.exc_info())) return str(e) return imgfile
def loadDeck(fileUrl): deckfile = ZipFile(fileUrl) #path = os.getcwd().replace('\\','/') + "/temp_dir/" path = tempfile.TemporaryDirectory().name.replace("\\", "/") + "/" deckfile.extractall(path) #deckyaml = yaml.load(open(path+'deck.yaml','r'), Loader=yaml.FullLoader) os.mkdir('deckimgs') for c in os.listdir(path+'/cards/'): card = yaml.load(open(path+"cards/"+c, 'r'), Loader=yaml.FullLoader) #Replace asset urls with path assetspath = 'file:///' + path + "assets/" #assetspath = "assets/" for asset in card['assets']: card['assets'][asset] = assetspath + card['assets'][asset] #sub the data and assets into the card templatepath = path+'templates/'+card['cardType']+'.svg' frontSVG = open(templatepath, 'r').read() cardSVG = pystache.render(frontSVG, card) outputPath = "deckimgs/"+c.replace(".yaml", "")+'.png' options = {'width': 600, 'height':450, 'disable-smart-width': ''} imgkit.from_string(cardSVG, outputPath, options=options)
def wordart_to_image(text, file_path, style): ''' Generate WordArt image directly from the HTML template ''' h_styles = [ 6, 7, 8, 9, 10, 12, 13, 15, 16, 18, 19, 20, 21, 22, 24, 26, 27, 28 ] v_styles = [5, 11, 17, 23, 29] if style is None: style = choice(h_styles) width = max([1000, len(text) * 200]) options = { 'format': 'png', 'encoding': "UTF-8", 'crop-h': '1300', 'crop-w': width, 'quality': '60', 'quiet': '', } absolute_path = os.getcwd() with open('assets/template.html', 'r', encoding='utf-8') as template: t = template.read() t = t.replace('$$ABS_PATH$$', str(absolute_path)) t = t.replace('$$STYLE$$', str(style)) t = t.replace('$$WIDTH$$', str(width)) t = t.replace('$$TEXT$$', str(text)) from_string(t, file_path, options=options)
async def call(self, ctx, all_series): favorites = get_guild_favorites(ctx.guild.id) if not favorites: await ctx.send( 'Follow the directions by calling `!setfavseries` to set favorite' 'series before ') return series = series_from_ids(favorites, all_series) if not series: await ctx.send( 'Series not found, wait a minute and try again or contact an admin.' ) race_week = series[ 0].race_week - 1 # This is 1 indexed for some reason, but the tracks aren't this_week_string = build_race_week_string(race_week, series, 'This Week', self.log) next_week_string = build_race_week_string(race_week + 1, series, 'Next Week', self.log) this_week_filename = f'{ctx.guild.id}_this_week.jpg' next_week_filename = f'{ctx.guild.id}_next_week.jpg' display = Display(visible=0, size=(600, 600)) display.start() imgkit.from_string(this_week_string, this_week_filename) imgkit.from_string(next_week_string, next_week_filename) await ctx.send(file=discord.File(this_week_filename)) await ctx.send(file=discord.File(next_week_filename)) cleanup_file(this_week_filename) cleanup_file(next_week_filename) display.stop()
def save_all_rotator(self): # import ipdb; ipdb.set_trace() date1 = datetime.now() date2 = timedelta(days=90) dates = date1 + date2 # print(self.data['rotator']) __array = [] for i in loads(self.data['rotator']): # print(i['html']) if i.get('html'): print("FE") tmp = "tmp_media/" + str( self.request.user.id) + self.generator() + '.jpg' html = "koomper/media/" + tmp imgkit.from_string(i['html'], html) i.update({"html_file": tmp}) self.export_attr(Rotator, i) self.values['banner_id'] = self.data.get('banner_id') self.values['date_time_start'] = date1 self.values['date_time_end'] = dates __array.append(Rotator(**self.values)) Rotator.objects.bulk_create(__array) self.result = Rotator.objects.filter( status=True, banner_id=self.data.get('banner_id')).values()
def generate_standards_images(self): standards = [] excel_data_df = pandas.read_excel(self.INPUT_FILE, header=(Config.HEADER_START_ROW - 1), sheet_name=Config.DATA_SHEET_NAME) for i in excel_data_df.index: standard_name = self.__clean_string__( excel_data_df[Config.STANDARD_NAME_COL][i]) if standard_name: fair_info = self.__get_fairness_info__(excel_data_df, i) standard = Standard.Standard(None, standard_name, None) standard.FAIRNESS_INFO = fair_info standards.append(standard) print(len(standards)) tables = self.UTILS.get_standards_tables(standards) options = { 'crop-w': '540', } for std_name, std_table in tables.items(): std_name = self.__clean_file_name(std_name) file_name = "data/images/" + std_name + ".jpg" print("File name == " + file_name) imgkit.from_string(std_table, file_name, options=options)
def html_to_image(StrPrintHtml="", printer_name="", widthPage=300, heightPage=100): """ Функция вывода текста на принтер :param StrPrintHtml: - Текст HTML :param printer_name: - имя принтера :return: """ requestMessage = {} try: filename = tempfile.mktemp(".png") imgkit.from_string( """<!DOCTYPE html><html><head><meta charset="utf-8"><title>Печать</title></head><body>%s</body></html>""" % StrPrintHtml, filename, options={ 'width': widthPage, 'height': heightPage }) except Exception: requestMessage["Error"] = "create temp file %s %s" % ( filename, traceback.format_exc()) return requestMessage requestMessage = print_local_file(filename, printer_name) try: os.remove(filename) except Exception: print("Remove file from temp :(%s) %s" % (filename, traceback.format_exc())) return requestMessage
def stats(tg_id, name): trusters = crrd.find_one({"tg_id": tg_id}) if trusters is None: truster = [{ "fecha": "N/A", "username": "******", "id": "N/A", "mensaje": "N/A" }] qty = 0 else: truster = trusters["truster"] qty = len(truster) THIS_DIR = os.path.dirname(os.path.abspath(__file__)) j2_env = Environment(loader=FileSystemLoader(THIS_DIR), trim_blocks=True) b = j2_env.get_template('template.html') try: a = b.render(users=truster, trusted=name, numeros=qty) imgkit.from_string( a, str(tg_id) + ".jpeg", # options={"xvfb": ""} ) except Exception as ee: logging.warning(ee) pass
async def call(self, ctx, iracing_id): async with ctx.typing(): user_id = str(ctx.author.id) guild_id = str(ctx.guild.id) if not iracing_id: try: driver = await Driver.get(discord_id=user_id) iracing_id = driver.iracing_id except: pass if not iracing_id: await ctx.send( 'Please send an iRacing ID with the command or link your own with `!saveid <iRacing ' 'ID>`') return races_stats_list = await self.pyracing.last_races_stats(iracing_id) if races_stats_list: table_html_string = await recent_races_table_db_string( races_stats_list, iracing_id) filename = f'{guild_id}_{iracing_id}_recent_races.jpg' imgkit.from_string(table_html_string, filename) await ctx.send(file=discord.File(filename)) cleanup_file(filename) else: await ctx.send('Recent races not found for user: ' + iracing_id)
async def send_message(self, event=None): if not self.cl.is_connected(): return self.chat.configure(state=tkinter.DISABLED) self.send_message_btn.configure(state=tkinter.DISABLED) excel_processor = ExcelProcessor(self.chat.get()) print('file is choosed', self.chat.get(), sep=' = ') result = excel_processor.process_file() print('Excel content is parsed. Sending started...') for key in list(result.keys()): text = TEMPLATE_START_LOG.format(datetime.now().strftime("%m/%d/%Y, %H:%M:%S"), result[key].phone, result[key].contract, result[key].count, len(result[key].contents)) self.log.insert(tkinter.END, text) self.log.yview(tkinter.END) user = await self.cl.get_entity(result[key].phone) if is_phone_number(result[key].phone) else await self.get_private_group(result[key].phone) # await self.cl.send_message(user, str(result[key].contract)) print("user",user, sep='=') for content in result[key].contents: html = prepare_body(excel_processor.header+content) imgkit.from_string(html, IMAGE, options=img_opts) await self.cl.send_file(user, IMAGE) text = TEMPLATE_END_LOG.format( datetime.now().strftime("%m/%d/%Y, %H:%M:%S")) self.log.insert(tkinter.END, text) self.chat.configure(state=tkinter.NORMAL) self.send_message_btn.configure(state=tkinter.NORMAL)
def html_to_pdf(self): data = parameter_required(("html_str", )) import imgkit, platform, os, uuid, shutil, oss2 from jinrui.config.secret import ALIOSS_BUCKET_NAME, ALIOSS_ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET pdf_uuid = str(uuid.uuid1()) if platform.system() == "Windows": pdf_path = "D:\\jinrui_pdf\\" + pdf_uuid + "\\" else: pdf_path = "/tmp/jinrui_pdf/" + pdf_uuid + "/" if not os.path.exists(pdf_path): os.makedirs(pdf_path) imgkit.from_string(data.get("html_str"), pdf_path + "pdf-" + pdf_uuid + ".pdf") auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET) bucket = oss2.Bucket(auth, ALIOSS_ENDPOINT, ALIOSS_BUCKET_NAME) pdf_url = "https://" + ALIOSS_BUCKET_NAME + "." + ALIOSS_ENDPOINT + "/" + "pdf-" + pdf_uuid + ".pdf" result = bucket.put_object_from_file( "pdf-" + pdf_uuid + ".pdf", pdf_path + "pdf-" + pdf_uuid + ".pdf") return { "code": 200, "success": True, "message": "创建成功", "data": { "pdf_url": pdf_url } }
def process_file(filename): ''' Extracts tables from HTML file. Outputs each table as an image file. Segments each image file into table cells. Performs OCR on each cell. Returns JSON for all tables in each HTML input file. ''' try: with open(location['input'] + '/' + filename, 'r') as f: file_contents = f.read() soup = BeautifulSoup(file_contents, 'html.parser') tables = soup.select('table') filename_parts = filename.split('.') # for i in range(len(tables)): for i in range(5): if i != 4: continue table = tables[i] image_filename = location['output'] + '/' + \ filename_parts[0] + '_' + str(i) + '.png' imgkit.from_string(table.prettify(), image_filename) segment(image_filename) except: print("Unexpected error:", sys.exc_info()[0]) raise
def start_playing_league(bot, update, league): try: logger = _get_logger() # Validaciones de argumentos if not _authenticate(update): bot.send_message(chat_id=update.message.chat_id, text="Grupo invalido") return league["__$STATE"] = "PLAYING" league["partidos"] = [] html = """<!DOCTYPE html><html><head><style>table {font-family: arial, sans-serif;border-collapse: collapse;width: 400x;}td, th {border: 1px solid #dddddd;text-align: left;padding: 8px;}.header {background-color: #dddddd;}.nameColumn {width: 75px;}.pointColumn {width: 60px;}</style></head><body><h2>Partidos</h2><table><tr><td class='nameColumn header'>Jugador A</td><td class='nameColumn header'>Jugador B</td><td class='pointColumn header'>Golas A</td><td class='pointColumn header'>Goles B</td><td class='pointColumn header'>PJ</td></tr>""" for game in list(itertools.combinations(league["players"], 2)): tmp = {"games": 0} tmp[game[0]] = 0 tmp[game[1]] = 0 html += """<tr><td class='nameColumn'>{JUGA}</td><td class='nameColumn'>{JUGB}</td><td class='pointColumn'>{GA}</td><td class='pointColumn'>{GB}</td><td class='pointColumn'>{PJ}</td></tr>""".format( JUGA=game[0], JUGB=game[1], GA="0", GB="0", PJ="0") league["partidos"].append(tmp) html += """</table></body></html>""" file_name = str(uuid.uuid4()) + ".png" path_wkthmltopdf = WKHTMLTOIMAGE_PATH config = imgkit.config(wkhtmltoimage=path_wkthmltopdf) options = {'format': 'png', 'encoding': "UTF-8", 'crop-w': '435'} imgkit.from_string(html, file_name, options=options, config=config) file = open(file_name, 'rb') bot.send_photo(chat_id=update.message.chat_id, photo=file, timeout=60) file.close() os.remove(file_name) update_doc(LEAGUES_COLLECTION, {"__$STATE": "JOINING"}, league) except Exception as ex: bot.send_message(chat_id=update.message.chat_id, text=str(ex)) logger.exception(ex) return
def generate(self, data, outfile='output.png', height=300, width=400, bgcolor='#f5f5dc'): wkhtml_options = { 'height': height, 'width': width } # Set defaults context = { 'card_height': height, 'card_width': width, 'bgcolor': bgcolor, 'armor': 0, 'parry': '', 'notes': [], 'additional_notes': [] } # Find inherited weapon stats if applicable context.update(self.default_armor.get(data.get('inherit', ''), {})) context.update(data) # Look up notes by reference for ndx, note in enumerate(context.get('notes', [])): if type(note) is str: if note in self.armor_notes: context['notes'][ndx] = self.armor_notes[note] else: print('Unknown note name: %s' % note) imgkit.from_string(self.template.render(context), outfile, options=wkhtml_options)
def print_tabelle(liga, spieltag, ligatabelle): #for pos in ligatabelle: # print(pos['platz'], pos['mannschaft'], pos['spiele'], pos['tordiff'],pos['punkte']) trstrhead = '<tr><td>{}</td><td>{}</td><td align="right">{}</td><td align="right">{}</td>' \ '<td align="right">{}</td></tr>' trstr = '<tr><td align="right" style="padding-right:50px">{}</td>' \ '<td>{}</td><td align="right" style="padding-right:70px">{}</td>' \ '<td align="right" style="padding-right:70px">{}</td>' \ '<td align="right" style="padding-right:70px">{}</td></tr>' hdrstr = trstrhead.format('Platz', 'Verein', 'Spiele', 'Tordiff', 'Punkte') options = {'width': 1200, 'transparent': '', 'quiet': ''} n = len(ligatabelle) n1 = n // 2 + n % 2 html = html_head html += '<body class="tab"><table><caption>Tabelle {}. Spieltag {} (I)</caption></tr>'.format(spieltag, liga) html += hdrstr for pos in ligatabelle[0:n1]: html += trstr.format(pos['platz'],pos['mannschaft'], pos['spiele'],pos['tordiff'],pos['punkte']) html += '</table></body></html>' imgkit.from_string(html, path + liga + 'Tabelle_I.png', options=options) html = html_head html += '<body class="tab"><table><caption>Tabelle {}. Spieltag {} (II)</caption></tr>'.format(spieltag, liga) html += hdrstr for pos in ligatabelle[n1:]: html += trstr.format(pos['platz'], pos['mannschaft'], pos['spiele'],pos['tordiff'],pos['punkte']) html += '</table></body></html>' imgkit.from_string(html, path + liga + 'Tabelle_II.png', options=options)
def makeJPG(HTML_list, TwitterID, path='reply'): now_path = os.path.dirname(os.path.abspath(__file__)) filedir = f"{now_path}/images/{path}/{TwitterID}" os.makedirs(filedir, exist_ok=True) for i, html in enumerate(HTML_list): filepath = f"{filedir}/result_{i+1}.jpg" imgkit.from_string(html, filepath, options={'width': 1300})