Muhammad Gulfam
Muhammad Gulfam

Reputation: 255

how to fix line width for print document printing c#

I am printing a series of strings through print document object in c# and it is working fine. each string prints in a new line by default. but if a string contains more characters than a line can print then the remaining characters cut off and do not appear on the next line. Can anyone tell me how can i fix the number of character for a line and print the exceeding characters on the new line ?

Thanks

Upvotes: 0

Views: 1363

Answers (2)

Jeremy
Jeremy

Reputation: 161

This may not be best practice, but one option is to split the array, and then add it into a line string based on whether or not the string would still be under the line length limit. Keep in mind you would have to consider letter width if not using a monospace text.

Example:

String sentence = "Hello my name is Bob, and I'm testing the line length in this program.";
String[] words = sentence.Split();

//Assigning first word here to avoid begining with a space.
String line = words[0];

            //Starting at 1, as 0 has already been assigned
            for (int i = 1; i < words.Length; i++ )
            {
                //Test for line length here
                if ((line + words[i]).Length < 10)
                {
                    line = line + " " + words[i];
                }
                else
                {
                    Console.WriteLine(line);
                    line = words[i];
                }
            }

            Console.WriteLine(line);

Upvotes: 0

Chris Dunaway
Chris Dunaway

Reputation: 11216

In order to make your text wrap at the end of each line, you need to call the DrawString overload that takes a Rectangle object. The text will be wrapped inside that rectangle:

private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
    //This is a very long string that should wrap when printing
    var s = new string('a', 2048);

    //define a rectangle for the text
    var r = new Rectangle(50, 50, 500, 500);

    //draw the text into the rectangle.  The text will
    //wrap when it reaches the edge of the rectangle
    e.Graphics.DrawString(s, Me.Font, Brushes.Black, r);

    e.HasMorePages = false;
}

Upvotes: 1

Related Questions