HTML to IMAGE using Python

Manu __ picture Manu __ · Mar 9, 2020 · Viewed 15.8k times · Source

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.

Answer

Mohit Chandel picture Mohit Chandel · Mar 9, 2020

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