def refresh_thumbs(user):
    """Refresh the thumbnail images for the writer homepage.

    Arguments:
        user {str} -- The user to refresh the thumbs for. Passing 'all' will update all users thumbnails.
    """
    if user != "all":
        WRITER_PATH = "userdata/{}/writer/documents".format(user)
        THUMB_PATH = "userdata/{}/writer/thumbnails".format(user)
        # Windows needs executable path to be specified.
        if os.name == "nt":
            config = imgkit.config(
                wkhtmltoimage=
                b"C:/Program Files/wkhtmltopdf/bin/wkhtmltoimage.exe")
        else:
            config = imgkit.config()
        # xvfb is needed by Linux
        if os.name == "posix":
            options.update(xvfb="")

        files = os.listdir(WRITER_PATH)
        for i in files:
            # Don't create a thumbnail for the backup folder.
            if i != "oopsie":
                imgkit.from_file(
                    WRITER_PATH + "/" + i,
                    THUMB_PATH + "/" + i + "_thumb.png",
                    options=options,
                    config=config,
                )
    else:
        # List every user and recursively refresh thumbnails.
        users = os.listdir("userdata/")
        for user in users:
            refresh_thumbs(user)
Ejemplo n.º 2
0
 def test_custom_config(self):
     conf = imgkit.config()
     self.assertEqual('imgkit-', conf.meta_tag_prefix)
     conf = imgkit.config(meta_tag_prefix='prefix-')
     self.assertEqual('prefix-', conf.meta_tag_prefix)
     with self.assertRaises(IOError):
         imgkit.config(wkhtmltoimage='wrongpath')
Ejemplo n.º 3
0
def get(url):
    sucesso = False
    while not sucesso:
        try:
            if os.name == 'nt':
                config = imgkit.config(wkhtmltoimage=windows_path)
            else:
                config = imgkit.config(wkhtmltoimage=heroku_path)

            options = {
                'format': 'jpg',
                'crop-h': '1230',
                'crop-w': '1440',
                'crop-x': '0',
                'crop-y': '0',
                'encoding': "UTF-8",
                'quiet': '',
            }

            imgkit.from_url(url,
                            'screenshot.jpg',
                            config=config,
                            options=options)

            sucesso = True

        except OSError as e:
            print(e)
            sleep(2)
            continue
Ejemplo n.º 4
0
 def test_custom_config(self):
     conf = imgkit.config()
     self.assertEqual("imgkit-", conf.meta_tag_prefix)
     conf = imgkit.config(meta_tag_prefix="prefix-")
     self.assertEqual("prefix-", conf.meta_tag_prefix)
     with self.assertRaises(IOError):
         config = imgkit.config(wkhtmltoimage="wrongpath")
         config.get_wkhtmltoimage()
     with self.assertRaises(IOError):
         config = imgkit.config(xvfb="wrongpath")
         config.get_xvfb()
Ejemplo n.º 5
0
def generaImg(partita):
    html = apriTemplateHTML()
    html = html.replace("#CLAN", partita['clan'])
    i = 1
    for giocatori in partita["giocatori"]:
        if (i > 5):
            break
        print(i)
        nick = "ND"
        membri = sis.getMembri()
        for p in membri:
            print(p["id"])
            if (giocatori == p["id"]):
                nick = p["alias"][0]
        html = html.replace("gioc" + str(i), nick)
        i += 1
    html = esito(partita, html)
    if (platform.system() == "Windows"):
        path_wkthmltoimage = r'C:/Program Files/wkhtmltopdf/bin/wkhtmltoimage.exe'
        config = imgkit.config(wkhtmltoimage=path_wkthmltoimage)
        options = {'width': 352, 'disable-smart-width': ''}
        return [
            imgkit.from_string(html, "out.png", options=options,
                               config=config), "yes"
        ]
    else:
        options = {'width': 352, 'disable-smart-width': '', 'xvfb': ''}
        return [imgkit.from_string(html, "out.png", options=options), "yes"]
