欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

网页WEB打印控件制作

程序员文章站 2023-12-05 22:01:34
在web系统中,打印的确是比较烦人的问题,如果我们能制作一个属于自己的自定义的打印插件,那么我们在后续自定义打印的时候能随心所欲的控制打印,这样的效果对于程序员来说是非常开...

在web系统中,打印的确是比较烦人的问题,如果我们能制作一个属于自己的自定义的打印插件,那么我们在后续自定义打印的时候能随心所欲的控制打印,这样的效果对于程序员来说是非常开心的一件事件,本文将自己开发编写的c# 制作的html打印插件分享出来,让有同样需求的朋友提供一个参考;此插件是基于microsoft .net framework 2.0 开发的,缺点是每台客户端在安装插件时,必须要安装microsoft .net framework 2.0 ;本插件能实现 页眉、页脚、表头、标题、表尾的分页打印;支持纸张类型、自动补充空行等功能;由于技术有限,肯定有很多不足的地方,请批评指正!

由于本打印插件是基于我们开发平台的报表基础来开发设计的,所以打印控件的原理:通过js将页面表格数据生成固定格式的xml字符串(图片通过64base图片格式)传送给打印插件,有打印插件自主绘图生成打印页面。e_print插件可以在web或winform中使用:

打印插件完整源码:e_print.rar (包含插件源码、打包程序、winform调试demo)

下面贴出源码:(在源码中有详细的注释说明)

1、printcontrol 打印插件类

