PrintWordWarp & WordWarp[打印自动换行,字符串自动换行]

这两个方法是我今天在给一个客户做解决方案的时候想出来的,由于时间仓促,也没有进行细化,也就大概实现了一部分功能,有兴趣的朋友,可以完善下这两个方法,当然也希望在你完善之后也在此共享一下你的代码,使其能够帮助更多的人。

刚开始使用的代码编辑器不好看,结果想换一个,看到已经有这么多人浏览了,就没删除这篇文章重新上传,只是在live wirter上编辑好直接复制过来,但是没想到这个代码编辑器复制过来的没有了折叠功能,大家见谅。

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    string strSource = "Welcome to the MSDN Library, an essential source of information "
        + "for developers using Microsoft® tools, products, technologies and services. "
        + "The MSDN Library includes how-to and reference documentation, sample code, "
        + "technical articles, and more. To find the content you need, browse the table of contents, "
        + "use search, or use a Quick Link to jump to some of the most popular areas of the library. "
        + "To get the latest MSDN headlines sent to you via e-mail. Sign up for the MSDN Flash Newsletter.";

    float x = 33f;
    float y = 280f;
    Font printFont = new Font("Times New Roman", 10); ;
    PrintWordWarp(e.Graphics, e.PageSettings, printFont, strSource, x, y);
}

public void PrintWordWarp(Graphics graphics, PageSettings pageSettings, Font printFont, string strSource, float x, float y)
{
    float _x = x;
    float _y = y;
    IList<string> list = new List<string>();
    string[] strArr = strSource.Split(' ');

    float pWidth = pageSettings.PrintableArea.Width;
    float cWidth;
    for (int i = 0; i < strArr.Count(); i++)
    {
        cWidth = graphics.MeasureString(strArr[i], printFont).Width;
        if (_x + cWidth > pWidth)
        {
            _y += graphics.MeasureString(strArr[i], printFont).Height;
            _x = x;
        }
        graphics.DrawString(strArr[i], printFont, Brushes.Black, _x, _y, new StringFormat());
        _x += cWidth;
    }
}

//下面是字符串自动换行,与上面的方法无关联,可单独使用
string resultStr;
public void WordWarp(string strSource, int startIndex, int numPerLine)
{
    int lastIndex = startIndex + numPerLine;
    if (lastIndex > strSource.Length)
    {
        resultStr = strSource;
        return;
    }
    if (strSource.ElementAt(lastIndex) != ' ')
    {
        startIndex = strSource.LastIndexOf(' ', lastIndex, numPerLine);
    }
    else
    {
        startIndex += numPerLine;
    }
    strSource = strSource.Remove(startIndex, 1);
    strSource = strSource.Insert(startIndex, "\n");
    WordWarp(strSource, startIndex + 1, numPerLine);
}

PS:我的同事开发了一个MSDN论坛的小工具,有兴趣的朋友可以试试,此工具已开始在国内推行:

MSDN论坛好帮手

posted @ 2011-03-09 23:06  Mike Dos Zhang  阅读(1793)  评论(3编辑  收藏  举报