Reputation: 1171
Convert an HTML string to image data and display it as an image in a template using Python. I have a string like below
text = """< html>< body>< p style='color:red'>Stack Overflow< /p>< /body>< /html>
"""
I need to convert it as image data and to display that image into a template page.
Upvotes: 1
Views: 1721
Reputation: 2791
You can use something like this:
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
text = """< html>< body>< p style='color:red'>Stackoverflow< /p>< /body>< /html> """
bgcolor = 'white'
text_color = 'black'
rightpadding = 10
leftpadding = 5
font = ImageFont.load_default() # or ImageFont.truetype(font=font_name, size=font_size)
line_width = font.getsize(text)[0]
img_height = font.getsize(text)[1]
img = Image.new("RGBA", (line_width + rightpadding , img_height), bgcolor)
draw = ImageDraw.Draw(img)
draw.text((leftpadding, 0), text, text_color)
img.show()
Upvotes: 1