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

.Net 5 下的可打印图文报表解决方案 最近需要处理一个有关打印的问题,有一些界面上的要求。首要选择是ECharts渲染图,因为其界面的表现是非常酷的;其次要求支持渲染表格;再次是需要可以打印、导出为word、pdf、excel等格式,有关打印,之前也处理过很多,最近的应用基本都是基于Fast-report,利用后台产生pdf完成的,当然前端也有很多的插件,比如vue-print等,针对这个功能,又有什么更好的方案呢? 先比对几个商业产品看看,毕竟商业版的比较重产品化。 1、纯后端方案 1.1、Fastreport.Net 最新版本支持.NE. 阅读详情

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

  }

 }

}

netcoreprint打印数据 netcoreprint打印数据 var rs = pn.GetYSBHListExcel(strWhere); string excelName = DateTime.Now.ToString("yyyyMmddHHmmss"); if (!String.IsNullOrEmpty(excelname)) { excelName = excelname; } var buffer = IO.printExcel(rs.Data, excelName); return File(buffer, "application/vnd.ms-excel", PubSetting.UserName + excelName + ".xlsx"); 立即下载

相关推荐

net图形报表控件源码(效果非常强大+亲测)

net图形报表控件源码它拥有功能强大的可视化报表设计器,支持缩放,撤消/重做,指针,标尺。它具有与水晶报表应用组件功能确实强大。

RDLC报表打印

如果你的报表能正常显示,会看到RDLC工具条下的打印图标:   如果在客户端,第一次去点击此铵钮,如果当前操作者没有管理权限,会提示: Unable to load client print control。   改为管理员,再点击打印机图片,在状态栏出现安装提示RSClientPrint Control:   按照提示,去安装ActiveX组件:   点击安装ActiveX控件:...

weixin_34203426的博客 228

使用VS自带RDLC报表,根据用户输入内容生成条形码并在报表上显示

使用VS自带RDLC报表,根据用户输入内容生成条形码并在报表上显示

C#.NET自定义报表数据打印

PS:自己曾经做过报表打印,但是没有这篇文章中所描述的饼状图,遂转,供以后使用参考。 这是一个自定义的报表打印,是对PrintPreviewDialog的扩展和封装。PrintPreviewDialog是一个windows的打印预览控件,该类返回的就是一个PrintPreviewDialog对象了,直接显示该控件就可以了。     该报表主要包含两个方面的内容:一个是数据统计分析的

Mr. Feng 3835

C# winform打印DataTable数据

简单的使用打印控件实现的打印表格效果,初学者有益

通用数据查询与报表打印系统开源源码

简单数据查询与报表打印系统源码通用数据查询与报表打印系统开源C#源码可以实现简单的人员管理,自定义查询功能比较突出数据库在DB_51aspx文件夹下,附加即可(不是还原)默认管理帐号密码均为51aspx

WPF中打印问题的探讨[转]

转自:http://blog.sina.com.cn/s/blog_624dc0120100ld6m.html 最近在做一个WPF方面的项目,在打印功能实现上费了很大劲。因为我原来是在做Winform方面的项目,接受WPF时感觉还很相似,可仔细往里做下去却发现两者外看相似,实则差异很大,打印就是其中很大的差距。Winform有对应的对话框围绕打印核心类PrintDocum...

weixin_30408309的博客 199

Asp.net 自带报表的使用详解

1:新建報表所需的數據源DataSet.cs 代码如下:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data; namespace ********{    public class DataSet    {        public DataTable CreatDataSet()        {            DataTable dt = new DataTable();            dt.Columns.Add(“A”);

使用.NET自带的类实现DataGrid报表的打印

使用.NET自带的类实现DataGrid报表的打印。using System;using System.Windows.Forms;using System.Drawing;using System.Drawing.Printing;using System.Data;using System.Collections;using DataLibrary;namespace Cont

maskX的专栏 895

Docker+vLLM内网离线部署Qwen3 流程

本文介绍了在CentOS 7系统下进行VLLM容器化部署Qwen3-32B大模型的内网离线方案。首先需准备Nvidia显卡驱动、CUDA 12.4和Docker环境。通过联网机器拉取vllm/vllm-openai镜像并导入内网服务器,同时从魔塔社区下载模型文件。部署时使用docker run命令启动容器,配置了GPU资源、内存共享、端口映射等参数,特别指定了模型路径、并行计算、内存利用率等关键参数。该方案实现了大模型在内网环境的安全高效部署,适用于需要离线运行的AI推理场景。

qq_42881308的博客 1036

保姆级教程:在ESXi 8.0上为NVIDIA ConnectX-5/6网卡开启SR-IOV(从BIOS到虚拟机配置)

本文提供在ESXi 8.0上为NVIDIA ConnectX-5/6网卡开启SR-IOV的详细教程,涵盖BIOS设置、固件配置、驱动优化及虚拟机部署。通过SR-IOV技术,显著提升虚拟化环境中的网络性能,适用于高性能计算、AI训练等场景。

weixin_26934905的博客 455
上一篇: 公共配置底层代码
下一篇: 如何用C#在Excel中生成图表?
甴曱
博客等级 码龄24年 184粉丝 29原创
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值