Casey
Casey

Reputation: 2045

Writing text with carriage return to image in Python using PIL

I have a python script that is writing text to images using the PIL. Everything this is working fine except for when I encounter strings with carriage returns in them. I need to preserve the carriage returns in the text. Instead of writing the carriage return to the image, I get a little box character where the return should be. Here is the code that is writing the text:

<code>
 draw = ImageDraw.Draw(blankTemplate)
 draw.text((35 + attSpacing, 570),str(attText),fill=0,font=attFont)
</code>

attText is the variable that I am having trouble with. I'm casting it to a string before writing it because in some cases it is a number.

Thanks for you help.

Upvotes: 1

Views: 3189

Answers (2)

DaZeller
DaZeller

Reputation: 41

You could try the the following code which works perfectly good for my needs:

# Place Text on background
    lineCnt = 0
    for line in str(attText):
        draw = ImageDraw.Draw(blankTemplate)
        draw.text((35 + attSpacing,570 + 80 * lineCnt), line, font=attFont)
        lineCnt = lineCnt +1

The expression "y+80*lineCnt" moves the text down y position depending on the line no. (the factor "80" for the shift must be adapted according the font).

Upvotes: 0

S.Lott
S.Lott

Reputation: 391854

Let's think for a moment. What does a "return" signify? It means go to the left some distance, and down some distance and resume displaying characters.

You've got to do something like the following.

y, x = 35, 570
for line in attText.splitlines():
    draw.text( (x,y), line, ... )
    y = y + attSpacing

Upvotes: 7

Related Questions