如何修复打印文档打印 C# 的线宽



我正在通过 c# 打印文档对象打印一系列字符串,它工作正常。 默认情况下,每个字符串在新行中打印。 但是,如果字符串包含的字符数超过一行可以打印的字符数,则剩余字符将被切断,不会出现在下一行中。 谁能告诉我如何修复一行的字符数并在新行上打印多余的字符?

谢谢

为了使文本在每行末尾换行,您需要调用采用Rectangle对象的DrawString重载。 文本将换行在该矩形内:

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

这可能不是最佳做法,但一种选择是拆分数组,然后根据字符串是否仍低于行长度限制将其添加到行字符串中。请记住,如果不使用等宽文本,则必须考虑字母宽度。

例:

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

最新更新