打印,打印datagrid
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Data;
namespace train
...{
/**//// <summary>
/// DataGridPrinter負責打印
/// </summary>
public class DataGridPrinter
...{
private DataTable table;
private PrintDocument printDocument;
private PageSetupDialog pageSetupDialog;
private PrintPreviewDialog printPrevIEwDialog;
public DataGridPrinter(DataTable printtable)
...{
printDocument=new PrintDocument();
table=printtable;
}
/**//// <summary>
/// 實現打印事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void printDocument_PrintPage(object sender,PrintPageEventArgs e)
...{
Font objFont=new Font("Tahoma",12,FontStyle.Regular);
Brush objBrush=Brushes.Black;
Pen objPen=new Pen(objBrush);
objPen.Width=3;
float nleft=pageSetupDialog.PageSettings.Margins.Left;
float ntop=pageSetupDialog.PageSettings.Margins.Top;
for(int i=0;i<table.Columns.Count;i++)
...{
e.Graphics.DrawString(table.Columns[i].ColumnName,objFont,objBrush,nleft,ntop);
nleft=nleft+180;
}
ntop=ntop+20;
try
...{
for(int i=0;i<table.Rows.Count;i++)
...{
ntop=ntop+20;
nleft=pageSetupDialog.PageSettings.Margins.Left;
for(int j=0;j<table.Columns.Count;j++)
...{
e.Graphics.DrawString(table.Rows[i][j].ToString(),objFont,objBrush,nleft,ntop);
nleft=nleft+180;
}
}
}
catch(Exception ex)
...{
Console.WriteLine(ex.Message);
}
}
/**//// <summary>
/// 打印數據
/// </summary>
public void Print()
...{
printDocument.PrintPage+=new PrintPageEventHandler(printDocument_PrintPage);
try
...{
pageSetupDialog=new PageSetupDialog();
; pageSetupDialog.Document=printDocument;
pageSetupDialog.Document.DefaultPageSettings.Landscape=true;
if(pageSetupDialog.ShowDialog()==DialogResult.OK)
...{
printPreviewDialog=new PrintPrevIEwDialog();
printPrevIEwDialog.Document=printDocument;
printPrevIEwDialog.Height=600;
printPrevIEwDialog.Width=800;
printPrevIEwDialog.ShowDialog();
}
}
catch(Exception e)
...{
throw new Exception("打印出現錯誤:"+e.Message);
}
}
}
}