2017-02-24 105 views
0

我正在通过打印文档对象在c#中打印一系列字符串,并且它工作正常。每个字符串默认打印一个新行。但是如果一个字符串包含的字符数多于一行可以打印的字符数,那么其余的字符将被截断,并且不会出现在下一行。 任何人都可以告诉我如何修复一行的字符数量并在新行上打印超出的字符?如何修复用于打印文档打印的线宽c#

感谢

回答

1

为了使您的文本换行的每一行的末尾,你需要调用DrawString重载需要一个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; 
} 
0

这可能不是最好的做法,而是一种选择是分裂数组,然后它基于字符串是否仍然会加入到一个线串在线路长度限制下。请记住,如果不使用等宽文本,则必须考虑字母宽度。

实施例:

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);