How to estimate the length of a to-be-printed string?

1.7k Views Asked by At

I am trying to estimate the length of a printed string.

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 is {Width=60.3177, Height=19.875} points.

The actual width should be 60.3177 * 0.353 = 21.29 mm

where (1 point = 1/72 inch = 0.353 mm)

On paper (printed with Word) the width is about 13.5 mm

Why do we get such a big difference between the value computed with MeasureString (21.29 mm) and the real one (13.5 mm)?

I am aware of the limitations of the MeasureString method but I do not think this cannot justify such a big difference.

What I am missing?

2

There are 2 best solutions below

0
On

Printing units are by default in hundredths of an inch, not 72ths of an inch.

As the other answer mentions, you need to use PrinterSettings.CreateMeasurementGraphics to get a graphics object that will be configured the right way to measure text for printing.

4
On

Because you initialize your Graphics object wrong. You are using a display handle, not a print handle.

According to this post your Graphics object should be obtained using the PrinterSettings.CreateMeasurementGraphics method on a PrintDocument:

Graphics g = pd.PrinterSettings.CreateMeasurementGraphics();