Windows Form 程式列印概述

來源:互聯網
上載者:User

本文沒有新的技術或技巧,只是對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();

下載原始碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.