如何固定打印文档打印的线宽c#

how to fix line width for print document printing 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);