Search code examples
pythonwinapiunicodepywin32

Unable to draw Unicode characters with Python's PyCDC.DrawText()


I'm trying to draw Unicode characters using PyCDC.DrawText(), but it seems to draw two ASCII characters instead. For example, when trying to draw 'Я' (\u042F), I get: https://i.sstatic.net/hh9RJ.png

My string is defined as a Unicode string:

text = u'Я'

And the file starts with:

# -*- coding:utf-8 -*-

I also tried printing the string (to the console) and it comes out fine, so the problem is probably lying within the implementation of DrawText().

Thanks!


Solution

  • To output Unicode text on Windows you need to encode it in UTF-16 and call the wide character version of the DrawText() or TextOut() Win32 functions. In case you aren't familiar, the Windows API is natively UTF-16 and has parallel 8 bit ANSI versions for legacy support.

    I know nothing of the Win32 wrapper you are using but rather suspect that PyCDC.DrawText() is calling the ANSI version of whichever one of these Win32 functions is doing the work. Your solution will likely involve finding a way to invoke DrawTextW() or TextOutW(). You could do it with ctypes, and these functions must surely be available through PyWin32 also.

    However, I would probably opt for something higher level, like PyQt.