using system;
using system.collections.generic;
using system.componentmodel;
using system.drawing;
using system.data;
using system.text;
using system.windows.forms;
using system.runtime.interopservices;
using system.drawing.printing;
using system.xml;
using system.security;
using system.drawing.drawingd;
using system.drawing.text;
using system.text.regularexpressions;
namespace e_print
{
/// <summary>
/// 打印控件
/// 实现iobjectsafety接口
/// 网页上所有所使用到的guid 通过guid工具生成的唯一编码
/// dedd-ba--a-ffbeec 编码以后不允许修改
/// </summary>
[guid("dedd-ba--a-ffbeec"), progid("ereportprint"), comvisible(true)]
public partial class printcontrol : usercontrol, iobjectsafety
{
#region 私有变量
#region 通用参数
/// <summary>
/// 缩放比例
/// </summary>
private float zoom = ;
/// <summary>
/// 网页高度 像素 px
/// </summary>
private float htmlheight = ;
/// <summary>
/// 网页宽度 像素 px
/// </summary>
private float htmlwidth = ;
/// <summary>
/// 报表区域矩形
/// </summary>
private rectanglef tablerect = new rectanglef();
/// <summary>
/// 报表绘制实例
/// </summary>
private reportdraw rptdraw = new reportdraw();
#endregion
#region 页边距
/// <summary>
/// 左边距 
/// 毫米 mm(一位小数)
/// </summary>
private float _marginleft = .f;
/// <summary>
/// 右边距
/// </summary>
private float _marginright = .f;
/// <summary>
/// 上边距
/// </summary>
private float _margintop = .f;
/// <summary>
/// 下边距
/// </summary>
private float _marginbottom = .f;
#endregion
#region 版型方向
/// <summary>
/// 版型方向 landscape: true 横向;false 纵向
/// </summary>
private bool _landscape = false;
#endregion
#region 纸型大小
/// <summary>
/// 纸张类型
/// </summary>
private string _papername = "a";
/// <summary>
/// 纸张宽度
/// </summary>
private int _paperwidth = ; // 毫米
/// <summary>
/// 纸张高度
/// </summary>
private int _paperheight = ; // 毫米
#endregion
#region 打印参数
/// <summary>
/// 自适应纸张大小方法 
/// null: 无
/// row: 横向
/// col: 纵向
/// </summary>
private string _zoomtype = "null";
/// <summary>
/// 是否每页打印标题
/// </summary>
private bool _istbltitleallpage = false;
/// <summary>
/// 是否每页打印表头
/// </summary>
private bool _istblheadallpage = false;
/// <summary>
/// 是否每页打印表尾
/// </summary>
private bool _istblfootallpage = false;
/// <summary>
/// 最后一页自动补行
/// </summary>
private bool _isautofillrow = false;
/// <summary>
/// 字符溢出是否换行缩小处理方式
/// </summary>
private bool _isoverflow = false;
/// <summary>
/// 打印数据
/// </summary>
private string _dataxml = "";
#endregion
#region 页眉参数
/// <summary>
/// 页眉--绘制页眉
/// </summary>
private bool _headdraw = false;
/// <summary>
/// 页眉--高度 毫米
/// 默认 刚好
/// </summary>
private float _headheight = .f;
/// <summary>
/// 页眉--左侧文字
/// </summary>
private string _headleft = "";
/// <summary>
/// 页眉--中间文字
/// </summary>
private string _headcenter = "";
/// <summary>
/// 页眉--右侧文字
/// </summary>
private string _headright = "";
/// <summary>
/// 页眉--字体名称
/// </summary>
private string _headfontname = "宋体";
/// <summary>
/// 页眉--字体大小
/// </summary>
private string _headfontsize = "pt";
/// <summary>
/// 页眉--字体颜色
/// </summary>
private string _headfontcolor = "black";
/// <summary>
/// 页眉--字体--粗体
/// </summary>
private bool _headfontbold = false;
/// <summary>
/// 页眉--字体--斜体
/// </summary>
private bool _headfontitalic = false;
/// <summary>
/// 页眉--字体--删除线
/// </summary>
private bool _headfontstrikeout = false;
/// <summary>
/// 页眉--字体--下划线
/// </summary>
private bool _headfontunderline = false;
/// <summary>
/// 页眉--绘制分隔线
/// </summary>
private bool _headlinedraw = false;
/// <summary>
/// 页眉--分隔线宽度
/// </summary>
private float _headlinewidth = .f;
/// <summary>
/// 页眉--分隔线线型
/// </summary>
private string _headlinedash = "solid";
/// <summary>
/// 页眉--分隔线颜色
/// </summary>
private string _headlinecolor = "black";
#endregion
#region 页脚参数
/// <summary>
/// 页脚--绘制页脚
/// </summary>
private bool _footdraw = false;
/// <summary>
/// 页脚--高度 毫米
/// </summary>
private float _footheight = .f;
/// <summary>
/// 页脚--左侧文字
/// </summary>
private string _footleft = "";
/// <summary>
/// 页脚--中间文字
/// </summary>
private string _footcenter = "";
/// <summary>
/// 页脚--右侧文字
/// </summary>
private string _footright = "";
/// <summary>
/// 页脚--字体名称
/// </summary>
private string _footfontname = "宋体";
/// <summary>
/// 页脚--字体大小
/// </summary>
private string _footfontsize = "pt";
/// <summary>
/// 页脚--字体颜色
/// </summary>
private string _footfontcolor = "black";
/// <summary>
/// 页脚--字体--粗体
/// </summary>
private bool _footfontbold = false;
/// <summary>
/// 页脚--字体--斜体
/// </summary>
private bool _footfontitalic = false;
/// <summary>
/// 页脚--字体--删除线
/// </summary>
private bool _footfontstrikeout = false;
/// <summary>
/// 页脚--字体--下划线
/// </summary>
private bool _footfontunderline = false;
/// <summary>
/// 页脚--绘制分隔线
/// </summary>
private bool _footlinedraw = false;
/// <summary>
/// 页脚--分隔线宽度
/// </summary>
private float _footlinewidth = .f;
/// <summary>
/// 页脚--分隔线线型
/// </summary>
private string _footlinedash = "solid";
/// <summary>
/// 页脚--分隔线颜色
/// </summary>
private string _footlinecolor = "black";
#endregion
#endregion
#region 构造方法
/// <summary>
/// 打印控件构造函数
/// </summary>
public printcontrol()
{
initializecomponent();
init_pagesetting();
}
#endregion
#region 接口实现
private const string _iid_idispatch = "{---c-}";
private const string _iid_idispatchex = "{aef-c-d--acdcaa}";
private const string _iid_ipersiststorage = "{a---c-}";
private const string _iid_ipersiststream = "{---c-}";
private const string _iid_ipersistpropertybag = "{df-cb-ce--aabb}";
private const int interfacesafe_for_untrusted_caller = x;
private const int interfacesafe_for_untrusted_data = x;
private const int s_ok = ;
private const int e_fail = unchecked((int)x);
private const int e_nointerface = unchecked((int)x);
private bool _fsafeforscripting = true;
private bool _fsafeforinitializing = true;
public int getinterfacesafetyoptions(ref guid riid, ref int pdwsupportedoptions, ref int pdwenabledoptions)
{
int rslt = e_fail;
string strguid = riid.tostring("b");
pdwsupportedoptions = interfacesafe_for_untrusted_caller | interfacesafe_for_untrusted_data;
switch (strguid)
{
case _iid_idispatch:
case _iid_idispatchex:
rslt = s_ok;
pdwenabledoptions = ;
if (_fsafeforscripting == true)
pdwenabledoptions = interfacesafe_for_untrusted_caller;
break;
case _iid_ipersiststorage:
case _iid_ipersiststream:
case _iid_ipersistpropertybag:
rslt = s_ok;
pdwenabledoptions = ;
if (_fsafeforinitializing == true)
pdwenabledoptions = interfacesafe_for_untrusted_data;
break;
default:
rslt = e_nointerface;
break;
}
return rslt;
}
public int setinterfacesafetyoptions(ref guid riid, int dwoptionsetmask, int dwenabledoptions)
{
int rslt = e_fail;
string strguid = riid.tostring("b");
switch (strguid)
{
case _iid_idispatch:
case _iid_idispatchex:
if (((dwenabledoptions & dwoptionsetmask) == interfacesafe_for_untrusted_caller) && (_fsafeforscripting == true))
rslt = s_ok;
break;
case _iid_ipersiststorage:
case _iid_ipersiststream:
case _iid_ipersistpropertybag:
if (((dwenabledoptions & dwoptionsetmask) == interfacesafe_for_untrusted_data) && (_fsafeforinitializing == true))
rslt = s_ok;
break;
default:
rslt = e_nointerface;
break;
}
return rslt;
}
#endregion
#region 属性方法
#region 页边距
/// <summary>
/// 获取--设置--左边距
/// 计量单位 毫米(mm)
/// </summary>
public float marginleft
{
get { return _marginleft; }
set { _marginleft = value; }
}
/// <summary>
/// 获取--设置--右边距
/// 计量单位 毫米(mm)
/// </summary>
public float marginright
{
get { return _marginright; }
set { _marginright = value; }
}
/// <summary>
/// 获取--设置--上边距
/// 计量单位 毫米(mm) 
/// </summary>
public float margintop
{
get { return _margintop; }
set { _margintop = value; }
}
/// <summary>
/// 获取--设置--下边距
/// 计量单位 毫米(mm) 
/// </summary>
public float marginbottom
{
get { return _marginbottom; }
set { _marginbottom = value; }
}
#endregion
#region 版型方向
/// <summary>
/// 获取--设置--版型方向
/// landscape: true 横向; false 纵向
/// </summary>
public bool landscape
{
get { return _landscape; }
set { _landscape = value; }
}
#endregion
#region 纸张属性
/// <summary>
/// 获取--设置--纸张类型
/// </summary>
public string papername
{
get { return _papername; }
set { _papername = value; }
}
/// <summary>
/// 获取--设置--纸张高度
/// 计量单位 毫米(mm)
/// </summary>
public int paperheight
{
get { return _paperheight; }
set { _paperheight = value; }
}
/// <summary>
/// 获取--设置--纸张宽度
/// 计量单位 毫米(mm)
/// </summary>
public int paperwidth
{
get { return _paperwidth; }
set { _paperwidth = value; }
}
#endregion
#region 页眉参数
/// <summary>
/// 获取--设置--页眉是否绘制
/// </summary>
public bool headdraw
{
get { return _headdraw; }
set { _headdraw = value; }
}
/// <summary>
/// 获取--设置--页眉高度
/// 单位:毫米整数类型
/// </summary>
public float headheight
{
get { return _headheight; }
set { _headheight = value; }
}
/// <summary>
/// 获取--设置--页眉左侧文字
/// </summary>
public string headleft
{
get { return _headleft; }
set { _headleft = value; }
}
/// <summary>
/// 获取--设置--页眉中间文字
/// </summary>
public string headcenter
{
get { return _headcenter; }
set { _headcenter = value; }
}
/// <summary>
/// 获取--设置--页眉右侧文字
/// </summary>
public string headright
{
get { return _headright; }
set { _headright = value; }
}
/// <summary>
/// 获取--设置--页眉字体名称
/// </summary>
public string headfontname
{
get { return _headfontname; }
set { _headfontname = value; }
}
/// <summary>
/// 获取--设置--页眉字体大小
/// </summary>
public string headfontsize
{
get { return _headfontsize; }
set { _headfontsize = value; }
}
/// <summary>
/// 获取--设置--页眉字体颜色
/// </summary>
public string headfontcolor
{
get { return _headfontcolor; }
set { _headfontcolor = value; }
}
/// <summary>
/// 获取--设置--页眉字体--粗体
/// </summary>
public bool headfontbold
{
get { return _headfontbold; }
set { _headfontbold = value; }
}
/// <summary>
/// 获取--设置--页眉字体--斜体
/// </summary>
public bool headfontitalic
{
get { return _headfontitalic; }
set { _headfontitalic = value; }
}
/// <summary>
/// 获取--设置--页眉字体--删除线
/// </summary>
public bool headfontstrikeout
{
get { return _headfontstrikeout; }
set { _headfontstrikeout = value; }
}
/// <summary>
/// 获取--设置--页眉字体--下划线
/// </summary>
public bool headfontunderline
{
get { return _headfontunderline; }
set { _headfontunderline = value; }
}
/// <summary>
/// 获取--设置--是否绘制分割线
/// </summary>
public bool headlinedraw
{
get { return _headlinedraw; }
set { _headlinedraw = value; }
}
/// <summary>
/// 获取--设置--页眉分隔线宽度
/// </summary>
public float headlinewidth
{
get { return _headlinewidth; }
set { _headlinewidth = value; }
}
/// <summary>
/// 获取--设置--页眉分隔线线型
/// </summary>
public string headlinedash
{
get { return _headlinedash; }
set { _headlinedash = value; }
}
/// <summary>
/// 获取--设置--页眉分隔线颜色
/// </summary>
public string headlinecolor
{
get { return _headlinecolor; }
set { _headlinecolor = value; }
}
#endregion
#region 页脚参数
/// <summary>
/// 获取--设置--页脚是否绘制
/// </summary>
public bool footdraw
{
get { return _footdraw; }
set { _footdraw = value; }
}
/// <summary>
/// 获取--设置--页脚高度
/// 单位:毫米整数类型
/// </summary>
public float footheight
{
get { return _footheight; }
set { _footheight = value; }
}
/// <summary>
/// 获取--设置--页脚左侧文字
/// </summary>
public string footleft
{
get { return _footleft; }
set { _footleft = value; }
}
/// <summary>
/// 获取--设置--页脚中间文字
/// </summary>
public string footcenter
{
get { return _footcenter; }
set { _footcenter = value; }
}
/// <summary>
/// 获取--设置--页脚右侧文字
/// </summary>
public string footright
{
get { return _footright; }
set { _footright = value; }
}
/// <summary>
/// 获取--设置--页脚字体名称
/// </summary>
public string footfontname
{
get { return _footfontname; }
set { _footfontname = value; }
}
/// <summary>
/// 获取--设置--页脚字体大小
/// </summary>
public string footfontsize
{
get { return _footfontsize; }
set { _footfontsize = value; }
}
/// <summary>
/// 获取--设置--页脚字体颜色
/// </summary>
public string footfontcolor
{
get { return _footfontcolor; }
set { _footfontcolor = value; }
}
/// <summary>
/// 获取--设置--页脚字体--粗体
/// </summary>
public bool footfontbold
{
get { return _footfontbold; }
set { _footfontbold = value; }
}
/// <summary>
/// 获取--设置--页脚字体--斜体
/// </summary>
public bool footfontitalic
{
get { return _footfontitalic; }
set { _footfontitalic = value; }
}
/// <summary>
/// 获取--设置--页脚字体--删除线
/// </summary>
public bool footfontstrikeout
{
get { return _footfontstrikeout; }
set { _footfontstrikeout = value; }
}
/// <summary>
/// 获取--设置--页脚字体--下划线
/// </summary>
public bool footfontunderline
{
get { return _footfontunderline; }
set { _footfontunderline = value; }
}
/// <summary>
/// 获取--设置--是否绘制分割线
/// </summary>
public bool footlinedraw
{
get { return _footlinedraw; }
set { _footlinedraw = value; }
}
/// <summary>
/// 获取--设置--页脚分隔线宽度
/// </summary>
public float footlinewidth
{
get { return _footlinewidth; }
set { _footlinewidth = value; }
}
/// <summary>
/// 获取--设置--页脚分隔线线型
/// </summary>
public string footlinedash
{
get { return _footlinedash; }
set { _footlinedash = value; }
}
/// <summary>
/// 获取--设置--页脚分隔线颜色
/// </summary>
public string footlinecolor
{
get { return _footlinecolor; }
set { _footlinecolor = value; }
}
#endregion
#region 打印参数
/// <summary>
/// 获取--设置--打印数据
/// 前台传入的xml格式的打印数据
/// </summary>
public string dataxml
{
get { return _dataxml; }
set { _dataxml = value; }
}
/// <summary>
/// 获取--设置--是否每页打印标题
/// </summary>
public bool istbltitleallpage
{
get { return _istbltitleallpage; }
set { _istbltitleallpage = value; }
}
/// <summary>
/// 获取--设置--是否每页打印表头
/// </summary>
public bool istblheadallpage
{
get { return _istblheadallpage; }
set { _istblheadallpage = value; }
}
/// <summary>
/// 获取--设置--是否每页打印表尾
/// </summary>
public bool istblfootallpage
{
get { return _istblfootallpage; }
set { _istblfootallpage = value; }
}
/// <summary>
/// 获取--设置--末页自动补行
/// </summary>
public bool isautofillrow
{
get { return _isautofillrow; }
set { _isautofillrow = value; }
}
/// <summary>
/// 获取--设置--缩放方向
/// 参数:以下三种;默认null
/// null: 无
/// row: 横向
/// col: 纵向
/// </summary>
public string zoomtype
{
get { return _zoomtype; }
set { _zoomtype = value; }
}
/// <summary>
/// 获取--设置--字符溢出是否缩小换行处理方式
/// </summary>
public bool isoverflow
{
get { return _isoverflow; }
set { _isoverflow = value; }
}
#endregion
#region 加载参数
/// <summary>
/// 加载打印参数
/// </summary>
public void initprintparam()
{
init_pagesetting();
}
#endregion
#endregion
#region 加载事件
/// <summary>
/// 初始化--页面设置参数
/// </summary>
private void init_pagesetting()
{
this.e_printdocument.defaultpagesettings.margins.left = (int)math.round(marginleft * ); // 左边距
this.e_printdocument.defaultpagesettings.margins.right = (int)math.round(marginright * ); // 右边距
this.e_printdocument.defaultpagesettings.margins.top = (int)math.round(margintop * ); // 上边距
this.e_printdocument.defaultpagesettings.margins.bottom = (int)math.round(marginbottom * ); // 下边距
this.e_printdocument.printersettings.copies = ; // 打印份数
this.e_printdocument.defaultpagesettings.landscape = this.landscape; // 版型方向 
papersize size = getpapersize(papername); // 纸张类型
if (size != null)
this.e_printdocument.defaultpagesettings.papersize = size;
else
this.e_printdocument.defaultpagesettings.papersize = new papersize(this.papername, (int)math.round(this.paperwidth / . * ), (int)math.round(this.paperheight / . * ));
}
/// <summary>
/// 获取--纸张类型
/// </summary>
/// <param name="papername">纸张类型名称</param>
/// <returns></returns>
private papersize getpapersize(string papername)
{
papersize paper = null;
foreach (papersize ps in this.e_printdocument.printersettings.papersizes)
{
if (ps.papername.tolower() == papername.tolower()) // 检查打印机是否有指定的纸张类型
{
paper = ps;
break;
}
}
return paper;
}
#endregion
#region 打印事件
/// <summary>
/// 直接打印
/// 此处加入了再次调用打印设置界面,因为用户可能需要选择那种打印机
/// </summary>
/// <returns></returns>
public string print()
{
// 直接打印时,直接调用printdocument的print()方法
// 因为用户可能在打印之前还要再更改打印设置所以需再次显示打印设置对话框
if (this.e_printdialog.showdialog() == dialogresult.ok)
{
try
{
this.init_printer();
this.e_printdocument.print();
}
catch (exception ex)
{
this.e_printdocument.printcontroller.onendprint(this.e_printdocument, new printeventargs());
return ex.message.tostring();
}
}
return "";
}
/// <summary>
/// 打印预览
/// 将打印的数据进行预览
/// </summary>
public string preview()
{
try
{
this.init_printer();
this.e_printpreviewdialog.showdialog();
}
catch (exception ex)
{
return ex.message.tostring();
}
return "";
}
/// <summary>
/// 页面设置
/// 设置打印的页面的纸张大小、纸型、页面边距
/// </summary>
public void pageste()
{
// 页面设置对话框中使用的是公制长度计量单位 (厘米)
// 在.net中采用的是英制的计量单位 (英寸)
// 英寸约等于.厘米,厘米=毫米
// 所以在下面中需要加入转换信息 将对话框中设置的页边距进行转换保存
// 设置传入的纸张信息
if (this.e_pagesetupdialog.showdialog() == dialogresult.ok) // 弹出页面设置对话框
{
if (system.globalization.regioninfo.currentregion.ismetric) // 转换页边距计量单位
this.e_pagesetupdialog.pagesettings.margins = printerunitconvert.convert(this.e_pagesetupdialog.pagesettings.margins, printerunit.display, printerunit.tenthsofamillimeter);
this.e_printdocument.defaultpagesettings = this.e_pagesetupdialog.pagesettings; // 更新页面设置参数值
// 更新参数
this.landscape = this.e_printdocument.defaultpagesettings.landscape; // 版型方向 
this.papername = this.e_printdocument.defaultpagesettings.papersize.papername; // 纸张类型
papersize tmpsize = this.e_printdocument.defaultpagesettings.papersize; // 纸张尺寸
this.paperwidth = (int)math.round(tmpsize.width * . / ); // 纸张宽度
this.paperheight = (int)math.round(tmpsize.height * . / ); // 纸张高度
this.marginleft = (float)math.round(this.e_printdocument.defaultpagesettings.margins.left / f, ); // 左边距
this.marginright = (float)math.round(this.e_printdocument.defaultpagesettings.margins.right / f, ); // 右边距
this.margintop = (float)math.round(this.e_printdocument.defaultpagesettings.margins.top / f, ); // 上边距
this.marginbottom = (float)math.round(this.e_printdocument.defaultpagesettings.margins.bottom / f, ); // 下边距
}
}
/// <summary>
/// 打印设置
/// 设置打印机的信息(选择打印机、设置打印份数等信息)
/// </summary>
public void printset()
{
this.e_printdialog.showdialog();
}
#endregion
#region 绘制对象
/// <summary>
/// 打印及打印前初始化数据
/// </summary>
private void init_printer()
{
htmlheight = ; // 网页报表高度
htmlwidth = ; // 网页报表宽度
calctablerect(); // 计算区域矩形
rptdraw = new reportdraw(); // 报表绘制实例
rptdraw.isallprinttitle = this._istbltitleallpage; // 每页打印标题
rptdraw.isallprinthead = this._istblheadallpage; // 每页打印表头
rptdraw.isallprintfoot = this._istblfootallpage; // 每页打印表尾
rptdraw.isautofillrow = this._isautofillrow; // 末页自动补行
rptdraw.isoverflow = this._isoverflow; // 字符溢出缩小
rptdraw.reptrect = tablerect; // 赋值报表矩形
if (!parsexml()) return; // 解析报表数据
calcreportzoom(); // 计算缩小比例
calczoomallsize(); // 按比计算尺寸
rptdraw.zoom = this.zoom; // 赋值缩小比例 
rptdraw.calcpaging(); // 计算打印分页
}
/// <summary>
/// printdocument 对象打印绘制事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void e_printdoc_printpage(object sender, printpageeventargs e)
{
graphics g = e.graphics;
g.clear(color.white);
drawheader(g);
drawfooter(g);
if (rptdraw.drawreport(g))
e.hasmorepages = true;
else
e.hasmorepages = false;
}
/// <summary>
/// 绘制页眉
/// </summary>
/// <param name="g">绘图对象</param>
private void drawheader(graphics g)
{
// 是否绘制
if (_headdraw)
{
// 页眉实例
pageheader pgheader = new pageheader();
// 页眉矩形
rectanglef pgheaderrect = new rectanglef(tablerect.x, // x 坐标
tablerect.y - mmtopixel(_headheight), // y 坐标 
tablerect.width, // w 宽度
mmtopixel(_headheight) // h 高度
);
// 页眉赋值
pgheader.headrect = pgheaderrect;
pgheader.strleft = replacepagenum(_headleft); // 左侧文本
pgheader.strcenter = replacepagenum(_headcenter); // 中间文本 
pgheader.strright = replacepagenum(_headright); // 右侧文本
fontstyle fontstyle = fontstyle.regular; // 字体样式
if (_headfontbold) fontstyle |= fontstyle.bold;
if (_headfontitalic) fontstyle |= fontstyle.italic;
if (_headfontstrikeout) fontstyle |= fontstyle.strikeout;
if (_headfontunderline) fontstyle |= fontstyle.underline;
pgheader.strfont = new font(_headfontname, (float)convert.todouble(_headfontsize.tolower().replace("px", "").replace("pt", "")), fontstyle, graphicsunit.point);
pgheader.strcolor = (color)printtool.strtocolor(_headfontcolor);
if (_headlinedraw) // 绘制分割线
{
pgheader.linedraw = _headlinedraw;
pgheader.linewidth = _headlinewidth;
pgheader.linecolor = (color)printtool.strtocolor(_headlinecolor);
pgheader.linedash = printtool.getdashstyle(_headlinedash);
}
// 页眉绘制
pgheader.draw(g);
}
}
/// <summary>
/// 绘制页脚
/// </summary>
/// <param name="g">绘图对象</param>
private void drawfooter(graphics g)
{
// 是否绘制
if (_footdraw)
{
// 页脚实例
pagefooter pgfooter = new pagefooter();
// 页脚矩形
rectanglef pgfooterrect = new rectanglef(tablerect.x, // x 坐标
tablerect.y + tablerect.height, // y 坐标 
tablerect.width, // w 宽度
mmtopixel(_footheight) // h 高度
);
// 页脚赋值
pgfooter.footrect = pgfooterrect;
pgfooter.strleft = replacepagenum(_footleft); // 左侧文本
pgfooter.strcenter = replacepagenum(_footcenter); // 中间文本 
pgfooter.strright = replacepagenum(_footright); // 右侧文本
fontstyle fontstyle = fontstyle.regular; // 字体样式
if (_footfontbold) fontstyle |= fontstyle.bold;
if (_footfontitalic) fontstyle |= fontstyle.italic;
if (_footfontstrikeout) fontstyle |= fontstyle.strikeout;
if (_footfontunderline) fontstyle |= fontstyle.underline;
pgfooter.strfont = new font(_footfontname, (float)convert.todouble(_footfontsize.tolower().replace("px", "").replace("pt", "")), fontstyle, graphicsunit.point);
pgfooter.strcolor = (color)printtool.strtocolor(_footfontcolor);
if (_footlinedraw) // 绘制分割线
{
pgfooter.linedraw = _footlinedraw;
pgfooter.linewidth = _footlinewidth;
pgfooter.linecolor = (color)printtool.strtocolor(_footlinecolor);
pgfooter.linedash = printtool.getdashstyle(_footlinedash);
}
// 页脚绘制
pgfooter.draw(g);
}
}
#endregion
#region 辅助方法
/// <summary>
/// 毫米 to 像素
/// </summary>
/// <param name="mmvalue">毫米值</param>
/// <returns></returns>
public static float mmtopixel(float mmvalue) //mmvalue是毫米,厘米=毫米
{
return (mmvalue / .f * f);
}
/// <summary>
/// 替换 当前页码、总共页数两个变量
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string replacepagenum(string str)
{
string retstr = "";
if (str == null || str.trim() == "")
return retstr;
retstr = str;
int t = ;
while (t >= )
{
t = retstr.indexof("[curpage]", stringcomparison.ordinalignorecase);
if (t >= )
{
retstr = retstr.substring(, t) + rptdraw.curpagenum.tostring() + retstr.substring(t + "[curpage]".length);
}
}
t = ;
while (t >= )
{
t = retstr.indexof("[allpage]", stringcomparison.ordinalignorecase);
if (t >= )
{
retstr = retstr.substring(, t) + rptdraw.allpagenum.tostring() + retstr.substring(t + "[allpage]".length);
}
}
return retstr;
}
/// <summary>
/// 解析xml文件
/// </summary>
/// <returns>返回成功与否</returns>
private bool parsexml()
{
if (this.dataxml == null || this.dataxml.trim() == "") return false;
xmldatadocument xmldoc = new xmldatadocument();
try
{
xmldoc.loadxml(this.dataxml);
xmlnode rootnode = xmldoc.documentelement;
if (rootnode.childnodes.count == ) return false;
if (rootnode.childnodes[].name.tolower() != "table") return false;
xmlnode tablenode = rootnode.childnodes[]; // 表格节点
htmlheight = float.parse(tablenode.attributes["height"].value);
htmlwidth = float.parse(tablenode.attributes["width"].value);
int tmrowindex = ;
foreach (xmlnode trnode in tablenode.childnodes)
{
if (trnode.name.tolower() != "tr") continue;
// 解析表格行
row tmrow = new row();
tmrow.rowindex = tmrowindex;
tmrow.rowheight = float.parse(trnode.attributes["height"].value);
tmrow.rowtype = trnode.attributes["rowtype"].value.tolower();
// 解析单元格
foreach (xmlnode tdnode in trnode.childnodes)
{
cell tmcell = new cell();
#region 合并\坐标\矩形
tmcell.rowspan = convert.toint(tdnode.attributes["rowspan"].value);
tmcell.colspan = convert.toint(tdnode.attributes["colspan"].value);
tmcell.rowindex = convert.toint(tdnode.attributes["r"].value);
tmcell.colindex = convert.toint(tdnode.attributes["c"].value);
tmcell.rectx = float.parse(tdnode.attributes["x"].value);
tmcell.recty = float.parse(tdnode.attributes["y"].value);
tmcell.rectw = float.parse(tdnode.attributes["w"].value);
tmcell.recth = float.parse(tdnode.attributes["h"].value);
#endregion
#region 设置单元格字体
fontstyle tmstyle = new fontstyle();
tmstyle = fontstyle.regular;
if (tdnode.attributes["italic"].value.tostring() == "") tmstyle |= fontstyle.italic;
if (tdnode.attributes["bold"].value.tostring() == "") tmstyle |= fontstyle.bold;
if (tdnode.attributes["strikeout"].value.tostring() == "") tmstyle |= fontstyle.strikeout;
if (tdnode.attributes["underline"].value.tostring() == "") tmstyle |= fontstyle.underline;
tmcell.cellfont = new font(tdnode.attributes["fontname"].value, float.parse(tdnode.attributes["fontsize"].value.replace("pt", "").replace("px", "")), tmstyle, graphicsunit.point);
tmcell.fontcolor = (color)printtool.strtocolor(tdnode.attributes["fontcolor"].value);
tmcell.backcolor = (color)printtool.strtocolor(tdnode.attributes["backcolor"].value);
stringformat tmformat = new stringformat();
switch (tdnode.attributes["align"].value.tolower()) // 水平对齐方式
{
case "center":
tmformat.alignment = stringalignment.center;
break;
case "right":
tmformat.alignment = stringalignment.far;
break;
default:
tmformat.alignment = stringalignment.near;
break;
}
switch (tdnode.attributes["valign"].value.tolower()) // 垂直对齐方式
{
case "middle":
tmformat.linealignment = stringalignment.center;
break;
case "bottom":
tmformat.linealignment = stringalignment.far;
break;
default:
tmformat.linealignment = stringalignment.near;
break;
}
tmcell.strformat = tmformat;
#endregion
#region 内嵌图片-属性
tmcell.isimage = tdnode.attributes["isimage"].value.tostring() == "" ? true : false;
if (tmcell.isimage)
tmcell.imageurl = tdnode.attributes["imageurl"].value;
#endregion
#region 单元格边框属性
// 左边框线
string tmval = tdnode.attributes["leftwidth"].value;
if (tmval.indexof("px") >= )
{
tmcell.leftborder = new borderline(
float.parse(tmval.replace("px", "")),
(color)printtool.strtocolor(tdnode.attributes["leftcolor"].value),
printtool.getdashstyle(tdnode.attributes["leftdash"].value)
);
}
// 上边框线
tmval = tdnode.attributes["topwidth"].value;
if (tmval.indexof("px") >= )
{
tmcell.topborder = new borderline(
float.parse(tmval.replace("px", "")),
(color)printtool.strtocolor(tdnode.attributes["topcolor"].value),
printtool.getdashstyle(tdnode.attributes["topdash"].value)
);
}
// 右边框线
tmval = tdnode.attributes["rightwidth"].value;
if (tmval.indexof("px") >= )
{
tmcell.rightborder = new borderline(
float.parse(tmval.replace("px", "")),
(color)printtool.strtocolor(tdnode.attributes["rightcolor"].value),
printtool.getdashstyle(tdnode.attributes["rightdash"].value)
);
}
// 下边框线
tmval = tdnode.attributes["bottomwidth"].value;
if (tmval.indexof("px") >= )
{
tmcell.bottomborder = new borderline(
float.parse(tmval.replace("px", "")),
(color)printtool.strtocolor(tdnode.attributes["bottomcolor"].value),
printtool.getdashstyle(tdnode.attributes["bottomdash"].value)
);
}
#endregion
#region 单据格数据数值
tmcell.value = tdnode.innertext;
#endregion
// 加入对应的行内
tmrow.rowcells.add(tmcell);
}
rptdraw.rowslist.add(tmrow);
tmrowindex++;
}
}
catch
{
return false;
}
finally
{
xmldoc = null;
}
return true;
}
/// <summary>
/// 计算报表区域矩形
/// 真实的绘制报表的区域
/// </summary>
private void calctablerect()
{
// 重新初始化实例
tablerect = new rectanglef();
// 左顶点 x坐标
tablerect.x = mmtopixel(_marginleft);
// 左顶点 y坐标
tablerect.y = mmtopixel(_margintop);
if (_headdraw) // 需要绘制页眉
tablerect.y += mmtopixel(_headheight);
// 报表矩形宽度高度
if (this.landscape) // 版型方向 横向
{
// 颠倒 宽高
tablerect.width = mmtopixel((float)_paperheight - _marginleft - _marginright);
tablerect.height = mmtopixel((float)_paperwidth - _margintop - _marginbottom);
}
else // 版型方向 纵向
{
tablerect.width = mmtopixel((float)_paperwidth - _marginleft - _marginright);
tablerect.height = mmtopixel((float)_paperheight - _margintop - _marginbottom);
}
// 报表矩形高度缩减
if (_headdraw) // 需要绘制页眉
tablerect.height -= mmtopixel(_headheight);
if (_footdraw) // 需要绘制页脚
tablerect.height -= mmtopixel(_footheight);
}
/// <summary>
/// 计算缩放比例
/// </summary>
private void calcreportzoom()
{
if (this.zoomtype.tolower() == "row")
{
if (convert.toint(tablerect.width) >= htmlwidth)
this.zoom = ;
else
this.zoom = tablerect.width / htmlwidth;
}
else if (this.zoomtype.tolower() == "col")
{
if (convert.toint(tablerect.height) >= htmlheight)
this.zoom = ;
else
this.zoom = tablerect.height / htmlheight;
}
else
{
this.zoom = ;
}
}
/// <summary>
/// 转换所有的尺寸
/// 根据缩放比例
/// </summary>
private void calczoomallsize()
{
if (this.zoom != )
{
// 转换html 高度宽度
htmlwidth = htmlwidth * zoom;
htmlheight = htmlheight * zoom;
// 转换所有行号
foreach (row zrow in this.rptdraw.rowslist)
{
// 行高缩小
zrow.rowheight = zrow.rowheight * zoom;
// 转换所有单元格 
foreach (cell zcell in zrow.rowcells)
{
zcell.rectx = zcell.rectx * zoom;
zcell.recty = zcell.recty * zoom;
zcell.rectw = zcell.rectw * zoom;
zcell.recth = zcell.recth * zoom;
zcell.topborder.linewidth = zcell.topborder.linewidth * zoom;
zcell.bottomborder.linewidth = zcell.bottomborder.linewidth * zoom;
zcell.leftborder.linewidth = zcell.leftborder.linewidth * zoom;
zcell.rightborder.linewidth = zcell.rightborder.linewidth * zoom;
// 字体相应缩小
zcell.cellfont = new font(zcell.cellfont.name, zcell.cellfont.size * zoom, zcell.cellfont.style, graphicsunit.point);
}
}
}
}
#endregion
}
}

