Search code examples
c#printinggraphicsdocumentprintdocument

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


Solution

  • 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;
    }