Ejemplo n.º 6
0
def get_chart_from_sheet(date):
    month = date.strftime("%B")
    result = SheetService().read_sheet(SPREADSHEET_ID, f'{month}!F2:G')
    values = result.get('values', [])
    if len(values) == 0:
        return None

    title = values[0]
    values = list(map(convert_to_decimal, values[1:]))
    values.insert(0, title)
    html = HTML(html=str(chart_template % {"json": values}))
    loop = asyncio.new_event_loop()
    text = threading.Thread(target=render, args=(html, loop))
    text.start()
    text.join()
    # HEROKU PATH
    # config = imgkit.config(wkhtmltoimage='.apt/usr/local/bin/wkhtmltoimage')
    config = imgkit.config(
        wkhtmltoimage='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltoimage.exe')
    content = html.find('#content')[0].html
    img = imgkit.from_string(content,
                             False,
                             config=config,
                             options={
                                 'format': 'png',
                                 'crop-w': '650',
                                 'crop-x': '150',
                                 'crop-y': '50',
                                 'crop-h': '400',
                                 'encoding': 'utf-8',
                             })
    str_file = io.BytesIO(img)
    return str_file
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
    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")
Ejemplo n.º 9
0
def create_base_table(title, x_list, data_list):
    headers = [" "] + x_list
    rows = []
    for key in data_list.keys():
        #print(key)
        row = []
        row.append(key)
        for x in data_list[key]:
            row.append(x)
        #print(row)
        rows.append(row)
    table = Table()
    table.add(headers, rows)
    table.set_global_opts(
        title_opts=opts.ComponentTitleOpts(title=title)
    )
    src_path = "./test/"
    html_file_name = src_path + title + ".html"
    img_file_name = src_path + title + ".png"
    table.render(html_file_name)
    path_wkimg = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe'  # 工具路径
    cfg = imgkit.config(wkhtmltoimage=path_wkimg)
    imgkit.from_file(html_file_name, img_file_name, config=cfg)
    #make_snapshot(snapshot, table.render(html_file_name), img_file_name)
    print(img_file_name+"生成完毕...")
Ejemplo n.º 10
0
def fq(avatar, username, timestamp, content, max_width=400, scale=1.2, color='#dcddde'):

    dir_path = change_cwd()
    inject_js(avatar, username, color, timestamp, content, max_width)

    # 設定wkhtmltoimage程式位置
    config = imgkit.config(wkhtmltoimage=path.join(dir_path, 'wkhtmltoimage.exe'))
    options = {
        'format': 'png',
        'encoding': 'UTF-8',
        'quality': '100',
        'transparent': '',
        'zoom': str(scale),
        'quiet': '',
        'crop-y': '0',
    }
    output = 'out.png'
    imgkit.from_file(filename='sample.html', output_path=output, config=config, options=options)
    # 調用47行會在終端出現一行字,目前找不到解法
    # 已經試過調用stdout跟print('\r')等
    im = Image.open(output)
    size = (0, 3, im.size[0], im.size[1]-3)
    im = im.crop(size)
    im2 = im.crop(im.getbbox())  # 去除透明部分
    im2.save(output)
    result = open(output, 'rb')  # 返回byte形式檔案,方便傳送至Discord
    return result
Ejemplo n.º 11
0
    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
Ejemplo n.º 12
0
def pharming(url):
    my_resolver = dns.resolver.Resolver()
    my_resolver.nameservers = ['208.67.222.222','208.67.220.220','8.8.8.8','8.8.8.9','156.154.70.1','156.154.71.1']
    subDomain, domain, suffix = extract(url)
    try:
        answer = my_resolver.query(domain+'.'+ suffix)
        addr2 = socket.gethostbyname(domain+'.'+ suffix)#It gives the ip from your DNS
        add1 = []
        for rdata in answer:
           add1.append(str(rdata))    
        if addr2 not in add1:
            config = imgkit.config(wkhtmltoimage="/usr/local/bin/wkhtmltoimage")
            imgkit.from_url('http://'+add1[0], 'out1.jpg',config=config)
            imgkit.from_url('http://'+addr2, 'out2.jpg',config=config)
            original = cv2.imread("out1.jpg")
            duplicate = cv2.imread("out2.jpg")
            # 1) Check if 2 images are equals
            if original.shape == duplicate.shape:
                #print("The images have same size and channels")
                difference = cv2.subtract(original, duplicate)
                b, g, r = cv2.split(difference)
                if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
                    #print("The images are completely Equal")
                    return 1#Legi
                    #print(1)
            else:
                #print(-1)
                return -1#Attack 
        else:
            #print(1)
            return 1#legi
        #np.array_equal(original,duplicate)
    except Exception:
        #print(0)
        return 0#suspicious
