Determining the number of lines in a text string?

sooprise picture sooprise · Feb 16, 2011 · Viewed 8k times · Source

As part of a printing class, I want to be able to print long strings over multiple pages, but I don't know how to calculate the height of the entire string, which I will determine by first counting the number of lines in my string. I know I can count the number of line breaks, but I am also using word-wrap, so line breaks will be added whenever a line goes on past the width of the page. So I suppose I could count the number of line breaks, and figure out the width of each line, and figure out if there is a need for a word-wrap line break for each line, but this seems like an overly complicated problem for something I imagine can be done more simply.

e.Graphics.DrawString(multiPageString, new Font("Courier New", 12), Brushes.Black, new RectangleF(0, 0, 810, pageHeight));

If you have any advice, please let me know thanks!

Answer

Alexander picture Alexander · May 11, 2012
int iMaxWidth = 240; // Maximum width, in pixels
string sText = @"blah-blah-blah";
Font objFont = new Font("Times New Roman", 13, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point);
StringFormat sfFmt = new StringFormat(StringFormatFlags.LineLimit);
Graphics g = Graphics.FromImage(new Bitmap(1, 1));
int iHeight = (int)g.MeasureString(sText, objFont, iMaxWidth, sfFmt).Height;
int iOneLineHeight = (int)g.MeasureString("Z", objFont, iMaxWidth, sfFmt).Height;
int iNumLines = (int)(iHeight/iOneLineHeight);