33

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.

2
  • Does this answer your question? Render HTML to an image Commented Mar 9, 2020 at 10:42
  • 1
    @ThomasSchillaci Actually i want to do it using python, like i created the .html file from the string. i want to apply other operations like cropping to the image file after converting the html file to image. Commented Mar 9, 2020 at 10:46

7 Answers 7

37

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
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for your answer. By using the method you described above i got the image version of the html file. But the images in the html file is missing in the .jpg file.
@Manu__ add <meta content="text/html; charset=utf-8" http-equiv="Content-type"> <meta content="jpg" name="imgkit-format"> in your html string and then try
In your second method we have to specify the data, right? in my case the data will be a user input so it can vary. This method is not useful in my case. First method is okay. But the converted file, ie, ".jpg" file is missing the images in the html file, please give a solution for that. thanks
copied <meta content="text/html; charset=utf-8" http-equiv="Content-type"> <meta content="jpg" name="imgkit-format"> and added it in html string. But the result is still same.
yes, the image path is correct and i can open the image file. Okay let me check the solution you provided.
|
32

If you don't want your project to depend on wkhtmltopdf, like other Python modules use, I recommend html2image.

You can get it using the pip install html2image command. A web browser shall also be installed on your machine (Chrome/Chromium or Edge for now).

Once installed, you can take a screenshot of an HTML string like so:

from html2image import Html2Image
hti = Html2Image()

html = '<h1> A title </h1> Some text.'
css = 'body {background: red;}'

# screenshot an HTML string (css is optional)
hti.screenshot(html_str=html, css_str=css, save_as='page.png')

You can also directly take screenshots of existing HTML files or URLs:

# screenshot an HTML file
hti.screenshot(
    html_file='page.html', css_file='style.css', save_as='page2.png'
)

# screenshot an URL
hti.screenshot(url='https://www.python.org', save_as='python_org.png')

For documentation and more examples, you can check out the the GitHub page of the project.

2 Comments

Html2Image is indeed a wrapper around Chrome/Chromium, and has the advantage of generating images that are (most of the time) perfect replicas of what you can see in your own browser, which is not always the case using wkhtmltopdf. As the author of this package, thanks for recommending it, I hope to add support for additional browsers/tools in the future.
Wish I would have seen this earlier. I'm using this to map a web calendar to an ePaper. All the other tools just displayed a blank page. Thank you both!
7

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())

1 Comment

This is in fact what html2image does
4
from html2image import Html2Image
hti = Html2Image()
with open('./test.html') as f:
    hti.screenshot(f.read(), save_as='out.png')

1 Comment

While this code may answer the question, consider sharing a link to the library and some explanation of features or why you suggest it over others. See, the quite identical answer from ajskateboarder was duplicated.
2

check out HtmlWebShot

# pip install htmlwebshot

from htmlwebshot import WebShot
shot = WebShot()
shot.quality = 100

image = shot.create_pic(html="file.html")

Comments

0

You can do it with familiar tool - selenium. You will just need to put path to the file instead of link:

from selenium import webdriver
driver = webdriver.Chrome(executable_path = ‘path\to\chromedriver.exe’’)
driver.get("file:/path/to/html")
driver.save_screenshot(‘out.png’)

Voila, you made an image with few lines of code and without unknown packages

Comments

0

I’ve developed a Python module called hex_htmltoimg, designed to convert HTML content into image files easily. This module is especially useful for automating the process of rendering HTML files or URLs into image formats like PNG, JPEG, and others.

It’s lightweight, fast, and can handle dynamic HTML rendering. Whether you need to capture web page previews, generate content screenshots, or visualize HTML-based data, this tool simplifies the task.

You can check it out here:

GitHub Repository PyPI Page Feel free to share your feedback or any suggestions for improvements!

1 Comment

Hi! It would be great if you could add a sample usage of the packet to address the OP question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.