Skip to content

Instantly share code, notes, and snippets.

@ecarreras
Last active January 21, 2016 08:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ecarreras/f7ac5fb7fc851c00f507 to your computer and use it in GitHub Desktop.
Save ecarreras/f7ac5fb7fc851c00f507 to your computer and use it in GitHub Desktop.

Convert HTML to Image

from html2image import HTML2Image

with HTML2Image('<html><strong>Fooo</strong></html>', width='300') as html:
    image = html.render()
import os
import subprocess
import tempfile
class HTML2Image(object):
def __init__(self, content, **kwargs):
if 'format' not in kwargs:
kwargs['format'] = 'png'
self.arguments = kwargs
self.content = content
self.html_file = tempfile.mkstemp(suffix='.html')[1]
with open(self.html_file, 'w') as f:
f.write(content)
self.output = tempfile.mkstemp(suffix='.%s' % kwargs['format'])[1]
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
os.unlink(self.html_file)
os.unlink(self.output)
def render(self):
command = ['wkhtmltoimage']
for arg, value in self.arguments.iteritems():
command += ['--{}'.format(arg), value]
command += [
self.html_file,
self.output
]
subprocess.call(command)
with open(self.output, 'r') as f:
return f.read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment