2014-11-06 47 views
1

我想估计打印字符串的长度。如何估算待打印字符串的长度?

Font newFont = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point); 
label1.Font = newFont; 
labe1.Text = "300028"; 
Graphics g = Graphics.FromHwnd(label1.Handle); 
SizeF txtSize = g.MeasureString(label1.Text, label1.Font); 

txtSize是{Width = 60.3177,Height = 19.875}点。

实际宽度应为60.3177 * 0.353 =21.29毫米

,其中(1点= 1/72英寸= 0.353 MM)

在纸(印有字)的宽度为大约13.5毫米

为什么我们在用MeasureString(21.29毫米)和实际值(13.5毫米)计算出的值之间有如此大的差异?

我知道limitations of the MeasureString method,但我不认为这不能证明这么大的差异。

我缺少什么?

回答

3

因为您初始化您的Graphics对象错误。您正在使用显示句柄,而不是打印句柄。

根据this postGraphics对象应使用PrinterSettings.CreateMeasurementGraphics方法上PrintDocument获得:

Graphics g = pd.PrinterSettings.CreateMeasurementGraphics(); 
+0

非常感谢。使用打印手柄我得到宽度= 62,83094(我期望像38) – Klaus78 2014-11-06 13:39:02

+0

你设置字体大小为毫米? '新字体(“Arial”,12,FontStyle.Regular,GraphicsUnit.Millimeter);' – 2014-11-06 13:41:05

+0

我使用GraphicsUnit.Point其中1点= 1/72英寸= 0.353毫米,以我的理解 – Klaus78 2014-11-06 13:43:52