# -*- coding: utf-8 -*-
import win32ui, win32con, win32gui, win32print, traceback
# init, bla bla bla
printername = win32print.GetDefaultPrinter()
hprinter = win32print.OpenPrinter(printername)
# load default settings
devmode = win32print.GetPrinter(hprinter, 8)["pDevMode"]
# this is where it gets INTERESTING:
# after the following two lines, use:
# dc for win32ui calls like LineTo, SelectObject, ...
# hdc for DrawTextW, your *MAGIC* function that supports unicode output
hdc = win32gui.CreateDC("WINSPOOL", printername, devmode)
dc = win32ui.CreateDCFromHandle(hdc)
# 1440 twips = 1 inch
dc.SetMapMode(win32con.MM_TWIPS)
# 20 twips = 1 pt
scale_factor = 20
# start the document, description as unicode
description = u'Test1'
dc.StartDoc(description)
# when working with the printer, enclose any potentially failing calls within a try block,
# because if you do not properly end the print job (see bottom), after a couple of such failures,
# you might need to restart windows as it runs out of handles or something and starts
# behaving in an unpredictable way, some documents fail to print, you cannot open windows, etc.
try :
# Use a font
font = win32ui.CreateFont({
"name": "Arial Unicode MS", # a font name
"height": int(scale_factor * 10), # 10 pt
"weight": 400, # 400 = normal
})
# use dc -- SelectObject is a win32ui call
dc.SelectObject(font)
# this is the miracle where the unicode text gets to be printed; notice hdc,
# not dc, for DrawTextW uses a different handle, i have found this in other posts
win32gui.DrawTextW (hdc, u"\u6C49\u5B57\u3001\u306B\u307B\u3093\u3054\u3001\u05E2\u05D1\u05E8\u05D9\u05EA\u3001\u0639\u0631\u0628\u064A\u6211\u90FD\u4F1A\u5237\u51FA\u3002", -1, (0, -2000, 4000, -4000), win32con.DT_CENTER)
except :
traceback.print_exc()
# must not forget to tell Windows we're done. This line must get called if StartDoc
# was called, if you fail to do so, your sys might start behaving unexpectedly
dc.EndDoc()
如何使用此代码打印 bmp 文件?我需要打印二维码 我有 bmp 文件 我收到此错误 - ( win32gui.DrawTextW(hdc, img, -1, (0, -2100, 4000, -4000), win32con.DT_CENTER) TypeError: Objects of type 'PilImage'无法转换为 Unicode。)