2、reportdraw 打印绘制类

using system;
using system.collections.generic;
using system.drawing;
using system.drawing.drawingd;
using system.io;
namespace e_print
{
/// <summary>
/// 报表绘制
/// </summary>
public class reportdraw
{
#region 私有成员
/// <summary>
/// 当前页码
/// </summary>
private int _curpagenum;
/// <summary>
/// 总共页数
/// </summary>
private int _allpagenum;
/// <summary>
/// 表格矩形
/// </summary>
private rectanglef _reptrect;
/// <summary>
/// 报表全部行集
/// </summary>
private list<row> _rowslist;
/// <summary>
/// 分页页面数组
/// </summary>
private list<pagingitem> _pagelist;
/// <summary>
/// 是否每页打印标题
/// </summary>
private bool _isallprinttitle;
/// <summary>
/// 是否每页打印表头
/// </summary>
private bool _isallprinthead;
/// <summary>
/// 是否每页打印表尾
/// </summary>
private bool _isallprintfoot;
/// <summary>
/// 是否末页自动补行
/// </summary>
private bool _isautofillrow;
/// <summary>
/// 缩小比例
/// </summary>
private float _zoom;
/// <summary>
/// 字符溢出处理方式
/// </summary>
private bool _isoverflow;
/// <summary>
/// 每页打印的标题+表头的高度
/// </summary>
private float _headpix;
/// <summary>
/// 每页打印的表尾高度
/// </summary>
private float _footpix;
#endregion
#region 构造方法
/// <summary>
/// 构造函数
/// </summary>
public reportdraw()
{
_curpagenum = ;
_allpagenum = ;
_reptrect = new rectanglef();
_rowslist = new list<row>();
_pagelist = new list<pagingitem>();
_isallprinttitle = false;
_isallprinthead = false;
_isallprintfoot = false;
_isautofillrow = false;
_zoom = ;
_isoverflow = false;
_headpix = ;
_footpix = ;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="printtitle">每页打印标题</param>
/// <param name="printhead">每页打印表头</param>
/// <param name="printfoot">每页打印表位</param>
/// <param name="fillrows">自动补全空行</param>
/// <param name="tablerect">报表尺寸矩形</param>
/// <param name="overflow">字符溢出处理</param>
public reportdraw(bool printtitle, bool printhead, bool printfoot, bool fillrows, rectanglef tablerect, bool overflow)
{
_reptrect = tablerect;
_isallprinttitle = printtitle;
_isallprinthead = printhead;
_isallprintfoot = printfoot;
_isautofillrow = fillrows;
_isoverflow = overflow;
_curpagenum = ;
_allpagenum = ;
_zoom = ;
_rowslist = new list<row>();
_pagelist = new list<pagingitem>();
_headpix = ;
_footpix = ;
}
#endregion
#region 属性方法
/// <summary>
/// 获取--设置--当前页码
/// </summary>
public int curpagenum
{
get { return _curpagenum; }
set { _curpagenum = value; }
}
/// <summary>
/// 获取--设置--总共页数
/// </summary>
public int allpagenum
{
get { return _allpagenum; }
set { _allpagenum = value; }
}
/// <summary>
/// 获取--设置--表格矩形
/// </summary>
public rectanglef reptrect
{
get { return _reptrect; }
set { _reptrect = value; }
}
/// <summary>
/// 获取--设置--报表全部行集
/// </summary>
public list<row> rowslist
{
get { return _rowslist; }
set { _rowslist = value; }
}
/// <summary>
/// 获取--设置--分页页面数组
/// </summary>
public list<pagingitem> pagelist
{
get { return _pagelist; }
set { _pagelist = value; }
}
/// <summary>
/// 获取--设置--是否每页打印标题
/// </summary>
public bool isallprinttitle
{
get { return _isallprinttitle; }
set { _isallprinttitle = value; }
}
/// <summary>
/// 获取--设置--是否每页打印表头
/// </summary>
public bool isallprinthead
{
get { return _isallprinthead; }
set { _isallprinthead = value; }
}
/// <summary>
/// 获取--设置--是否每页打印表尾
/// </summary>
public bool isallprintfoot
{
get { return _isallprintfoot; }
set { _isallprintfoot = value; }
}
/// <summary>
/// 获取--设置--末页是否自动补行
/// </summary>
public bool isautofillrow
{
get { return _isautofillrow; }
set { _isautofillrow = value; }
}
/// <summary>
/// 获取--设置--缩小比例
/// </summary>
public float zoom
{
get { return _zoom; }
set { _zoom = value; }
}
/// <summary>
/// 获取--设置--字符溢出处理方式
/// </summary>
public bool isoverflow
{
get { return _isoverflow; }
set { _isoverflow = value; }
}
/// <summary>
/// 获取--设置--每页打印的标题+表头高度
/// </summary>
public float headpix
{
get { return _headpix; }
set { _headpix = value; }
}
/// <summary>
/// 获取--设置--每页打印的表尾高度
/// </summary>
public float footpix
{
get { return _footpix; }
set { _footpix = value; }
}
#endregion
#region 计算分页
/// <summary>
/// 计算分页
/// </summary>
public void calcpaging()
{
// 分页实例
pagingcalc inscalc = new pagingcalc();
inscalc.tablerect = this.reptrect;
inscalc.rowslist = this.rowslist;
inscalc.isallprinttitle = this.isallprinttitle;
inscalc.isallprinthead = this.isallprinthead;
inscalc.isallprintfoot = this.isallprintfoot;
// 分页计算
_pagelist = inscalc.calcpages();
this._allpagenum = _pagelist.count;
this._curpagenum = ;
this._headpix = inscalc.myheadpix;
this._footpix = inscalc.myfootpix;
}
#endregion
#region 绘制方法
/// <summary>
/// 绘制报表
/// </summary>
/// <param name="g"></param>
/// <returns>返回是否结束</returns>
public bool drawreport(graphics g)
{
bool ismorepage = false;
float offsetx = _reptrect.x; // x 偏移量
float offsety = _reptrect.y; // y 偏移量
bool iscanfillrow = false; // 是否需要补行
bool isfillflag = false; // 是否已经补过
int isfillrownum = ; // 需要补充几行
pagingitem nowpage = getpageitem(curpagenum); // 当前页
if (nowpage != null)
{
#region 判定高度不足是否自动补行
// 判定补行条件 报表设置了末页不足自动补行、同时 为最后一页
if (_isautofillrow == true && curpagenum == allpagenum)
{
// 判定页面高度 与 数据高度
float n_pageheith = reptrect.height; // 当前页面高度
float n_dataheith = getthispagedatarowsheight(); // 当前数据高度
// 补行行高
while ((n_dataheith + (isfillrownum + ) * * zoom) < n_pageheith)
{
isfillrownum++;
}
if (isfillrownum > )
iscanfillrow = true;
}
#endregion
#region 首先绘制上一页补充单元格
if (curpagenum > )
{
pagingitem prepage = getpageitem(curpagenum - ); // 上一页
if (prepage != null)
{
foreach (pagingmakeup tmmk in prepage.makeuplist)
{
// 绘制补充单元格(上页中未绘制完成的单元格)
drawtd(g, tmmk.makeupcell, offsetx, offsety, true, tmmk.makeupheight, false);
}
}
}
#endregion
#region 其次绘制当前页面的单元格
// 其次绘制当前页的单元格
for (int ii = ; ii < nowpage.indexlist.count; ii++)
{
// 先绘制 td cell 单元格
row rowtr = getrow(nowpage.indexlist[ii]);
#region 执行补行
if (iscanfillrow == true && rowtr.rowtype.tolower().trim() == "f") // 需要补行 行标志为f 表尾前进行补充空行
{
row fillrow = new row();
if (ii == )
fillrow = rowtr;
else
fillrow = getrow(nowpage.indexlist[ii - ]);
if (fillrow != null) // 绘制自动补充的空行单元格
{
// 开始补充空行 
for (int fi = ; fi <= isfillrownum; fi++)
{
bool bcflag = true;
// 绘制单元格
foreach (cell filltdcell in fillrow.rowcells)
{
if (bcflag)
{
// 绘制边框线(合并单元格的情况才用到)
if (filltdcell.rectx > )
{
drawline(g, offsetx, offsety, offsetx, offsety + .f * zoom); // 最左边竖线
drawline(g, offsetx, offsety + .f * zoom, offsetx + filltdcell.rectx, offsety + .f * zoom);
}
bcflag = false;
}
drawtd(g, filltdcell, offsetx, offsety, false, , true);
}
// 再将偏移量+行号 补充的行高全部为px
offsety += * zoom;
}
}
isfillflag = true;
}
#endregion
#region 正常绘制
foreach (cell td in rowtr.rowcells)
{
drawtd(g, td, offsetx, offsety, false, , false);
}
// 再将偏移量+行号
offsety += rowtr.rowheight;
#endregion
}
// 判定是否补过;没有补充过,则在最后进行补充空行
if ((iscanfillrow == true) && (isfillflag == false) && (nowpage.indexlist.count > ))
{
row fillrow = getrow(nowpage.indexlist[nowpage.indexlist.count - ]);
if (fillrow != null) // 绘制自动补充的空行单元格
{
// 开始补充空行
for (int fi = ; fi <= isfillrownum; fi++)
{
bool newflag = true;
foreach (cell filltdcell in fillrow.rowcells)
{
if (newflag)
{
// 绘制边框线(合并单元格的情况才用到)
if (filltdcell.rectx > )
{
drawline(g, offsetx, offsety, offsetx, offsety + .f * zoom); // 最左边竖线
drawline(g, offsetx, offsety + .f * zoom, offsetx + filltdcell.rectx, offsety + .f * zoom);
}
newflag = false;
}
drawtd(g, filltdcell, offsetx, offsety, false, , true);
}
offsety += * zoom; // 再将偏移量+行号 补充的行高全部为px
}
}
}
#endregion
if (curpagenum < allpagenum)
{
ismorepage = true; // 还有下页
curpagenum++; // 页码增加
}
}
return ismorepage;
}
/// <summary>
/// 绘制单元格
/// </summary>
/// <param name="g">绘图对象</param>
/// <param name="tdcell">单元格</param>
/// <param name="setx">x偏移量</param>
/// <param name="sety">y坐标值</param>
/// <param name="ismakeup">是否补充单元格</param>
/// <param name="mkh">补充单元格高度</param>
/// <param name="fillcell">自动补行的单元格</param>
private void drawtd(graphics g, cell tdcell, float setx, float sety, bool ismakeup, float mkh, bool fillcell)
{
#region 参数变量
pen pen;
brush brush;
// 获取单元格绘制坐标矩形信息
float tdx = tdcell.rectx + setx;
float tdy = sety;
float tdw = tdcell.rectw;
float tdh = ;
if (fillcell)
{
tdh = * zoom; // 自动补行的单元格的高度固定为px
}
else
{
if (ismakeup) // 补充单元格
{
tdh = mkh;
tdy = tdy + headpix; // 如果是补充单元格,则此单元格的y坐标:如果每页打印标题或表头,则y坐标 需要下移 headpix
}
else // 实际单元格
{
tdh = tdcell.recth;
}
if (tdcell.rowspan > ) // 判定单元格高度是否超过底线
{
tdh = calc_celloverheight(tdcell, tdy, tdh);
}
}
#endregion
#region 绘制背景
// 填充颜色
brush = new solidbrush(tdcell.backcolor);
g.fillrectangle(brush, tdx + .f * zoom, tdy + .f * zoom, tdw - .f * zoom, tdh - .f * zoom);
#endregion
#region 绘制边框
// 左边框线
if (tdcell.leftborder.linewidth > )
{
pen = new pen(tdcell.leftborder.linecolor);
pen.dashstyle = tdcell.leftborder.linedash;
pen.width = tdcell.leftborder.linewidth;
g.drawline(pen, tdx, tdy, tdx, tdy + tdh);
}
// 上边框线
if (tdcell.topborder.linewidth > )
{
pen = new pen(tdcell.topborder.linecolor);
pen.dashstyle = tdcell.topborder.linedash;
pen.width = tdcell.topborder.linewidth;
g.drawline(pen, tdx, tdy, tdx + tdw, tdy);
}
// 右边框线
if (tdcell.rightborder.linewidth > )
{
pen = new pen(tdcell.rightborder.linecolor);
pen.dashstyle = tdcell.rightborder.linedash;
pen.width = tdcell.rightborder.linewidth;
g.drawline(pen, tdx + tdw, tdy, tdx + tdw, tdy + tdh);
}
// 下边框线
if (tdcell.bottomborder.linewidth > )
{
pen = new pen(tdcell.bottomborder.linecolor);
pen.dashstyle = tdcell.bottomborder.linedash;
pen.width = tdcell.bottomborder.linewidth;
g.drawline(pen, tdx, tdy + tdh, tdx + tdw, tdy + tdh);
}
#endregion
#region 绘制文字
if (!fillcell)
{
rectanglef rect = new rectanglef(tdx, tdy, tdw, tdh);
if (tdcell.isimage)
{
this.drawimg(g, rect, tdcell.imageurl);
}
else
{
brush = new solidbrush(tdcell.fontcolor);
this.drawstr(g, rect, brush, tdcell.cellfont, tdcell.strformat, tdcell.value);
}
}
#endregion
}
/// <summary>
/// 绘制字符串
/// 溢出时,换行缩小字符
/// 字体缩小到的最小值不得小于
/// </summary>
/// <param name="g">绘图对象</param>
/// <param name="strrect">文本区域</param>
/// <param name="strbrush">文本笔画</param>
/// <param name="strfont">文本字体</param>
/// <param name="strformat">文本格式</param>
/// <param name="strvalue">文本字符</param>
/// <returns></returns>
private void drawstr(graphics g, rectanglef strrect, brush strbrush, font strfont, stringformat strformat, string strvalue)
{
// 报表设置:字符溢出不做处理
if (!this.isoverflow)
{
g.drawstring(strvalue, strfont, strbrush, strrect, strformat);
}
else // 需要处理
{
// 测量字体的宽度和高度 会发现误差很大,如果一个一个的测量,误差就实在太大,所以这里就用简单的方式来进行处理
sizef sf = g.measurestring(strvalue, strfont); // 此种方式测量误差很大,如果
if (strrect.width > sf.width)
{
g.drawstring(strvalue, strfont, strbrush, strrect, strformat);
}
else
{
// 计算换行后字符的全部高度是否满足
int maxlines = ; // 计算当前字符当前字体最大打印的行数
maxlines = (int)math.ceiling((double)sf.width / (double)strrect.width);
if (strrect.height >= maxlines * sf.height)
{
g.drawstring(strvalue, strfont, strbrush, strrect, strformat);
}
else
{
float tmscale = strrect.height / (maxlines * sf.height);
font tmnewfont = new font(strfont.name, strfont.size * tmscale, strfont.style, graphicsunit.point);
g.drawstring(strvalue, tmnewfont, strbrush, strrect, strformat);
}
}
}
}
/// <summary>
/// 绘制图片
/// 将base图片流字符串转换成图片并进行绘制
/// </summary>
/// <param name="g"></param>
/// <param name="strrect"></param>
/// <param name="baseimg"></param>
private void drawimg(graphics g, rectanglef strrect, string baseimg)
{
if (baseimg.trim() == "") return;
string imgstr = baseimg.replace("data:image/gif;base,", "").trim();
if (imgstr == "") return;
// 生成图片
try
{
memorystream stream = new memorystream(convert.frombasestring(imgstr));
bitmap picimg = new bitmap(stream);
rectanglef imgrectf = new rectanglef(f, f, (float)picimg.width, (float)picimg.height); // 原始图片矩形
rectanglef newrectf = new rectanglef(strrect.x + f, strrect.y + f, (float)strrect.width - f, (float)strrect.height - f); // 绘制图片矩形
g.drawimage(picimg, newrectf, imgrectf, graphicsunit.pixel); // 绘制缩放图片
stream.close();
}
catch
{
return;
}
}
/// <summary>
/// 绘制线条
/// </summary>
/// <param name="g">绘图对象</param>
/// <param name="start_x">开始x</param>
/// <param name="start_y">开始y</param>
/// <param name="end_x">结束x</param>
/// <param name="end_y">结束y</param>
private void drawline(graphics g, float start_x, float start_y, float end_x, float end_y)
{
pen linepen = new pen(color.black, .f);
linepen.dashstyle = dashstyle.solid;
g.drawline(linepen, start_x, start_y, end_x, end_y);
}
private float changeunit(float vsize)
{
return (vsize * f / f * f / f);
}
/// <summary>
/// 获取行对象
/// </summary>
/// <param name="rowindex"></param>
/// <returns></returns>
private row getrow(int rowindex)
{
foreach (row retrow in _rowslist)
{
if (retrow.rowindex == rowindex)
return retrow;
}
return null;
}
/// <summary>
/// 获取分页页面
/// </summary>
/// <param name="pno">页码</param>
/// <returns></returns>
private pagingitem getpageitem(int pno)
{
foreach (pagingitem retpitem in pagelist)
{
if (retpitem.pagenum == pno)
return retpitem;
}
return null;
}
/// <summary>
/// 计算绘制高度
/// 判定并且计算单元格高度是否超过当前页面所有行高度的底线
/// </summary>
/// <param name="mcell">单元格</param>
/// <param name="my">y 轴坐标值</param>
/// <param name="mh">h 当前高度</param>
/// <returns></returns>
private float calc_celloverheight(cell mcell, float my, float mh)
{
float returnheight = ; // 返回高度
float tm_alltrheight = getthispagedatarowsheight(); // 当前页面内所有数据行的高度
float tm_realy = ; // 相对最大y值
float tm_absy = ; // 实际最大y值
float tm_overplus = ; // 单元格剩余高度
tm_realy = my + mh; // 实际最大y值
if (isallprintfoot) // 每页打印表尾
tm_absy = reptrect.y + (tm_alltrheight - footpix); // 需要减去表尾高度
else
tm_absy = tm_alltrheight + reptrect.y;
if (tm_realy > tm_absy)
{
returnheight = tm_absy - my; // 当前页面实际最大高度-单元格的当前y坐标值 = 返回单元格在本页内需要绘制的高度
tm_overplus = mh - returnheight; // 当前高度-单元格当前页面需要绘制的高度=下页需要绘制的补充高度
// 将当前单元格添加到后页需要补充绘制数组中去
pagingitem npageitem = getpageitem(curpagenum);
pagingmakeup nmakeup = new pagingmakeup();
nmakeup.makeupcell = mcell;
nmakeup.makeupheight = tm_overplus;
npageitem.makeuplist.add(nmakeup);
}
else
{
returnheight = mh;
}
return returnheight;
}
/// <summary>
/// 获取本页内所有数据行的高度
/// </summary>
/// <returns></returns>
private float getthispagedatarowsheight()
{
float retheight = ;
pagingitem othispage = getpageitem(curpagenum); // 当前页
foreach (int orowindex in othispage.indexlist)
{
row othisrow = getrow(orowindex);
retheight += othisrow.rowheight;
}
return retheight;
}
/// <summary>
/// 获取页内某一项所属行的高度
/// </summary>
/// <param name="itempage">页面对象</param>
/// <param name="itemindex">本页行数组中的某一项的序号</param>
/// <returns></returns>
private float getthispageonerowheight(pagingitem itempage, int itemindex)
{
float retheight = ;
if (itemindex < itempage.indexlist.count && itemindex >= )
{
row othisrow = getrow(itempage.indexlist[itemindex]);
retheight = othisrow.rowheight;
}
return retheight;
}
#endregion
}
} 

3、pagingcalc 分页计算类

using system;
using system.collections.generic;
using system.text;
using system.drawing;
namespace e_print
{
/// <summary>
/// 分页计算
/// </summary>
public class pagingcalc
{
#region 私有变量
/// <summary>
/// 表格区域
/// </summary>
private rectanglef _tablerect;
/// <summary>
/// 报表行集
/// </summary>
private list<row> _rowslist;
/// <summary>
/// 是否每页打印标题
/// </summary>
private bool _isallprinttitle;
/// <summary>
/// 是否每页打印表头
/// </summary>
private bool _isallprinthead;
/// <summary>
/// 是否每页打印表尾
/// </summary>
private bool _isallprintfoot;
/// <summary>
/// 标题行集
/// </summary>
private list<row> titlelist;
/// <summary>
/// 表头前行集
/// </summary>
private list<row> hforelist;
/// <summary>
/// 表头行集
/// </summary>
private list<row> headlist;
/// <summary>
/// 数据行集
/// </summary>
private list<row> datalist;
/// <summary>
/// 表尾行集
/// </summary>
private list<row> footlist;
/// <summary>
/// 每页打印标题+表头高度
/// </summary>
private float _myheadpix;
/// <summary>
/// 每页打印表尾高度
/// </summary>
private float _myfootpix;
#endregion
#region 构造方法
/// <summary>
/// 构造函数
/// </summary>
public pagingcalc()
{
_tablerect = new rectanglef();
_rowslist = new list<row>();
_isallprinttitle = false;
_isallprinthead = false;
_isallprintfoot = false;
titlelist = new list<row>();
hforelist = new list<row>();
headlist = new list<row>();
datalist = new list<row>();
footlist = new list<row>();
_myheadpix = ;
_myfootpix = ;
}
#endregion
#region 属性方法
/// <summary>
/// 获取--设置--表格区域
/// </summary>
public rectanglef tablerect
{
get { return _tablerect; }
set { _tablerect = value; }
}
/// <summary>
/// 获取--设置--表格行集
/// </summary>
public list<row> rowslist
{
get { return _rowslist; }
set { _rowslist = value; }
}
/// <summary>
/// 获取--设置--是否每页打印标题
/// </summary>
public bool isallprinttitle
{
get { return _isallprinttitle; }
set { _isallprinttitle = value; }
}
/// <summary>
/// 获取--设置--是否每页打印表头
/// </summary>
public bool isallprinthead
{
get { return _isallprinthead; }
set { _isallprinthead = value; }
}
/// <summary>
/// 获取--设置--是否每页打印表尾
/// </summary>
public bool isallprintfoot
{
get { return _isallprintfoot; }
set { _isallprintfoot = value; }
}
/// <summary>
/// 获取--设置--每页打印标题+表头高度
/// </summary>
public float myheadpix
{
get { return _myheadpix; }
set { _myheadpix = value; }
}
/// <summary>
/// 获取--设置--每页打印表尾巴高度
/// </summary>
public float myfootpix
{
get { return _myfootpix; }
set { _myfootpix = value; }
}
#endregion
#region 计算方法
/// <summary>
/// 分页计算
/// </summary>
/// <returns></returns>
public list<pagingitem> calcpages()
{
list<pagingitem> retpages = new list<pagingitem>();
// 无需分页
if (get_tableallheight() <= tablerect.height)
{
pagingitem tmitem = new pagingitem();
tmitem.pagenum = ;
for (int y = ; y < rowslist.count; y++)
{
tmitem.indexlist.add(y);
}
retpages.add(tmitem);
}
else // 需要分页
{
// 有设置了 每页打印标题、表头、表位 其中的任意一个
if (get_iscusset_thdf()) // 则执行每页相对分页
{
paging_relative(, ref retpages);
// 计算每页打印头尾高度
myheadpix = ;
if (isallprinttitle)
{
myheadpix += get_tabletileheight();
}
if (isallprinthead)
{
myheadpix += get_tableheadheight();
}
if (isallprintfoot)
{
myfootpix = get_tablefootheight();
}
}
else // 执行直接数据分页
{
paging_direct(, ref retpages);
}
}
return retpages;
}
/// <summary>
/// 直接分页
/// </summary>
/// <param name="startr">开始行号</param>
/// <param name="pages">页面数组</param>
private void paging_direct(int startr, ref list<pagingitem> pages)
{
float p_height = tablerect.height;
pagingitem p_item = new pagingitem();
p_item.pagenum = pages.count + ;
for (int t = startr; t < rowslist.count; t++)
{
// 检查行内单元格是否不允许分页两种情况:条形码,图片
if (paging_checkcell(rowslist[t], p_height))
{
startr = t;
pages.add(p_item);
paging_direct(startr, ref pages);
break;
}
else
{
p_height -= rowslist[t].rowheight;
if (p_height <= )
{
startr = t;
pages.add(p_item);
paging_direct(startr, ref pages);
break;
}
else
{
p_item.indexlist.add(t);
if (t == rowslist.count - )
{
pages.add(p_item);
}
}
}
}
}
/// <summary>
/// 相对分页
/// </summary>
/// <param name="startr">开始序号</param>
/// <param name="pages">页面数组</param>
private void paging_relative(int startr, ref list<pagingitem> pages)
{
splitreportarea(); // 拆分表行
float p_height = tablerect.height; // 页面总高
pagingitem p_item = new pagingitem(); // 分页页面
p_item.pagenum = pages.count + ; // 分页页码
bool runnext = false; // 继续分页
#region 每页打印标题
// 每页打印标题
if (isallprinttitle)
{
p_height -= get_tabletileheight();
foreach (row p_row in titlelist)
p_item.indexlist.add(p_row.rowindex);
}
else
{
if (p_item.pagenum == ) // 第一页特殊处理
{
p_height -= get_tabletileheight();
foreach (row p_row in titlelist)
p_item.indexlist.add(p_row.rowindex);
}
}
#endregion
#region 每页打印表头
// 每页打印表头
if (isallprinthead)
{
if (p_item.pagenum == ) // 第一页特殊处理
{
// 计算表头前的行高
p_height -= get_tablehforheight();
foreach (row p_row in hforelist)
p_item.indexlist.add(p_row.rowindex);
}
// 计算表头行的高度
p_height -= get_tableheadheight();
foreach (row p_row in headlist)
p_item.indexlist.add(p_row.rowindex);
}
else
{
if (p_item.pagenum == ) // 第一页特殊处理
{
// 计算表头前的行高
p_height -= get_tablehforheight();
foreach (row p_row in hforelist)
p_item.indexlist.add(p_row.rowindex);
// 计算表头行的高度
p_height -= get_tableheadheight();
foreach (row p_row in headlist)
p_item.indexlist.add(p_row.rowindex);
}
}
#endregion
#region 每页数据区域
// 每页数据划分
if (isallprintfoot)
{
p_height -= get_tablefootheight(); // 表格高度 先减去表尾的高度
}
for (int t = startr; t < datalist.count; t++)
{
// 检查行内单元格是否不允许分页两种情况:条形码,图片
if (paging_checkcell(datalist[t], p_height)) // 此情况下,单元格不能分割,并且高度超过页面剩余高度,所以要启动新的一页
{
startr = t;
runnext = true;
break;
}
else
{
p_height -= datalist[t].rowheight;
if (p_height <= )
{
startr = t;
runnext = true;
break;
}
else
{
p_item.indexlist.add(datalist[t].rowindex);
}
}
}
#endregion
#region 每页打印表尾
// 每页打印表尾
if (isallprintfoot)
{
foreach (row p_row in footlist)
p_item.indexlist.add(p_row.rowindex);
}
#endregion
#region 添加分页页面
pages.add(p_item);
if (runnext)
{
paging_relative(startr, ref pages);
}
#endregion
}
/// <summary>
/// 检查行内单元格如果是图片
/// 并且合并行数大于
/// </summary>
/// <param name="crow"></param>
/// <param name="cheight"></param>
/// <returns></returns>
private bool paging_checkcell(row crow, float cheight)
{
foreach (cell ccell in crow.rowcells)
{
if (ccell.isimage == true)
{
if (ccell.recth > cheight)
return true;
}
}
return false;
}
#endregion
#region 辅助方法
/// <summary>
/// 获取--报表全部高度
/// </summary>
/// <returns></returns>
private float get_tableallheight()
{
float rethight = ;
for (int k = ; k < rowslist.count; k++)
{
row t_row = rowslist[k];
rethight += t_row.rowheight;
}
return rethight;
}
/// <summary>
/// 获取是否设置了标题、表头、表尾 中的任意一个
/// </summary>
/// <returns></returns>
private bool get_iscusset_thdf()
{
string tmtype = "";
foreach (row cusrow in this.rowslist)
{
tmtype = cusrow.rowtype.tolower().trim();
if (tmtype == "t" || tmtype == "h" || tmtype == "f")
return true;
}
return false;
}
/// <summary>
/// 获取--报表标题高度
/// </summary>
/// <returns></returns>
private float get_tabletileheight()
{
float rethight = ;
for (int k = ; k < titlelist.count; k++)
rethight += titlelist[k].rowheight;
return rethight;
}
/// <summary>
/// 获取--报表表头前高度
/// </summary>
/// <returns></returns>
private float get_tablehforheight()
{
float rethight = ;
for (int k = ; k < hforelist.count; k++)
rethight += hforelist[k].rowheight;
return rethight;
}
/// <summary>
/// 获取--报表表头高度
/// </summary>
/// <returns></returns>
private float get_tableheadheight()
{
float rethight = ;
for (int k = ; k < headlist.count; k++)
rethight += headlist[k].rowheight;
return rethight;
}
/// <summary>
/// 获取--报表表尾高度
/// </summary>
/// <returns></returns>
private float get_tablefootheight()
{
float rethight = ;
for (int k = ; k < footlist.count; k++)
rethight += footlist[k].rowheight;
return rethight;
}
/// <summary>
/// 拆分报表区域
/// </summary>
public void splitreportarea()
{
titlelist = new list<row>();
hforelist = new list<row>();
headlist = new list<row>();
datalist = new list<row>();
footlist = new list<row>();
for (int m = ; m < rowslist.count; m++)
{
row mmrow = rowslist[m];
switch (mmrow.rowtype.tolower())
{
case "t": // 标题
titlelist.add(mmrow);
break;
case "h": // 表头
headlist.add(mmrow);
break;
case "f": // 表尾
footlist.add(mmrow);
break;
case "d": // 数据
default:
datalist.add(mmrow);
break;
}
}
// 设置表头前行集
if (titlelist.count == && headlist.count > )
{
list<row> tmplist = new list<row>();
for (int n = ; n < datalist.count; n++)
{
if (datalist[n].rowindex < headlist[].rowindex)
{
hforelist.add(datalist[n]);
tmplist.add(datalist[n]);
}
}
for (int n = ; n < tmplist.count; n++)
{
datalist.remove(tmplist[n]);
}
tmplist.clear();
}
// 重设表尾 不是每页打印表尾情况下,那么表位就去掉
if (!isallprintfoot)
{
foreach (row trow in footlist)
datalist.add(trow);
footlist.clear();
}
}
#endregion
}
} 

4、pagingmakeup 分页补充绘制类

using system;
using system.collections.generic;
using system.text;
namespace e_print
{
/// <summary>
/// 下页需要补充绘制
/// </summary>
public class pagingmakeup
{
/// <summary>
/// 补充单元格
/// </summary>
private cell _makeupcell;
/// <summary>
/// 补充高度
/// </summary>
private float _makeupheight;
/// <summary>
/// 构造函数
/// </summary>
public pagingmakeup()
{
_makeupcell = new cell();
_makeupheight = ;
}
/// <summary>
/// 获取--设置--补充单元格
/// </summary>
public cell makeupcell
{
get { return _makeupcell; }
set { _makeupcell = value; }
}
/// <summary>
/// 获取--设置--补充高度
/// </summary>
public float makeupheight
{
get { return _makeupheight; }
set { _makeupheight = value; }
}
}
} 

5、iobjectsafety 抽象接口类

using system;
using system.collections.generic;
using system.text;
using system.runtime.interopservices;
namespace e_print
{
/// <summary>
/// 接口抽象基类
/// </summary>
[comimport, guidattribute("cbbdc-c-cf-f-fcd")]
[interfacetypeattribute(cominterfacetype.interfaceisiunknown)]
public interface iobjectsafety
{
[preservesig]
int getinterfacesafetyoptions(ref guid riid, [marshalas(unmanagedtype.u)] ref int pdwsupportedoptions, [marshalas(unmanagedtype.u)] ref int pdwenabledoptions);
[preservesig()]
int setinterfacesafetyoptions(ref guid riid, [marshalas(unmanagedtype.u)] int dwoptionsetmask, [marshalas(unmanagedtype.u)] int dwenabledoptions);
}
} 

6、预览效果

网页WEB打印控件制作

7、我们可以通过源码中的 eprinttest.exe 打印winform 实例 ,来执行示范,

通过web前端js 生成打印的table的 rptdata.xml格式 数据,在winform中直接使用

如果在网页中,通过js 直接传给打印控件就ok