Ejemplo n.º 1
0
def render_to_jpeg(html: HTML, buffer: io.BytesIO):
    png_buffer = io.BytesIO()
    html.write_png(png_buffer)
    png_buffer.seek(0)
    with Image(file=png_buffer) as image:
        image.background_color = Color('#fff')
        image.alpha_channel = 'remove'
        image.format = 'jpeg'
        image.save(file=buffer)
Ejemplo n.º 2
0
 def get_data():
     if 'wsgi.input' in environ and request_body_size:
         request = environ['wsgi.input'].read(request_body_size)
         content = parse_qs(request.decode('utf-8'))['content'][0]
     else:
         content = DEFAULT_CONTENT
     html = HTML(string=content)
     png = BytesIO()
     html.write_png(png)
     png.seek(0)
     return content, b64encode(png.read()).decode('ascii')
Ejemplo n.º 3
0
 def get_data():
     if 'wsgi.input' in environ and request_body_size:
         request = environ['wsgi.input'].read(request_body_size)
         content = parse_qs(request.decode('utf-8'))['content'][0]
     else:
         content = DEFAULT_CONTENT
     html = HTML(string=content)
     png = BytesIO()
     html.write_png(png)
     png.seek(0)
     return content, b64encode(png.read()).decode('ascii')
Ejemplo n.º 4
0
def render():
    html = request.args['html']
    assert html.strip()

    if html:
        assert 'fuu' not in html
        # Save the input HTML
        with open(INPUT, 'w') as fd:
            fd.write(html.encode('utf-8'))

    html = HTML(INPUT, encoding='utf8')
    html.write_pdf(PDF_OUTPUT)
    html.write_png(PNG_OUTPUT)

    return send_file(PNG_OUTPUT, cache_timeout=0)
Ejemplo n.º 5
0
def render():
    html = request.args['html']
    assert html.strip()

    if html:
        assert 'fuu' not in html
        # Save the input HTML
        with open(INPUT, 'w') as fd:
            fd.write(html.encode('utf-8'))

    html = HTML(INPUT, encoding='utf8')
    html.write_pdf(PDF_OUTPUT)
    html.write_png(PNG_OUTPUT)

    return send_file(PNG_OUTPUT, cache_timeout=0)
Ejemplo n.º 6
0
def createTable(data,
                columnDict,
                cssString,
                filename,
                resolution=300,
                na_rep='-'):

    data_r = data.rename(columns=columnDict)
    cols = [c for c in columnDict.values()]

    css = CSS(string=cssString)

    html = HTML(
        string=data_r.to_html(index=False, columns=cols, na_rep=na_rep))
    html.write_png(filename + '.png', stylesheets=[css], resolution=resolution)
Ejemplo n.º 7
0
def render_bounty(bounty, language):
    bounty_image = None
    try:
        bounty_image = BountyImage.objects.get(bounty=bounty,
                                               language=language)
    except BountyImage.DoesNotExist:
        pass
    if not bounty_image or bounty_image.is_expired():
        if not bounty_image:
            bounty_image = BountyImage(bounty=bounty, language=language)

        bounty_image.language = language
        t = loader.get_template('bounties/export.html')
        html = HTML(string=t.render(
            Context({
                'bounty': bounty,
                'SITE_URL': settings.SITE_URL
            })))
        image_content = ContentFile(html.write_png())
        image_content.name = "bounty_%s_%s.jpg" % (bounty.pk, language)
        bounty_image.image = image_content
        bounty_image.clean()
        bounty_image.save()
        return bounty_image.image.read()
    return bounty_image.image.read(-1)
Ejemplo n.º 8
0
    def write_thumbnail(self, thumbnail_data, resource_name, path):
        """Save generatered thumbnail.

        Args:
            thumbnail_data: Data of generated thumbnail.
            resource_name: Name of the resource (str).
            path: The path to write the thumbnail to (str).
        """
        # Only import weasyprint when required as production environment
        # does not have it installed.
        from weasyprint import HTML, CSS
        context = dict()
        context["resource"] = resource_name
        context["paper_size"] = self.options["paper_size"].value
        context["all_data"] = [[thumbnail_data]]
        pdf_html = render_to_string("resources/base-resource-pdf.html",
                                    context)
        html = HTML(string=pdf_html, base_url=settings.BUILD_ROOT)
        css_file = finders.find("css/print-resource-pdf.css")
        css_string = open(css_file, encoding="UTF-8").read()
        base_css = CSS(string=css_string)
        thumbnail = html.write_png(stylesheets=[base_css], resolution=72)
        thumbnail_file = open(path, "wb")
        thumbnail_file.write(thumbnail)
        thumbnail_file.close()