def DataFrame_to_image(data,
                       css=css,
                       outputfile="financial_data.png",
                       format="png"):

    fn = "filename.html"

    try:
        os.remove(fn)
    except:
        None

    # text_file = codecs.open(fn, "ba", encoding='utf-8', errors='ignore')
    text_file = open(fn, "a")
    #text_file =decode("utf-8", "ignore")
    # write the CSS
    text_file.write(css)
    # write the HTML-ized Pandas DataFrame
    text_file.write(data.to_html(index=False))
    text_file.close()

    imgkitoptions = {"format": format}
    path_for_wkhtml = r'wkhtmltopdf\wkhtmltoimage.exe'
    config = imgkit.config(wkhtmltoimage=path_for_wkhtml)
    imgkit.from_file(fn, outputfile, options=imgkitoptions, config=config)
    os.remove(fn)
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
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
0
    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
Ejemplo n.º 17
0
def _img_util(html_path, pdf_path):
    config = imgkit.config(
        wkhtmltoimage=current_app.config.get('PDF_IMAGE_PATH'))
    options = {
        'format': 'png',
        'encoding': "UTF-8",
        'custom-header': [('Accept-Encoding', 'gzip')],
        'no-outline': None
    }
    imgkit.from_file(html_path, pdf_path + '.jpg', config=config)
Ejemplo n.º 18
0
def sendMessage(body, id):
    config = imgkit.config(wkhtmltoimage=('bin/wkhtmltoimage'))
    options = {'format': 'jpg'}
    img = imgkit.from_url(
        "http://www.manadafoodhouse.com.br/carrinho/detail/" + id,
        'img-' + id + '.jpg',
        options=options,
        config=config)
    with open('img-' + id + '.jpg', "rb") as f:
        telegram_send.send(conf="telegramConf", messages=[body], images=[f])
Ejemplo n.º 19
0
def Score_plot(score, bit, savepath, path_wkimg):
    # 定义函数
    cLiquid = (Liquid().add(
        "水滴图", [score / 100],
        is_outline_show=False,
        is_animation=False,
        label_opts=opts.LabelOpts(is_show=False,
                                  font_size=50,
                                  position="inside")).set_global_opts())

    cLiquid.render(
        'temp.html'
    )  # 定格,括号内为文件名,注意单引号说明文件名省html后缀,双引号文件名,生成后缀,也可以加入路径,默认为代码.py所在的路径或文件夹。

    #########################将html文件转化成图片
    # https://blog.csdn.net/bobyuan888/article/details/108769274
    cfg = imgkit.config(wkhtmltoimage=path_wkimg)
    # 1、将html文件转为图片
    imgkit.from_file('temp.html', savepath, config=cfg)
    ###################截取部分图片
    # 打开一张图
    img = Image.open(savepath)
    # 图片尺寸
    img_size = img.size
    h = img_size[1]  # 图片高度
    w = img_size[0]  # 图片宽度
    x = 0.25 * w
    y = 0.25 * h
    w = 0.4 * w
    h = 0.6 * h
    # 开始截取
    region = img.crop((x, y, x + w, y + h))
    # 保存图片
    region.save(savepath)
    os.remove('temp.html')
    #######################在图片上添加文字
    bk_img = cv2.imread(savepath)
    # 设置需要显示的字体
    fontpath = "font/simsun.ttc"
    font = ImageFont.truetype(fontpath, 50)
    font2 = ImageFont.truetype(fontpath, 20)
    img_pil = Image.fromarray(bk_img)
    draw = ImageDraw.Draw(img_pil)
    # 绘制文字信息
    draw.text((110, 90), str(score) + '分', font=font, fill=(255, 255, 255))
    draw.text((50, 270),
              '* 设备稳定性击败了' + str(bit) + '%同类设备',
              font=font2,
              fill=(0, 0, 255))
    bk_img = np.array(img_pil)
    ####显示图片
    # cv2.imshow("add_text",bk_img)
    # cv2.waitKey()
    ###保存图片
    cv2.imwrite(savepath, bk_img)
Ejemplo n.º 20
0
    def __init__(self, config):
        self.config = config
        self.pm = tweepy.streaming.urllib3.PoolManager()
        self.get_access_token()
        self.jorf = None
        self.sommaire = None
        self.esr = None

        self.css = os.path.dirname(
            os.path.abspath(__file__)) + "/css/legifrance.css"  #"jorf.css"
        self.wkoptions = {"log-level": "info", "javascript-delay": 2000}
        self.wkconfig = imgkit.config(wkhtmltoimage=config.wk_path)
