1

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.

1 Answer 1

1

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

Comments

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.