Ejemplo n.º 9
0
    def process_IN_CREATE(self, event):
        if event.pathname.endswith(".html"):
            print "Creating:", event.pathname

            print "Loading file"
            wprint = HTML(filename=event.pathname)
            print "writing thumbnail"
            wprint.write_png(event.pathname.replace(".html", "_thumbnail.png")+".partial", resolution=10)
            print "writing pdf"
            wprint.write_pdf(event.pathname.replace(".html", ".pdf")+".partial")
            print "writing png"
            wprint.write_png(event.pathname.replace(".html", ".png")+".partial", resolution=300)

            # Remove the ".partial" to indicate that it's done generating both.
            for suffix in ('.pdf', '.png', '_thumbnail.png'):
                dest = event.pathname.replace(".html", suffix)
                src = dest + ".partial"
                os.rename(src, dest)
Ejemplo n.º 10
0
def generate_png():
    name = request.args.get('filename', 'unnamed.pdf')
    app.logger.info('POST  /png?filename=%s' % name)
    html = HTML(string=request.data)
    pdf = html.write_png()
    response = make_response(pdf)
    response.headers['Content-Type'] = 'image/png'
    response.headers['Content-Disposition'] = 'inline;filename=%s' % name
    app.logger.info(' ==> POST  /pdf?filename=%s  ok' % name)
    return response
Ejemplo n.º 11
0
    async def stoic(self, ctx):
        from weasyprint import HTML

        folder = config.path + "/src/templates/DailyStoic"
        human = ctx.get_human()
        now = human.current_time or datetime.datetime.utcnow()

        filename_format = "{day}-{month}.xhtml"
        z = lambda x: str(x).zfill(2)
        filename = filename_format.format(day=z(now.day), month=z(now.month))
        with open(f"{folder}/Text/{filename}", encoding="utf-8") as f:
            html = HTML(string=f.read(), base_url=folder + "/Text")
            output_filename = filename.replace("xhtml", "png")
            output_path = f"{config.path}/tmp/daily-stoic/{output_filename}"
            html.write_png(output_path)
            url = await self.bot.store_file(output_path,
                                            output_filename,
                                            owner=True)
            await ctx.send(url)
Ejemplo n.º 12
0
def tag_utter(utterances, path=PATH):
    """Select from allowed files"""

    # text = '\n\n'.join(utterances)
    # tagged_text = pos_matcher(utterances, nlp)
    # st.write(tagged_text)

    tagged_text = {
        'text': utterances + ' \n\n',
        'ents': M_E,
        'title': 'Utterance Labeler'
    }

    pos_txt = spacy.displacy.render(
        tagged_text,
        style='ent',
        page=True,
        manual=True,  ### use dict
        options={'colors': POS})

    # fix breaktag: </b> to <b>
    pos_txt = pos_txt.replace('</b>', '<b>')

    # Set CSS for weasyprint
    css = [
        CSS(string=
            '@page {size: A3; margin: 1cm; font-family: Titillium Web !important;}',
            font_config=font_config)
    ]

    # Save as pdf
    output_path = Path(f'{PATH}/tagged_utter.pdf')
    html = HTML(string=f'{pos_txt}')
    html.write_pdf(output_path, stylesheets=css)

    # Save/show as png - NOTE CAIRO ERROR: length of doc is limited!
    # add <p style="page-break-before: always" ></p>
    output_path = Path(f'{PATH}/tagged_utter.png')
    html = HTML(string=f'{pos_txt}')
    st.image(html.write_png(stylesheets=css),
             caption='Labeling utterances',
             use_column_width=True)

    # Save as svg
    output_path = Path(f'{PATH}/tagged_utter.svg')
    output_path.open("w", encoding="utf-8").write(pos_txt)

    return text
Ejemplo n.º 13
0
def generatePng():
    name = request.args.get('filename', 'unnamed.png')
    app.logger.info('POST  /png?filename=%s' % name)
    if request.headers['Content-Type'] == 'application/json':
        data = json.loads(request.data.decode('utf-8'))
        html = HTML(string=data['html'])
        css = [CSS(string=sheet) for sheet in data['css']]
        pdf = html.write_pdf(stylesheets=css)
    else:
        html = HTML(string=request.data.decode('utf-8'))
        png = html.write_png()
    response = make_response(png)
    response.headers['Content-Type'] = 'image/png'
    response.headers['Content-Disposition'] = 'inline;filename=%s' % name
    app.logger.info(' ==> POST  /png?filename=%s  ok' % name)
    return response
