C# 打印分页(HasMorePages用法)

网上关于打印分页的文章已经很多了,但大部分都没讲清楚HasMorePages这个属性的作用到底是什么。
它的作用很容易产生误解,但也很好理解:当PrintPage函数执行完后,如果HasMorePages==true,则重新执行一遍PrintPage这个函数。只要明白了这一点,打印分页就很简单了。
在打印时,可以把打印位置保存下来,以便于第二次执行PrintPage时知道从哪开始打印。
例如,下面这段程序用来打印一个DataTable中有所有数据,每页打印一条:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Print
{
    public partial class NoticePrinter : Form
    {
        PrintDialog _printDialog;
        PrintDocument _printDocument;
        DataTable _table;
        int _curRow;
 
        //在执行这个函数之前,先要把_curRow初始化为0;
        //当HasMorePages==true时,这个函数会重复执行,直到HasMorePages==fasle为止;
        void _printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            DataRow row;
            string name;
            string sex;
 
            row = _table.Rows[_curRow];
            name = row["xm"].ToString().Trim();
            sex = row["xb"].ToString().Trim();
 
            Font font = new Font("宋休", 12);
 
            e.Graphics.DrawString(name, font, Brushes.Black, new PointF(10.0, 10.0));
            e.Graphics.DrawString(sex, font, Brushes.Black, new PointF(10.0, 30.0));
 
            _curRow++;
            if (_curPage == _table.Rows.Count)
            {
                e.HasMorePages = false;
            }
            else
            {
                e.HasMorePages = true;
            }
        }
    }
}
发表评论?

8 条评论。

  1. bad
    你自己懂这篇文章吗?那程序你自己测试过没有?

  2. 你确定你测试过???我怎么测试就是不过呢??

  3. new PointF(10.0, 30.0)就是这个老报错

  4. 你的思路是对的 谢谢你的分享

  5. 我也是用e.HasMorePages =true,分页。也发现2次进入printpage但是我怎么2页内容重叠打到第一页了呢?请教

  6. @kaizi
    好久没用C#了,记不太清了

  7. 这篇文章是我自己写的,代码也是在我程序里拷出来的

  8. 代码就是从我程序里拷出来的
    VS报什么错误?

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>