Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML to IMAGE using Python

Here is a variable html_str, it is a string that contains html tags and contents in body. I am created a .html file from this string using the below code in python.

html_file = open("filename.html", "w")
html_file.write(html_str)
html_file.close()

now i got html file named file "filename.html". Now i want to convert that "filename.html" to a image, named filename.jpg with the exact contents of the html file. please help me.

like image 340
Manu __ Avatar asked Mar 09 '20 10:03

Manu __


2 Answers

You can do this by using imgkit

import imgkit

imgkit.from_file('test.html', 'out.jpg')

Or you can also use htmlcsstoimage Api

# pip3 install requests
import requests

HCTI_API_ENDPOINT = "https://hcti.io/v1/image"
HCTI_API_USER_ID = 'your-user-id'
HCTI_API_KEY = 'your-api-key'

data = { 'html': "<div class='box'>Hello, world!</div>",
         'css': ".box { color: white; background-color: #0f79b9; padding: 10px; font-family: Roboto }",
         'google_fonts': "Roboto" }

image = requests.post(url = HCTI_API_ENDPOINT, data = data, auth=(HCTI_API_USER_ID, HCTI_API_KEY))

print("Your image URL is: %s"%image.json()['url'])
# https://hcti.io/v1/image/7ed741b8-f012-431e-8282-7eedb9910b32
like image 142
Mohit Chandel Avatar answered Sep 28 '22 05:09

Mohit Chandel


Another very useful tool to render HTML sites is the headless Chromium browser.

In javascript you would use the puppeteer api to interact with it but there is a unofficial python port of puppeteer called pyppeteer

From my experience with python tools like imgkit the Chromium solution is far more reliable when it comes to loading in external assets like images or iFrames.

To get an image version of the rendered HTML using pyppeteer you simply load the page and then make a full page screenshot:

import asyncio
from pyppeteer import launch

async def main():
    browser = await launch()
    page = await browser.newPage()
    await page.goto('http://example.com')
    await page.screenshot({'path': 'example.png', 'fullPage': 'true'})
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())
like image 45
Mercury Avatar answered Sep 28 '22 07:09

Mercury