pythonthermal-printerescpos

Drawing Arabic Characters to bitmap


i have been trying to print arabic characters using SPRT thermal printer with the python-escpos package, but i cant seem to find any solution at all, so i decided to draw the arabic characters to a bitmap and then print it. But that also doesn't work..

this is the code used for converting the text to bitmap: `

from PIL import Image, ImageDraw, ImageFont

img = Image.new('L', (100, 10))
d = ImageDraw.Draw(img)
a = 'محمد'

d.text((1,1), f"{a}",255)
img.save('pil_text.png')

`

Result in Error: UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)

Also, i have tried to encode the string using utf-8 and 1256, but both didnt give me the correct characters: b'\xd9\x85\xd8\xad\xd9\x85\xd8\xaf'


Solution

  • In this case you need to use a particular font. Download any font which supports the arabic language. For example: I have used "arial-unicode-ms.tff".

    Keep the downloaded font in the same folder you're writing your code.

    from PIL import Image, ImageFont, ImageDraw
    
    image = Image.new("RGB",[320,320])
    draw = ImageDraw.Draw(image)
    a = 'محمد'
    font = ImageFont.truetype("arial-unicode-ms.ttf", 14)
    draw.text((50, 50), a, font=font)
    image.save("image.png")