65.9K
CodeProject 正在变化。 阅读更多。
Home

可自定义的打印文本类

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (5投票s)

2006年6月2日

2分钟阅读

viewsIcon

40098

downloadIcon

1281

一个文本文档打印类,为您的打印文本添加可定制的页眉、页脚和行号。文本也可以使用三种不同的样式打印。

PrintTextDocument test application.

引言

至少有一次,在程序员的职业生涯中,会遇到需要打印文本文档的情况。对于 .NET 程序员来说,这项任务相当简单,但有了 PrintTextDocument 类就更简单了。这个类是为了帮助打印文本文档而编写的,为打印文本添加可定制的页眉和页脚以及行号。文本可以换行以适应超出部分,截断或跨越多页打印。后一种模式对于打印文本横幅(例如来自 ASCII 艺术或具有许多列的文本表格的横幅)非常有用。PrintTextDocumen 继承自 System.Drawing.Printing.PrintDocument,并提供一些额外的属性,这些属性在打印期间设置类的行为。

使用代码

该类的使用非常简单。通常,您创建一个 PrintTextDocument 类的实例,设置描述如何打印的属性,例如页眉和页脚,然后调用 Print 方法开始打印过程;就像您使用 PrintDocument 类一样。类的构造函数是:PrintTextDocument(string filepath),其中 filepath 是要打印的文本文件的完整路径。

//
// Simple use of PrintTextDocument class
//
// assume filename a string that contains the full path of
// an ASCII file.
//

PrintTextDocument toPrint = new PrintTextDocument(filename);
toPrint.PrintMode = PrintTextMode.WrapText;
toPrint.PrintLineNumbers = true;

toPrint.Print();

关注点

当我编写代码时,第一个版本非常简单。OnPrintPage 重写包含一个循环,该循环扫描文本文件并调用 MeasureStringDrawText 方法。经过几次尝试后,我注意到文本换行中存在一个错误。好像 MeasureString 没有处理行尾的空格。这是因为我编写 GetLineBreakCharPosition 函数的方式。此函数检查 MeasureString 的结果,并根据测量文本末尾的空格数量进行调整。我不知道这是否是 MeasureString 的错误。我没有找到任何关于这种奇怪行为的有用信息。我甚至尝试使用 StringFormatMeasureString 方法,但没有改善。我想知道是否有另一种方法可以执行 GetLineBreakCharPosition 所做的事情。

private int GetLineBreakCharPosition(Graphics gfx, 
            string text, RectangleF rectangle)
{
    StringFormat fmt = 
      new StringFormat(StringFormatFlags.MeasureTrailingSpaces);

    int charactersOnLine = 0;
    int lines = 0;

    // Sets the value of charactersOnPage to the number of characters 
    // of stringToPrint that will fit within the bounds of the rectangle.
    SizeF sizeText = gfx.MeasureString(text, _printFont,
        rectangle.Size, fmt,
        out charactersOnLine, out lines);

    string rem = text.Substring(0, charactersOnLine);

    // Fix MeasureString issue with trailing spaces
    if(rem.EndsWith(" ") && (charactersOnLine < text.Length))
    {
        string noSpaces = rem.TrimEnd(new Char[] { ' ' });
        int nSpaces = rem.Length - noSpaces.Length;

        SizeF sizeChunk = gfx.MeasureString(noSpaces, 
            _printFont,
            rectangle.Size, fmt,
            out charactersOnLine, out lines);

        // Measure white space width
        string spacer = String.Empty;

        // Loop until all available space are filled
        while(sizeChunk.Width <= rectangle.Width)
        {
            spacer += " ";
            sizeChunk = gfx.MeasureString(noSpaces + spacer, 
                _printFont,
                new PointF(0, 0), fmt);
        }

        charactersOnLine += spacer.Length - 
            ((sizeChunk.Width > rectangle.Width) ? 1 : 0);
    }

    return charactersOnLine;
}

历史

  • 2006/05/28 - v.1.0.0.0 - PrintTextDocument 简单的文本文件打印类,具有自定义页眉、页脚和打印模式。
© . All rights reserved.