Ejemplo n.º 21
0
def export_png(html, filename):
    options = {
        'format': 'png',
        'height': '1872',
        'width': '1404',
        'quality': '80',
    }
    if platform.system() == 'Windows':
        config = imgkit.config(wkhtmltoimage=wkhtmltoimage_path_win)
        imgkit.from_string(html, filename, options=options, config=config)
    else:
        imgkit.from_string(html, filename, options=options)
Ejemplo n.º 22
0
def convert_png(content: str, i, wkhtmltoimage_path: str, output_path: str):

    config = imgkit.config(wkhtmltoimage=wkhtmltoimage_path)
    options = {
        'no-images': '',
        'encoding': 'UTF-8',
        'disable-javascript': '',
        'load-media-error-handling': 'ignore',
        'load-error-handling': 'ignore'
    }
    imgkit.from_string(content,
                       "{}/{}.png".format(output_path, i),
                       options=options,
                       config=config)
    return {'index': i, 'img_path': "{}/{}.png".format(output_path, i)}
Ejemplo n.º 23
0
def htmlToImage(file_path_by, wkhti):
    config = imgkit.config(wkhtmltoimage=wkhti)
    '''直接截图处理模式,图像不是很清晰'''
    options = {
        'format': 'jpg',
        'crop-h': '730',
        'crop-w': '489',
        'crop-x': '6',
        'crop-y': '6',
        'encoding': "gb18030",
    }
    imgkit.from_file(file_path_by + r'\grade.html',
                     file_path_by + r"\grade.jpg",
                     options,
                     config=config)
Ejemplo n.º 24
0
def setTablePreview(df):
    df = df.head(10)
    html = df.to_html()
    html_file = open("htmlDf.html", "w+")
    html_file.write(html)
    html_file.close()
    img_file_name = "tablePreview.jpg"
    imgkitoptions = {"format": "jpg"}
    configuration =  imgkit.config(
                    wkhtmltoimage = 
                    wkhtmltoimage_path)
    imgkit.from_file("htmlDf.html",img_file_name,
                    options = imgkitoptions,
                    config = configuration)
    moveFile(img_file_name)
Ejemplo n.º 25
0
def maketicket():
    p = re.compile("[.].+")
    dt = datetime.datetime.now()
    dt = p.sub("", str(dt))
    Thistime = datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
    video_title = request.form['video-title']
    platform = request.form['platform']
    people = request.form['people']
    place = request.form['place']
    theme = request.form['theme']
    cssfile = open("static/styles/%s.css" % theme, "r")
    cssstr = "<style>\n" + cssfile.read() + "\n</style>\n"

    html_output = render_template('ticket.html',
                                  Thistime=Thistime,
                                  video_title=video_title,
                                  platform=platform,
                                  people=people,
                                  place=place)

    filename = r"\%s_%d" % (str(Thistime)[:11],
                            len(os.listdir("imgmaking/htmlforimg")) + 1)
    with open("imgmaking/htmlforimg/" + filename + ".html",
              "w",
              encoding="UTF-8") as f:
        f.write(cssstr + html_output)

    path_wkthmltoimage = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe"
    config = imgkit.config(wkhtmltoimage=path_wkthmltoimage)
    options = {
        'format': 'png',
        'quality': '100',
        'encoding': "UTF-8",
        'crop-h': '500',
        'crop-w': '500',
    }
    imgkit.from_file(
        r"C:\develop\gamseongticket\imgmaking\htmlforimg" + filename + ".html",
        r"C:\develop\gamseongticket\imgmaking\imgs" + filename + ".png",
        config=config,
        options=options,
    )
    return send_file(
        r"C:\develop\gamseongticket\imgmaking\imgs" + filename + ".png",
        mimetype='image/png',
        attachment_filename=filename[1:] + ".png",  # 다운받아지는 파일 이름. 
        as_attachment=True)
