Windows Form 程序打印概述

本文没有新的技术或技巧,只是对Windows打印做一个小结,内容包括:多页打印,打印预览,打印机设置,页面设置。

一.打印
using System.Drawing.Printing;

private System.Drawing.Printing.PrintDocument printDocument;
this.printDocument.PrintPage += new PrintPageEventHandler(this.printDocument_PrintPage);

System.Collections.ArrayList InfoList = new ArrayList();
int TotalPages = 0;
int CurrentPage = 0;
const int LinesPerPage = 10;

private bool ReadyForPrint()
{
 InfoList.Clear();
 foreach (string line in this.textBox1.Lines)
 {
  InfoList.Add(line);
 }
 
 int Count = InfoList.Count;  
 if(Count>0)
 {  
  TotalPages = Count / LinesPerPage;
  if(Count%LinesPerPage != 0)
  {
   TotalPages ++;
  }
  CurrentPage = 1;
  return true;
 }
 else
 {
  return false;
 }
}

private void Print()
{
 if(ReadyForPrint())
 {
  this.printDocument.Print();
 }
}
 
private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)

 if(CurrentPage <= TotalPages)
 {
  Graphics g = e.Graphics;
  Font drawFont = new Font("Arial", 12);
  SolidBrush drawBrush = new SolidBrush(Color.Black);    

  for(int i=0;i<LinesPerPage;i++)
  {
   int line = (CurrentPage-1)*LinesPerPage + i;
   if(line > InfoList.Count-1){break;}

   string str = (string)InfoList[line];
   int x = 100;
   int y = 200 + 50*i;

   g.DrawString(str,drawFont,drawBrush,x,y);
  }

  CurrentPage++;
  if(CurrentPage <= TotalPages)
  {
   e.HasMorePages = true;
  }
  else
  {
   e.HasMorePages = false;
  }
  }
 }
}

当调用this.printDocument.Print();时,打印进程开始执行printDocument_PrintPage的内容。当该函数退出时如果e.HasMorePages为true,则打印进程会再次调用printDocument_PrintPage,打印进程不会知道打印总页数和当前打印页,这需要用户自己组织。


二.打印预览
private void PreView()
{
 if(ReadyForPrint())
 {
  PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
  printPreviewDialog.Document = printDocument;
  try
  {
   printPreviewDialog.ShowDialog();
  }
  catch(Exception excep)
  {
   MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
  } 
 }
}
打印预览进程同样会调用printDocument_PrintPage,所以必须运行 ReadyForPrint()以便printDocument_PrintPage能正确执行。


三.打印机设置
private void SetPrinter()
{
 PrintDialog printDialog = new PrintDialog();
 printDialog.Document = printDocument;
 printDialog.ShowDialog();
}   
  

四.页面设置
private void SetPage()
{
 PageSetupDialog pageSetupDialog = new PageSetupDialog();
 pageSetupDialog.Document = printDocument;
 pageSetupDialog.ShowDialog();



下载源代码

posted @ 2007-01-23 14:24  seabluescn  阅读(6348)  评论(1编辑  收藏  举报