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;
   }

}

}

}

使用.NET自带的类实现DataGrid报表的打印。相关推荐

  1. java 后端 使用 Graphics2D 制作海报,画echarts图,带工具类,各种细节:如头像切割成圆形,文字换行算法(完美实验success),解决画上文字、图片后不清晰问题

    文章目录 先看成品 前言 一.项目目录结构 一.海报制作PosterUtil.java工具类 1. 描述 2. 代码 二.测试生成海报 1. 描述 2. 直接上代码 四.其他测试 1. Test1_C ...

  2. 在.NET中不安装Office使用EPPlus生成带图表(Chart)的Excel报表

    在开发.NET应用中可能会遇到需要生成带图表(Chart)的Excel报表的需求,特别是在一些ASP.NET网站中,有时候我们并不能保证Web服务器上一定安装了Office组件,所以使用微软的Offi ...

  3. SAP BOM的类二维报表

    一个简单BOM的类二维报表. 代码如下: TABLES: MARA, T001W, AUFK.TYPES: BEGIN OF TY_OUTPUT,IDNRK TYPE STPOX-IDNRK, &qu ...

  4. 程序功能:创建打印机类Printer,定义抽象方法Print()。 创建针式打印机类DotMatrixtPrinter和墨式打印机InkpetPrinter两个子类,修改测试类,实现该打印机打印。

    程序功能:创建打印机类Printer,定义抽象方法Print(). 创建针式打印机类DotMatrixtPrinter和墨式打印机InkpetPrinter两个子类,并在各自类中重新print方法,编 ...

  5. GreenDao自带异步操作类简析

    AsyncSession: GreenDao提供一个异步操作的统一接口类AsyncSession,它提供了你所需要的所有异步操作方法. 你可以通过调用DaoSession#startAsyncSess ...

  6. 1.17 Java.util.logging:JDK自带记录日志类

    每个初学者都很熟悉在有问题的代码中使用 System.out.println 方法在控制台打印消息,来帮助观察程序运行的操作过程.如果你使用 System.out.println 方法,一旦发现问题的 ...

  7. php yii2 获取表里最大的id_Yii2中自带分页类实现分页

    1.首先写控制器层 先引用pagination类 use yiidataPagination; 写自己的方法: function actionFenye(){$data = Field::find() ...

  8. TP框架自带Http类实现下载文件(单一文件)

    在TP框架中有一个自带的Http类可以实现下载,而且比较方便: public function imgdown(){ import('ORG.Net.Http');$http = new \Org\N ...

  9. SpringBoot 自带工具类~ReflectionUtils

    org.springframework.util.ReflectionUtils 1.获取方法 // 在类中查找指定方法 Method findMethod(Class<?> clazz, ...

最新文章

  1. Serializer序列化使用
  2. 算法--------数组------反转字符串中的元音字母
  3. 启明智显分享| 关于ESP32-S3系列串口屏应用时配网需知
  4. mysql check table_mysql check table
  5. MongoDB安装的坑
  6. (12)FPGA面试题处理信号跨时域
  7. python中的第三方库 cv2_cv2 python
  8. ACCESS中执行sql语句
  9. 堪称神器的办公工具,国产精品福昕PDF编辑器上榜
  10. AI如何识别西瓜和冬瓜?
  11. 基于生物特征信息的身份识别(指纹、面部识别的方式和原理)的使用问题的思考
  12. 算法学习系列(贪心算法)—机器人攀登问题
  13. 上有尧舜之君,下有尧舜之民
  14. html5用css加粗字体,在CSS里怎样设置字体的浑厚,这个浑厚不是加粗……
  15. (转)利用Office里面的OWC组件进行画图
  16. Github加速访问
  17. 去ioe,什么是去IOE呢
  18. Linux下设备树dts内容(详细)总结及示例解析
  19. 关于千兆以太网项目的补充:FCS、CRC等校验功能
  20. HTML5Canvas实现抖音网红之龙卷风粒子旋涡特效

热门文章

  1. 1012. 数字分类 java_PAT-B-1012. 数字分类(Java)
  2. java飞机大战爆炸效果_Java飞机大战游戏设计与实现
  3. keras 的 example 文件 imdb_fasttext.py 解析
  4. Linux那些事儿 之 戏说USB(13)接口是设备的接口(二)
  5. Road-SLAM:基于道路标线车道级精度SLAM
  6. 强化学习(八) - 深度Q学习(Deep Q-learning, DQL,DQN)原理及相关实例
  7. 【坑爹】WebStorm编辑器突然回车不能换行了、回车不能使用、回车失效了!!!
  8. Blender制作3D模型导出到UE5完整学习教程
  9. Zookeeper ZAB协议原理浅析
  10. shell --- awk规范 系统总结