Printing.PaperSize - incorrect width when I get long string form RichTextBox. [vb]

835 Views Asked by At

One of the part of my project is RichTextBox with string length form 10 to 50 chars, and font's size 175-225 in single line. I use special printer: 100 mm height, and 3000 mm (3m) width ribbon. Very long width is a real problem.

I've got problem with Printing.PaperSize width element (I have to use it). It's (MSDN) "The width of the paper, in hundredths of an inch".

I tried to get this from:

RichTextBox1.PreferredSize.Width
g.MeasureString(RichTextBox1.Text, RichTextBox1.Font).Width
g.MeasureCharacterRanges(Text, Font, Rect, Format)

All of them gives me "pixels" but I have no idea how can I use it with Printing.PaperSize - all of them are too short, and dependent on used font family.

Tricky part of this is that I need very precise length of my PaperSize, because I have to print several items before and after the string.

Is any way to estimate printed width (in cm/inches) when I have only pixel size of element?

If anyone can give me any answer in C#, or C++ it doesn't matter - I will be grateful.

1

There are 1 best solutions below

4
On BEST ANSWER

You can measure the width of the string in a given font:

Sub ShowWidthOfText(s As String)
    Using img As New Bitmap(1, 1)
        img.SetResolution(300, 300)

        Using f As New Font("Times New Roman", 225, GraphicsUnit.Point)
            Using g = Graphics.FromImage(img)
                g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
                Dim w = g.MeasureString(s, f)
                MessageBox.Show(String.Format("{0} pixels = {1:N2} cm at {2} ppi", w.Width, w.Width * 2.54 / g.DpiX, g.DpiX))

            End Using
        End Using
    End Using

End Sub

which gives 90.75 cm (35.73 in) for "lorem ipsum dolor sit amet" in the font you suggest, which seems reasonable to me. If you are intending to set the the width of the paper size from that, you would of course need a minimum of 3573 hundredths of an inch.

If you want to fit the text to a particular width, it would probably be best to use a successive approximation method rather than a direct calculation because the kerning of the text may depend on the size of the font.

The .SetResolution is in there in case you use that code to construct your output, it makes no difference to the measurement.

(The resolution names in .NET are wrong: they should be, e.g. PpiX rather than DpiX etc.)

Ref: Measure a String without using a Graphics object?