python - 如何使用 Windows GDI 设置打印的字体类型和大小?

标签 python printing gdi pywin32

我的python程序只需要在某些位置打印文本。我正在使用 Windows GDI 来存档目标。

以下代码可以完成这项工作,但我需要设置字体类型和大小。

import win32ui
dc = win32ui.CreateDC()
dc.CreatePrinterDC()
dc.StartDoc('Test document')

dc.StartPage()
dc.TextOut(100,2000, 'HELLO WORLD!')
dc.EndPage()
dc.EndDoc()

最佳答案

使用CreateFont然后在设备上下文中选择字体,例如:

dc.StartPage()

fontdata = { 'name':'Arial', 'height':100, 'italic':True, 'weight':win32con.FW_NORMAL}
font = win32ui.CreateFont(fontdata);
dc.SelectObject(font)
dc.TextOut(100,2000, 'HELLO WORLD!')
...

要更好地计算字体大小,请使用以下基于 CreateFont WinAPI 引用的内容:

def getfontsize(dc, PointSize):
    inch_y = dc.GetDeviceCaps(win32con.LOGPIXELSY)
    return int(-(PointSize * inch_y) / 72)

示例:现在您可以使用它在页面中心以 11 号字体进行绘制

fontsize = getfontsize(dc, 11)
fontdata = { 'name':'Consolas', 'height':fontsize}
font = win32ui.CreateFont(fontdata);
dc.SelectObject(font)

此外,LOGPIXELSY/LOGPIXELSYPHYSICALWIDTH/PHYSICALHEIGHT可用于更准确地计算坐标。

关于python - 如何使用 Windows GDI 设置打印的字体类型和大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48549555/

相关文章:

python - 为什么 platform.release() 在 Windows 10 中返回 "8"?

python - Pandas groupby 和选择器顺序

python - 装饰类的特定方法

php - PHP中echo、echo()、print和print()的区别

graphics - 电脑怎么画线??

python - Django:Postgres 连接未关闭

html - 在 : avoid works only in IE? 之后分页

c - 如何在 C 中自动打印结构值(如 gdb ptype)?

windows - 使用GDI显示图像的红色 channel

c++ - 使用坐标空间和变换滚动和缩放增强型 Windows 图元文件