I already have this code but it gives me the wrong result.
private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int charPerLine = e.MarginBounds.Width / (int)e.Graphics.MeasureString("m", txtMain.Font).Width;
}
The txtMain is a textbox.
This should do the trick. Be careful when dividing by a variable cast to an integer. You are leaving yourself open to a divide-by-zero here in the event that the
Widthproperty is less than one, which will be truncated to zero. It may be unlikely that you will have such a small font in your application, but it is still good practice.The real issue though is why do you even need to know the number of characters per line. Unless you are trying to do some sort of ASCII art, you can use the different overloads of
Graphics.DrawStringto have GDI+ layout the text for you inside a bounding rectangle without needing to know how many characters fit on a line.This sample from MSDN shows you how to do this:
So if you are trying to print a page of text, you can just set the
drawRectto thee.MarginBoundsand plug a page worth of text in fordrawString.Another thing, if you are trying to print tabular data, you can just partition the page into rectangles – one for each column/row (however you need it), and use
e.Graphics.DrawLineoverloads to print the table borders.If you post more details on what you are actually trying to achieve we can help more.