Convert HTML String to an Image in Python

HTML to IMAGE using Python

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

Convert HTML string to an image in Python

webkit2png. The original version is OSX-only, but luckily there is a cross-platform fork:
https://github.com/AdamN/python-webkit2png

Converting HTML Files to PNG Images

You can use weasyprint

from weasyprint import HTML, CSS

div = 'your div as string'
css_string = 'your css as string'

html = HTML(string=div)
css = CSS(string=css_string)
html.write_png('output.png', stylesheets=[css])


Related Topics



Leave a reply



Submit