Question

Ok so I want to print the text of a text box but I have one problem when I have a line that is too big it goes out of the page how can I know how many chars a line can contains within the bounds, keep in mind that the size and font change.

I already have this code that I got from the web somewhere so you know what i want.

private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            float linesPerPage = 0;
            float yPosition = 0;
            int count = 0;
            float leftMargin = e.MarginBounds.Left;
            float topMargin = e.MarginBounds.Top;
            string line = null;

            Font printFont = txtMain.Font;
            SolidBrush myBrush = new SolidBrush(Color.Black);
            // Work out the number of lines per page, using the MarginBounds.
            linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);
            // Iterate over the string using the StringReader, printing each line.
            while (count < linesPerPage && ((line = myReader.ReadLine()) != null))
            {
                // calculate the next line position based on the height of the font according to the printing device
                yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
                // draw the next line in the rich edit control
                e.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
                count++;
            }
            // If there are more lines, print another page.
            if (line != null)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;
            myBrush.Dispose();
        }

Thanks in advance.

Was it helpful?

Solution

You should read about FontMetrics

Once you know how to get the font metric, you can use that in combination with your drawing area to decide how many characters you can place.

EDIT: You can get the size of the painting area as follows:

//This gives you a rectangle object with a length and width.
Rectangle bounds = e.MarginBounds;

Once you have the width of the page, you get the font metric from your font, then divide the page width by the font's width. Take the floor of that, and that is how many characters you can put horizontally on the page. Make sure that you are using the same units (width is default pixels). You can do the same thing for vertical if needed.

OTHER TIPS

I use this code that may help you.

private string txt(string yourtext)
{
    string[] text = new string[200];

    text = yourtext.ToLower().Split(' ');
    string b = "";
    int i = 1;

    foreach (string s in text)
    {
        if (b.Length < i * 100)
            b += s + " ";
        else
        {
            b += "\n";
            i++;
        }
    }

    return b;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top