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.