自动将文字换行到打印页面?

soo*_*ise 8 c# printing word-wrap

我有一些打印字符串的代码,但如果字符串是:"Blah blah blah"...并且没有换行符,则文本占用一行.我希望能够塑造这个字符串,使它的文字包裹在纸张的尺寸上.

private void PrintIt(){
    PrintDocument document = new PrintDocument();
    document.PrintPage += (sender, e) => Document_PrintText(e, inputString);
    document.Print();
}

static private void Document_PrintText(PrintPageEventArgs e, string inputString) {
    e.Graphics.DrawString(inputString, new Font("Courier New", 12), Brushes.Black, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)

我想我可以弄清楚一个角色的长度,并手动包装文本,但如果有一个内置的方法来做到这一点,我宁愿这样做.谢谢!

She*_*Pro 12

是的,DrawString能够自动对文本进行自动换行.您可以使用MeasureString方法检查指定的字符串是否可以在Page或Not上完全绘制,以及需要多少空间.

还有一个专门用于此目的的TextRenderer类.

这是一个例子:

         Graphics gf = e.Graphics;
         SizeF sf = gf.MeasureString("shdadj asdhkj shad adas dash asdl asasdassa", 
                         new Font(new FontFamily("Arial"), 10F), 60);
         gf.DrawString("shdadj asdhkj shad adas dash asdl asasdassa", 
                         new Font(new FontFamily("Arial"), 10F), Brushes.Black,
                         new RectangleF(new PointF(4.0F,4.0F),sf), 
                         StringFormat.GenericTypographic);
Run Code Online (Sandbox Code Playgroud)

这里我指定最多60个像素作为宽度然后测量字符串将给我绘制此字符串所需的大小.现在,如果您已经有一个尺寸,那么您可以与返回的尺寸进行比较,以查看它是正确绘制还是截断


pik*_*chu 11

sooprise,你问过你如何处理一页太长的文本.我也想要这个.我不得不搜索很长时间,但最终我发现了这一点.

http://msdn.microsoft.com/en-us/library/cwbe712d.aspx

private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
    int charactersOnPage = 0;
    int linesPerPage = 0;

    // Sets the value of charactersOnPage to the number of characters 
    // of stringToPrint that will fit within the bounds of the page.
    e.Graphics.MeasureString(stringToPrint, this.Font,
        e.MarginBounds.Size, StringFormat.GenericTypographic,
        out charactersOnPage, out linesPerPage);

    // Draws the string within the bounds of the page
    e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
        e.MarginBounds, StringFormat.GenericTypographic);

    // Remove the portion of the string that has been printed.
    stringToPrint = stringToPrint.Substring(charactersOnPage);

    // Check to see if more pages are to be printed.
    e.HasMorePages = (stringToPrint.Length > 0);
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你