Ejemplo n.º 14
0
def read_file(file, path=PATH):
    """Select from allowed files"""
    # st.markdown(file)
    with open(f'{path}/{file}', 'rb') as f:
        text = f.read().decode('utf-8')
    tagged_text = pos_matcher(text, nlp)

    pos_txt = spacy.displacy.render(tagged_text,
                                    style='ent',
                                    page=True,
                                    manual=True,
                                    options={'colors': POS})

    # fix breaktag: </b> to <b>
    pos_txt = pos_txt.replace('</b>', '<b>')

    # Set CSS for weasyprint
    css = [
        CSS(string=
            '@page {size: A3; margin: 1cm; font-family: Titillium Web !important;}',
            font_config=font_config)
    ]

    # Save as pdf
    output_path = Path(f'{PATH}/{file.split(".")[0]}_pos_cv.pdf')
    html = HTML(string=f'{pos_txt}')
    html.write_pdf(output_path, stylesheets=css)

    # Save as png
    output_path = Path(f'{PATH}/{file.split(".")[0]}_pos_cv.png')
    html = HTML(string=f'{pos_txt}')
    st.image(html.write_png(stylesheets=css),
             caption='AIxPact Resumé Analyzer',
             use_column_width=True)

    # Save as svg
    output_path = Path(f'{PATH}/{file.split(".")[0]}_pos_cv.svg')
    output_path.open("w", encoding="utf-8").write(pos_txt)

    return text
Ejemplo n.º 15
0
def render():
    if request.json is None:
        return Response('JSON payload expected', 400)

    html = request.json.get('html')
    output_format = request.json.get('outputFormat') or 'pdf'

    if html is None:
        return Response('HTML missing', 400)

    document = HTML(string=html)

    if output_format == 'png':
        mimetype = 'image/png'
        response_content = document.write_png()
    elif output_format == 'pdf':
        mimetype = 'application/pdf'
        response_content = document.write_pdf()
    else:
        return Response('Unsupported output format', 400)

    return Response(response_content, mimetype=mimetype)
Ejemplo n.º 16
0
def generate_resource_thumbnail(name, generator):
    """Return image of thumbnail for of PDF resource.

    Args:
        name: Name of resource to be created (str).
        generator: Instance of specific resource generator class.

    Returns:
        Thumbnail of generated resource.
    """
    from weasyprint import HTML, CSS

    context = dict()
    context["resource"] = name
    context["paper_size"] = generator.requested_options["paper_size"]
    context["all_data"] = [generate_resource_copy(generator, thumbnail=True)]
    pdf_html = render_to_string("resources/base-resource-pdf.html", context)
    html = HTML(string=pdf_html, base_url=settings.BUILD_ROOT)
    css_file = finders.find("css/print-resource-pdf.css")
    css_string = open(css_file, encoding="UTF-8").read()
    base_css = CSS(string=css_string)
    return html.write_png(stylesheets=[base_css], resolution=72)
Ejemplo n.º 17
0
    def convertToImg(self, confession: str):
        """Render the confession text into an HTML page and convert it to a PNG image"""
        text = confession.replace('\n', '<br>')
        htmlStr = self.template.replace('INSERT_TEXT_HERE', text)

        fontConfig = FontConfiguration()
        fontString = "@font-face {{ font-family: \"Symbola\"; src: url(\"file://{}\") format(\"opentype\"); }}"
        fontString = fontString.format(
            CCTwitterBot.absolutePath('./Symbola.otf'))
        fontCss = CSS(string=fontString, font_config=fontConfig)

        css = CSS(string='@page { width: 664px; margin: 0px; padding: 0px }',
                  font_config=fontConfig)
        html = HTML(string=htmlStr).render(stylesheets=[css, fontCss],
                                           font_config=fontConfig)

        for page in html.pages:
            for child in page._page_box.descendants():
                if child.element_tag == 'body':
                    page._page_box.height = child.height
                    page.height = child.height

        imgBytes, _, _ = html.write_png(None, resolution=150)
        return io.BytesIO(imgBytes)
Ejemplo n.º 18
0
def genimage():
    #font_config = FontConfiguration()
    html = HTML(string='<h1>The title</h1>')
    #css = CSS(string="""@font-face {font-family: Gentium;src: url(http://example.com/fonts/Gentium.otf);}h1 { font-family: Gentium }""",font_config=font_config)
    return html.write_png()