2014-11-06 66 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

相關問題