Winform中的打印总结篇

来源:互联网 发布:沈阳网络推广哪家好 编辑:程序博客网 时间:2024/06/07 16:03
在windows应用程序中文档的打印是一项非常重要的功能,在以前一直是一个非常复杂的工作,Microsoft .Net Framework的打印功能都以组件的方式提供,为程序员提供了很大的方便,但是这几个组件的使用还是很复杂的,有必要解释一下。
    打印操作通常包括以下四个功能
    1 打印设置 设置打印机的一些参数比如更改打印机驱动程序等
    2 页面设置 设置页面大小纸张类型等
    3 打印预览 类似于word中的打印预览
    4 打印

    在Winform中实现打印功能最主要的是PrintDocument类,这个类封装了当前的打印设置页面以及所有的与打印有关的事件和方法。
    该类有一个最重要的事件PrintPage事件,每打印一页时触发该事件,该事件接受一个PrintPageEventArgs参数,该参数封装了打印的相关信息。
    该类还包括一个重要的方法,Print()方法,该方法没有参数,调用它时将按照当前设置开始打印。
    下面的代码是打印功能的核心代码:PrintPage事件
    private void printDocument_PrintPage(object sender,PrintPageEventArgs e)
    {
     Graphics g = e.Graphics; //获得绘图对象
float linesPerPage = 0; //页面的行号
float yPosition = 0;   //绘制字符串的纵向位置
int count = 0; //行计数器
float leftMargin = e.MarginBounds.Left; //左边距
float topMargin = e.MarginBounds.Top; //上边距
  string line = null; 行字符串
Font printFont = this.textBox.Font; //当前的打印字体
SolidBrush myBrush = new SolidBrush(Color.Black);//刷子
linesPerPage = e.MarginBounds.Height / printFont.GetHeight(g);//每页可打印的行数
//逐行的循环打印一页
     while(count < linesPerPage && ((line=lineReader.ReadLine()) != null))
     {
         yPosition = topMargin + (count * printFont.GetHeight(g));
         g.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
         count++;
     }

if(line != null)  //如果本页打印完成而line不为空说明还有没完成的页面这将触发下一次的打印事 

                        //件在下一次的打印中lineReader会自动读取上次没有打印完的内容lineReader                        

                        //是这个打印方法外的类的成员它可以记录当前读取的位置

         e.HasMorePages = true;
     else
         e.HasMorePages = false;
    }

    下面的代码可以实现打印预览:

    protected void FileMenuItem_Print_Click(object sender,EventArgs e)
    {
    PrintDialog printDialog = new PrintDialog();
    printDialog.Document = printDocument;
    lineReader = new StringReader(textBox.Text);
    if (printDialog.ShowDialog() == DialogResult.OK)
    {
     try
        {
         printDocument.Print();
        }
       catch(Exception excep)
        {
              MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
              printDocument.PrintController.OnEndPrint(printDocument,new PrintEventArgs());
}
    }