from html2image import HTML2Image
with HTML2Image('<html><strong>Fooo</strong></html>', width='300') as html:
image = html.render()
Last active
January 21, 2016 08:48
-
-
Save ecarreras/f7ac5fb7fc851c00f507 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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