3

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'

Mido
  • 35
  • 3

1 Answers1

1

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")
Shakir Sadiq
  • 64
  • 1
  • 5
  • Well, it didn't work at first, but figured out that i have to download the font ttf file to the project's folder in order to access it. So, i did that and it worked, but the characters were in the wrong direction 'from left to right instead of right to left' and are not connected to each other. But `arabic_reshaper` solved that. So ye your answer was the key to the correct solution. – Mido Nov 25 '22 at 12:51
  • I will mark it as a solution, but edit it please and point out to the other steps i have mentioned so it won't be half a solution. – Mido Nov 25 '22 at 12:52
  • Yeah for drawing the arabic characters to bitmap. You need to download the font. (You can download any arabic language supporting font for it). Glad to hear that my solution helped you to solve this. :) – Shakir Sadiq Nov 30 '22 at 08:30