Ejemplo n.º 26
0
def render_images(df, img_dir=None, img_dir_prefix='rendered-images', wkhtml_p=None, wb=False):

    config = None
    options = {'quiet': ''}
    if platform == "linux" or platform == "linux2":
        options['xvfb'] = ''
    elif platform == "darwin":
        pass
    elif platform == "win32":
        if wkhtml_p is None:
            raise Exception('Please specify the path to the wkhtmltoimage exe.')
        config = imgkit.config(wkhtmltoimage=wkhtml_p)

    if img_dir is None:
        img_dir = img_dir_prefix + '-' + datetime.now().strftime('%Y-%m-%d-%H-%M-%S')

    pathlib.Path(img_dir).mkdir(parents=True, exist_ok=True)

    render_error = []
    render_error_msg = []

    for _, row in df.iterrows():
        path = os.path.join(img_dir, f"id_{row['id']}.jpg")
        if wb == True:
            # include wayback machine links:
            html = row['renderCodeWayback']
        else:
            html = row['renderCodeLink']
            #html = row['fullHtmlCode']

        try:
            imgkit.from_string(html, path, options=options, config=config)
            render_error.append(0)
            render_error_msg.append('')
            print(f"Successfully rendered image with id {row['id']}.")
        except Exception as e:
            print(f"An error occured when rendering image with id {row['id']}: {e}")
            # traceback.print_exc() # import traceback
            render_error.append(1)
            render_error_msg.append(str(e))

    #df["render_error_archive"]= render_error

    error_df = pd.DataFrame({'id': df.id, 'render_error': render_error, 'render_error_msg': render_error_msg})
    s3link = df['s3Link'].iloc[0]
    persist_errors(error_df, img_dir, s3link)
    return error_df
Ejemplo n.º 27
0
def df_to_img(input_name, df, output_name):

    # css used to stylized our HTML-ized dataframes
    css = """
        <style type=\"text/css\">
        table {
        color: #333;
        font-family: Helvetica, Arial, sans-serif;
        width: 640px;
        border-collapse:
        collapse; 
        border-spacing: 0;
        }
        td, th {
        border: 1px solid transparent; /* No more visible border */
        height: 30px;
        }
        th {
        background: #DFDFDF; /* Darken header a bit */
        text-align: center;
        font-weight: bold;
        }
        td {
        background: #FAFAFA;
        text-align: center;
        }
        table tr:nth-child(odd) td{
        background-color: white;
        }
        </style>
        """

    # Writing the dataframe with css to an html file
    text_file = open(input_name, "w")
    # write the CSS
    text_file.write(css)
    # write the HTML-ized Pandas DataFrame
    text_file.write(df.to_html())
    text_file.close()

    # Setting our path variable so imgkit can find wkhtmltoimg executable
    path_wkthmltoimage = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe'
    config = imgkit.config(wkhtmltoimage=path_wkthmltoimage)

    options = {'log-level': 'none'}

    imgkit.from_file(input_name, output_name, config=config, options=options)
Ejemplo n.º 28
0
    def __init__(self, bot):
        self.bot = bot
        # Initialize Imgkit & Jinja2
        self.imgkit_config = imgkit.config()
        self.imgkit_options = {
            'quiet': '',
            'format': 'png',
            'quality': '69',
            'encoding': "UTF-8",
            'width': '815'
        }

        file_loader = FileSystemLoader('templates')
        self.jinja_env = Environment(loader=file_loader)

        self.card_template = self.jinja_env.get_template("card.html")
        self.neon_card_template = self.jinja_env.get_template("card_neon.html")
Ejemplo n.º 29
0
def downloadimg(strhtml, cssfile, output):
    """html转图片
    @param cssfile: 样式文件路径
    @param output: 输出的文件完整路径"""
    options = {
        'format': 'png',
        'encoding': "UTF-8",
        'quiet': ''  # 不打印日志
    }
    myplatform = getplatform()
    config = imgkit.config(
        wkhtmltoimage=WkhtmltoimgPath) if 'Windows' in myplatform else None
    imgkit.from_string(strhtml,
                       output,
                       options=options,
                       css=cssfile,
                       config=config)
Ejemplo n.º 30
0
def generate_board_image():
    with open('data.json') as json_file:
        data = json.load(json_file)

        environment = Environment()
        environment.filters['debug'] = debug
        board = environment.from_string(boardTemplate).render(cardType=data[4])
        with open('board.html', 'w', encoding='utf8') as outfile:
            outfile.write(board)

    svg_options = {'format': 'svg'}
    svg_config = imgkit.config(
        wkhtmltoimage=r'.\lib\wkhtmltopdf\bin\wkhtmltoimage.exe')
    imgkit.from_file('board.html',
                     'board.svg',
                     options=svg_options,
                     config=svg_config)