c#打印源代码
2007年07月11日 星期三 11:33
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Drawing.Printing; using System.Data; using System.Windows.Forms; namespace WindowsApplication1 { /**//// <summary> /// Summary description for DatagridPrint. /// </summary> public class DatagridPrint { private DataGrid dataGrid; private PrintDocument printDocument; private PageSetupDialog pageSetupDialog; private PrintPreviewDialog printPreviewDialog; public DatagridPrint(DataGrid dataGrid) { this.dataGrid = dataGrid; printDocument = new PrintDocument(); printDocument.PrintPage += new PrintPageEventHandler(this.printDocument_PrintPage); } private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { int rowCount = 0; int colCount = 0; int x = 0; int y = 0; int rowGap = 20; int colGap = 5; int leftMargin = 50; Font font = new Font("Arial", 10); Font headingFont = new Font("Arial", 11, FontStyle.Underline); Font captionFont = new Font("Arial", 10, FontStyle.Bold); Brush brush = new SolidBrush(Color.Black); string cellValue = ""; if(dataGrid.DataSource.GetType().ToString() == "System.Data.DataTable") { rowCount = ((DataTable)dataGrid.DataSource).Rows.Count; } else if(dataGrid.DataSource.GetType().ToString() == "System.Collections.ArrayList") { rowCount = ((ArrayList)dataGrid.DataSource).Count; } colCount = dataGrid.TableStyles[0].GridColumnStyles.Count; //print caption if(dataGrid.CaptionVisible) { y += rowGap; x = leftMargin; e.Graphics.DrawString(dataGrid.CaptionText, captionFont, brush, x, y); } //print headings y += rowGap; x = leftMargin; for(int j = 0; j < colCount; j++) { if(dataGrid.TableStyles[0].GridColumnStyles[j].Width > 0) { cellValue = dataGrid.TableStyles[0].GridColumnStyles[j].HeaderText; e.Graphics.DrawString(cellValue, headingFont, brush, x, y); x += dataGrid.TableStyles[0].GridColumnStyles[j].Width + colGap; } } //print all rows for(int i = 0; i < rowCount; i++) { y += rowGap; x = leftMargin; for(int j = 0; j < colCount; j++) { if(dataGrid.TableStyles[0].GridColumnStyles[j].Width > 0) { cellValue = dataGrid[i,j].ToString(); e.Graphics.DrawString(cellValue, font, brush, x, y); x += dataGrid.TableStyles[0].GridColumnStyles[j].Width + colGap; y = y + rowGap * (cellValue.Split(new char[] {' ', ' '}).Length - 1); } } } string s = cellValue; string f3 = cellValue; } public PrintDocument GetPrintDocument() { return printDocument; } public void Print() { try { pageSetupDialog = new PageSetupDialog(); pageSetupDialog.Document = printDocument; pageSetupDialog.ShowDialog(); printPreviewDialog = new PrintPreviewDialog(); printPreviewDialog.Document = printDocument; printPreviewDialog.Height = 600; 免费网站源码资源分享 printPreviewDialog.Width = 800; printPreviewDialog.ShowDialog(); } catch(Exception e) { throw new Exception("Printer error." + e.Message); } } } } |
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论