设为首页
加入收藏
联系我们
首页 基础教程 技术文档 实例分析 数 据 库 疑难杂症 ASP.NET 七夕许愿树 技术论坛
同学网,基于同学关系的真实社区
<%-- 最新动态 Begin --%> <%-- 最新动态 End --%>
最新文章
 C#摄像头编程实例
 C#下用P2P技术实现点…
 Asp.net(c#)数…
 SQL Server数据…
 .NET牛人应该知道些什…
 NET牛人应该知道些什么
 SQL Server S…
 备份指定表到另一数据库
 SQLSERVER中快速…
 ASP.NET中url传…
 ASP.NET自动给UR…
 ASP.NET 2.0防…
 ASP.NET 2.0 …
 如何解决ASP.net中…
 sql server 与…
<%-- 最新动态 Begin --%> <%-- 最新动态 End --%>
推荐文章
 关于C#中的REF和黓认…
 读书笔记c#高级编程 委…
 【算法】C#快速排序类
 Visual C#的SQ…
 C#中调用API
 Infragistics…
 C#接口转换
 C#读取设备信息
 用.net操作word
 C# MessageBo…
 Visual C#中的数…
 雅虎公司C#笔试题,看看…
 C#.NET使用NHib…
 .net学习之运算符重载…
 Visual C# 3.…
<%-- 最新动态 Begin --%> <%-- 最新动态 End --%>
热门文章
 ADO.Net与ADO在…
 开发ASP.NET下的M…
 用C#+XMI技术进行U…
 什么是虚拟机?
 C#基础全接触
 C#学习第一天
 雅虎公司C#笔试题,看看…
 C#语言初级入门(1)
 C#中利用正则表达式实现…
 远程重启计算机(C#)
 用.net操作word
 什么是B/S三层?
 VB和C# 语法对比图 …
 Visual C#常用函…
 Visual C#的SQ…
使用.NET自带的类实现DataGrid报表的打印。
阅读正文 文字大小:增大 减小  文字行距:增大 减小   双击自动滚屏
本文由中国C#技术学习中心整理  如果你对本文有不明之处请到技术论坛讨论!

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
using System.Data;
using System.Collections;
using DataLibrary;

namespace ControlLibrary
{
 /// <summary>
 /// DataGrid打印
 /// </summary>
 public class DataGridPrinter
 {
  private PrintDocument ThePrintDocument;
  private DataTable TheTable;
  private DataGrid  TheDataGrid;
  public int RowCount = 0;
  private const int kVerticalCellLeeway = 10;
  public int PageNumber = 1;
  public ArrayList Lines = new ArrayList();
  public int header=0;
  public int footer=0;
  DataCatena DataCatena1;
  public int PageWidth;
  public int PageHeight;
  public int TopMargin;
  public int BottomMargin;
  int GridWidth = 0;
  public int LeftMargin;
  public int RightMargin;
  public string PaperName;
  public int pagecount;
  private int rows_page;
  public bool showfooter;

  public int bodylength
  {
   get
   {
    if(this.PageNumber<this.pagecount)
     return (1+this.rows_page) * ((int)(TheDataGrid.Font.SizeInPoints)  + kVerticalCellLeeway);
    else
     return (this.TheTable.Rows.Count + 1 -(this.rows_page*(this.PageNumber-1))) * ( (int)(TheDataGrid.Font.SizeInPoints)  + kVerticalCellLeeway);
   }
  }

  public DataGridPrinter(DataGrid aGrid, PrintDocument aPrintDocument,string theform,int Header,int Footer)
  {
   //
   // TODO: Add constructor logic here
   //
   this.header=Header;
   this.footer=Footer;
   this.showfooter=true;
   TheDataGrid = aGrid;
   ThePrintDocument = aPrintDocument;
   if(theform!="")
   {
    DataCatena1=new DataCatena();
    DataView myDV=DataCatena1.GetDataView("select * from yh_bbdy where bm='"+theform +"'");

    this.PaperName=myDV[0]["zm"].ToString();

    PaperSize pkSize;

    if(myDV[0]["fx"].ToString()=="True")
     this.ThePrintDocument.DefaultPageSettings.Landscape=true;
    else
     this.ThePrintDocument.DefaultPageSettings.Landscape=false;

    int found=0;
    for (int i = 0; i < this.ThePrintDocument.PrinterSettings.PaperSizes.Count; i++)
    {
     pkSize = this.ThePrintDocument.PrinterSettings.PaperSizes[i];
     if(pkSize.PaperName==this.PaperName)
     {
      this.ThePrintDocument.DefaultPageSettings.PaperSize=pkSize;
      found=1;
      i=this.ThePrintDocument.PrinterSettings.PaperSizes.Count;
      if(this.ThePrintDocument.DefaultPageSettings.Landscape)
      {
       PageHeight = pkSize.Width;
       PageWidth = pkSize.Height;
      }
      else
      {
       PageWidth = pkSize.Width;
       PageHeight = pkSize.Height;
      }
     }
    }

    if(found==0)
    {
     if(this.ThePrintDocument.DefaultPageSettings.Landscape)
     {
      PageHeight = Int32.Parse(myDV[0]["zk"].ToString());
      PageWidth = Int32.Parse(myDV[0]["zc"].ToString());
     }
     else
     {
      PageWidth = Int32.Parse(myDV[0]["zk"].ToString());
      PageHeight = Int32.Parse(myDV[0]["zc"].ToString());
     }
    }

    TopMargin = Int32.Parse(myDV[0]["sk"].ToString());
    BottomMargin = Int32.Parse(myDV[0]["xk"].ToString());
    RightMargin = Int32.Parse(myDV[0]["rightk"].ToString());
    LeftMargin = Int32.Parse(myDV[0]["leftk"].ToString());
   }
   else
   {
    PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
    PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
    TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;
    BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;
    RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;
    LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;
   }

   PageWidth -= this.LeftMargin ;
   PageWidth -= this.RightMargin;

   this.rows_page=(int)((float)(this.PageHeight-this.TopMargin-this.BottomMargin-this.footer-this.header)/(TheDataGrid.Font.SizeInPoints + kVerticalCellLeeway));

   for (int k = 0; k < TheDataGrid.TableStyles[0].GridColumnStyles.Count; k++)
   {
    GridWidth += TheDataGrid.TableStyles[0].GridColumnStyles[k].Width;  //  TheTable.Columns[k].ToString();
   }

  }

  public void DrawHeader(Graphics g)
  {
   SolidBrush ForeBrush = new SolidBrush(TheDataGrid.HeaderForeColor);
   SolidBrush BackBrush = new SolidBrush(Color.White);   //(TheDataGrid.HeaderBackColor);
   Pen TheLinePen = new Pen(TheDataGrid.GridLineColor, 1);
   StringFormat cellformat = new StringFormat();
   cellformat.Trimming = StringTrimming.EllipsisCharacter;
   cellformat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;
   cellformat.Alignment= StringAlignment.Center;


   int columnwidth = 0;

   int initialRowCount = RowCount;

   // draw the table header
   float startxposition = this.LeftMargin;                      //TheDataGrid.Location.X;
   RectangleF nextcellbounds = new RectangleF(0,0, 0, 0);

   /*
      这一段是画表头底色的代码

      RectangleF HeaderBounds  = new RectangleF(0, 0, 0, 0);

      HeaderBounds.X = this.LeftMargin;       //TheDataGrid.Location.X;
      HeaderBounds.Y =  + (RowCount - initialRowCount) * (TheDataGrid.Font.SizeInPoints  + kVerticalCellLeeway);
      HeaderBounds.Height = TheDataGrid.Font.SizeInPoints + kVerticalCellLeeway;
      HeaderBounds.Width = PageWidth;
   */
   float y1=(float)(header+this.TopMargin);

   g.DrawLine(TheLinePen, this.LeftMargin, y1, this.LeftMargin + this.PageWidth, y1);
   y1=y1+ (float)(TheDataGrid.Font.SizeInPoints + kVerticalCellLeeway);
   g.DrawLine(TheLinePen, this.LeftMargin, y1, this.LeftMargin + this.PageWidth, y1);

   //   g.FillRectangle(BackBrush, HeaderBounds);

   for (int k = 0; k < this.TheDataGrid.TableStyles[0].GridColumnStyles.Count; k++)
   {
    columnwidth = TheDataGrid.TableStyles[0].GridColumnStyles[k].Width * PageWidth / this.GridWidth;

    string nextcolumn = TheDataGrid.TableStyles[0].GridColumnStyles[k].HeaderText;  //  TheTable.Columns[k].ToString(); + (RowCount - initialRowCount) * (TheDataGrid.Font.SizeInPoints  + kVerticalCellLeeway)
    RectangleF cellbounds = new RectangleF(startxposition, header + TopMargin+2 ,
     columnwidth,
     TheDataGrid.HeaderFont.SizeInPoints + kVerticalCellLeeway-2);
    nextcellbounds = cellbounds;

    if (startxposition + columnwidth <= PageWidth+this.LeftMargin)
    {
     g.DrawString(nextcolumn, TheDataGrid.HeaderFont, ForeBrush, cellbounds, cellformat);
    }

    startxposition = startxposition + columnwidth;

   }
   y1=y1+ (float)(TheDataGrid.Font.SizeInPoints + kVerticalCellLeeway);
   g.DrawLine(TheLinePen, this.LeftMargin, y1, this.LeftMargin + this.PageWidth, y1);
 
   //if (TheDataGrid.GridLineStyle != DataGridLineStyle.None)
   // g.DrawLine(TheLinePen, TheDataGrid.Location.X, nextcellbounds.Bottom, PageWidth, nextcellbounds.Bottom);
  }

  public void SetDataSource(DataTable aTable)
  {
   TheTable = aTable;
   this.pagecount=(int)Math.Ceiling((double)(TheTable.Rows.Count)/(double)(this.rows_page));
   // MessageBox.Show("rows_count:"+TheTable.Rows.Count.ToString()+" rows_page:"+rows_page.ToString() + "page_count:" +this.pagecount.ToString());
   // this.ThePrintDocument
  }

  public bool DrawRows(Graphics g)
  {
   int lastRowBottom = TopMargin;
   Lines.Clear();

   try
   {
    SolidBrush ForeBrush = new SolidBrush(TheDataGrid.ForeColor);
    SolidBrush BackBrush = new SolidBrush(TheDataGrid.BackColor);
    SolidBrush AlternatingBackBrush = new SolidBrush(TheDataGrid.AlternatingBackColor);
    Pen TheLinePen = new Pen(TheDataGrid.GridLineColor, 1);
    StringFormat cellformat = new StringFormat();
    cellformat.Trimming = StringTrimming.EllipsisCharacter;
    cellformat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;
    int columnwidth = PageWidth/TheDataGrid.TableStyles[0].GridColumnStyles.Count;

    int initialRowCount = (this.PageNumber-1)*this.rows_page;
    int endrow=initialRowCount+this.rows_page;

    RectangleF RowBounds  = new RectangleF(0, 0, 0, 0);

    // draw vertical lines

    // draw the rows of the table
    for (int i = initialRowCount; i < TheTable.Rows.Count && i< endrow; i++)
    {
     DataRow dr = TheTable.Rows[i];
     int startxposition = this.LeftMargin+2;      //TheDataGrid.Location.X;

     RowBounds.X = 0;
     RowBounds.Y = header + TopMargin + ((RowCount - initialRowCount)+1) * (TheDataGrid.Font.SizeInPoints  + kVerticalCellLeeway);
     RowBounds.Height = TheDataGrid.Font.SizeInPoints + kVerticalCellLeeway;
     RowBounds.Width = PageWidth;

     
     /*  ///这一段是画表格底色的代码
          if (i%2 == 0)
          {
           g.FillRectangle(BackBrush, RowBounds);
          }
          else
          {
           g.FillRectangle(AlternatingBackBrush, RowBounds);
          }
     */

     for (int j = 0; j < TheDataGrid.TableStyles[0].GridColumnStyles.Count; j++)
     {
      columnwidth = TheDataGrid.TableStyles[0].GridColumnStyles[j].Width* PageWidth / this.GridWidth -2;
      RectangleF cellbounds = new RectangleF(startxposition,
       header + TopMargin + 2 +
       ((RowCount - initialRowCount) + 1) * (TheDataGrid.Font.SizeInPoints  + kVerticalCellLeeway),
       columnwidth,
       TheDataGrid.Font.SizeInPoints + kVerticalCellLeeway);
         

      if (startxposition + columnwidth <= PageWidth)
      {
       g.DrawString(dr[(TheDataGrid.TableStyles[0].GridColumnStyles[j].MappingName)].ToString(), TheDataGrid.Font, ForeBrush, cellbounds, cellformat);
      }

      startxposition = startxposition + columnwidth+2;
     }

     Lines.Add(RowBounds.Bottom);
     lastRowBottom = (int)RowBounds.Bottom;

     RowCount++;
    }

    DrawHorizontalLines(g, Lines);
    DrawVerticalGridLines(g, TheLinePen,lastRowBottom);
    
    if(this.showfooter==true)
     DrawFooter(g);

    if (this.PageNumber<this.pagecount)
    {
     return true;
    }
    else
    {
     return false;
    }

   }
   catch (Exception ex)
   {
    MessageBox.Show(ex.Message.ToString());

    return false;
   }

  }

  void DrawFooter(Graphics g)
  {
   FontFamily fontFamily = new FontFamily("宋体");

   string text="第"+this.PageNumber.ToString()+"页 共"
    +this.pagecount.ToString()+"页";

   Font font = new Font(
    fontFamily, 10,
    FontStyle.Regular,
    GraphicsUnit.Point);

   SizeF size= g.MeasureString(text,font);

   int startpos = this.PageHeight
    -this.BottomMargin;

   SolidBrush ForeBrush = new SolidBrush(Color.Black);

   StringFormat cellformat = new StringFormat();

   g.DrawString(text,font,ForeBrush,
    (this.PageWidth-size.Width)/2 + this.LeftMargin,
    startpos, cellformat);

   text="【Cobainsoft】";

   size= g.MeasureString(text,font);

   g.DrawString(text,font,ForeBrush,
    this.PageWidth + this.LeftMargin - size.Width-3,
    startpos, cellformat);

  }

 

  void DrawHorizontalLines(Graphics g, ArrayList lines)
  {
   Pen TheLinePen = new Pen(TheDataGrid.GridLineColor, 1);

   if (TheDataGrid.GridLineStyle == DataGridLineStyle.None)
    return;

   int i;

   for (i = 0;  i < lines.Count; i++)
   {
    g.DrawLine(TheLinePen, this.LeftMargin, (float)lines[i], this.LeftMargin + this.PageWidth, (float)lines[i]);
   }

  }

  void DrawVerticalGridLines(Graphics g, Pen TheLinePen, int bottom)
  {
   if (TheDataGrid.GridLineStyle == DataGridLineStyle.None)
    return;

   int posx=0;

   //画最左边的竖线

   g.DrawLine(TheLinePen, this.LeftMargin + posx,
    header + TopMargin,
    this.LeftMargin + posx,
    bottom);

   //画最右边的竖线
   g.DrawLine(TheLinePen, this.LeftMargin + this.PageWidth,
    header + TopMargin,
    this.LeftMargin + this.PageWidth,
    bottom);

   int total=TheDataGrid.TableStyles[0].GridColumnStyles.Count -1;
   for (int k = 0; k < total; k++)
   {
    posx+=(TheDataGrid.TableStyles[0].GridColumnStyles[k].Width) * this.PageWidth / this.GridWidth;
    g.DrawLine(TheLinePen, this.LeftMargin + posx,
     header + TopMargin,
     this.LeftMargin + posx,
     bottom);
   }
  }


  public bool DrawDataGrid(Graphics g)
  {

   try
   {
    DrawHeader(g);
    bool bContinue = DrawRows(g);
    return bContinue;
   }
   catch (Exception ex)
   {
    MessageBox.Show(ex.Message.ToString());
    return false;
   }

  }

 }

}



本文由中国C#技术学习中心整理  如果你对本文有不明之处请到技术论坛讨论!

中国C#技术交流QQ群:6337034  10976424  9383681  35248582  35248645
版权所有:中国C#技术学习中心 Copyright ? 2006-2008
建议浏览分辨率使用:1024*768分辨率
粤ICP备05002251号