winfrom 打印表格 字符串的封装实现代码 附源码下载
所以对于应用层用着还不是很方便。最近做一个项目顺便就封装了一个调用默认打印机的类。虽说有几个小bug,但对于目前来说,已经满足需求了。以后不够了在来升级吧。
1,关于打印上下左右边距和纸张的高宽。以往都把这些写死到代码里面。既然是调用默认打印机,打印机的型号自然有差异。所以我就把这些配置放到app.config里面。但又怕每次打印都加载config影响效率。故此设计了个printpaper类。里面所有属性都是静态的。还有一个静态的构造方法。这样只有在程序开始运行加载一次config。之后就直接从内存读取了。
printpaper类
/*createby:bonker,date:20121115*/
/// <summary>
/// 从配置文件读取纸张的大小,与边框的距离
/// </summary>
public class printpaper
{
/// <summary>
/// 距离上边界的距离
/// </summary>
public static int margintop { set; get; }
/// <summary>
/// 距离左边界的距离
/// </summary>
public static int marginleft { set; get; }
/// <summary>
/// 距离右边界的距离
/// </summary>
public static int marginright { set; get; }
/// <summary>
/// 距离下边界的距离
/// </summary>
public static int marginbottom { set; get; }
/// <summary>
/// 纸张的宽度
/// </summary>
public static int width { set; get; }
/// <summary>
/// 纸张的高度
/// </summary>
public static int height { set; get; }
/// <summary>
/// 异常情况
/// </summary>
public static string error { set; get; }
//对于静态属性和构造方法。当第一次使用该类的时候,先初始化静态属性,然后调用静态类。
//故此配置文件只加载一次,以后调用都会从内存中读取。
//此中写法的好处,一次加载,以后不再加载,速度快。弊端:程序运行过程中,改变了config配置。则需重新运行程序。配置才加载生效。
static printpaper()
{
//先给异常赋空值,当异常不为空时。说明配置数据有问题,或者程序有异常
error = null;
string margintop = bonkerconfig.getconfig("margintop");
string marginbottom = bonkerconfig.getconfig("marginbottom");
string marginleft = bonkerconfig.getconfig("marginleft");
string marginright = bonkerconfig.getconfig("marginright");
//margin的值可以为负值,但是width只能为正,
//margintop,等值默认已经为0,如果margin不为空,取值复制给margin
try
{
if (!string.isnullorwhitespace(margintop))
{
margintop = int.parse(margintop);
}
if (!string.isnullorwhitespace(margintop))
{
marginbottom = int.parse(marginbottom);
}
if (!string.isnullorwhitespace(margintop))
{
marginleft = int.parse(marginleft);
}
if (!string.isnullorwhitespace(margintop))
{
marginright = int.parse(marginright);
}
}
catch (exception ex)
{
//如果有异常继续
error = ex.message;
return;
}
//判断纸张宽度
try
{
//如果paperwidth配置不为正,则为printcore类打印的时候,则去默认值
string width = bonkerconfig.getconfig("paperwidth");
string height = bonkerconfig.getconfig("paperwidth");
if (!string.isnullorwhitespace(width))
{
width = int.parse(width);
}
if (!string.isnullorwhitespace(height))
{
height = int.parse(width);
}
}
catch (exception ex)
{
//如果有异常继续
error = ex.message;
return;
}
}
}
app.config的内容
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appsettings>
<!--******************************连接字符串设置************************************-->
<add key="dbconnectionstr" value=" "/>
<!--********************************打印边界设置**********************************-->
<!--打印纸的距四个边界的距离,为空这表示默认为0,可以为负值-->
<!--与上边界距离-->
<add key="margintop" value=""/>
<!--与上边界距离-->
<add key="marginbottom" value=""/>
<!--与上边界距离-->
<add key="marginleft" value=""/>
<!--与上边界距离-->
<add key="marginright" value=""/>
<!--********************************打印纸大小设置**********************************-->
<!--打印纸张的大小,为空表示取默认值,不可以为负值 -->
<!--纸张的宽度-->
<add key="paperwidth" value=""/>
<!--纸张的高度-->
<add key="paperheight" value=""/>
<!--*******************************************************************************-->
</appsettings>
</configuration>
2,打印表格,翻阅了很多msdn大神的代码。大致有点眉目。打印表格是在一点打印完字体后,然后不改变x,y坐标继续打印个矩形。所以就有表格了。这样的表格理论上表格的四个边框有点细。里面的小格子有点粗。但打印出来后基本就没差别了。
打印表格是自适应表格里面的文字最大的宽度。但如果表格里面确实列很少,没列的最大宽度又很小。打印完真整个表格没有页面的纸张宽。那会自动拉宽每一列的宽度。
打印的核心类printcore
/*createby:bonker,date:20121115*/
/// <summary>
/// 打印类,负责打印表格,普通行等。
/// </summary>
public class printcore
{
/// <summary>
/// 打印基础封装类printdocument
/// </summary>
public printdocument printdoc { set; get; }
/// <summary>
/// 当前打印的x坐标
/// </summary>
public float currentx { set; get; }
/// <summary>
/// 当前打印的y坐标
/// </summary>
public float currenty { set; get; }
/// <summary>
/// 默认打印字体
/// </summary>
public font defaultfont { set; get; }
/// <summary>
/// 打印的画刷,默认黑色加粗
/// </summary>
public brush defaultbrush { set; get; }
/// <summary>
/// 是否居中打印,默认为false
/// </summary>
public bool iscenter { set; get; }
/// <summary>
/// 异常错误
/// </summary>
public string error { set; get; }
private graphics graphic { set; get; }
/// 构造函数
/// </summary>
/// <param name="_printdoc">打印基础类</param>
/// <param name="_currentx">打印开始的x坐标,默认为0</param>
/// <param name="_currenty">打印开始的y坐标,默认为0</param>
public printcore(printdocument _printdoc, graphics _graphics, font _defaultfont, float _currentx = 0, float _currenty = 0)
{
this.printdoc = _printdoc;
this.currentx = _currentx;
this.currenty = _currenty;
this.defaultfont = _defaultfont;
this.graphic = _graphics;
this.defaultbrush = new solidbrush(color.black); //默认加粗黑色
this.iscenter = false;
//读取配置文件
printdocconfig(_printdoc);
error = printpaper.error;
}
private void printdocconfig(printdocument _printdoc)
{
_printdoc.defaultpagesettings.margins = new margins(printpaper.marginleft, printpaper.marginright, printpaper.margintop, printpaper.marginbottom);
//当paper配置的宽度和高度都大于0时,才配置。否则忽略
if (printpaper.width > 0 && printpaper.height > 0)
{
_printdoc.defaultpagesettings.papersize = new papersize("", printpaper.width, printpaper.height);
}
}
/// <summary>
/// 打印字符串,系统可以总动判断换行打印。
/// </summary>
/// <param name="prnstr">打印的字符串</param>
/// <param name="isprintline">打印完成后,是否换行,默认为true</param>
public void printstring(string prnstr, bool isprintline = true)
{
//打印字符串,根据字符串长度,和纸张宽度,高度等自动换行
sizef measure = graphic.measurestring(prnstr, defaultfont);
//如果x坐标不为0,或者打印的一行宽度大于纸张的宽度,则居中打印是没用的。不考虑打印
if (!iscenter || currentx != 0 || printdoc.defaultpagesettings.papersize.width < measure.width)
{
//计算打印这么多字要多少行
int rows = (int)math.ceiling(measure.width / (printdoc.defaultpagesettings.papersize.width - currentx));
//根据行,算出要打印的边界矩形框
graphic.drawstring(prnstr, defaultfont, defaultbrush, new rectangle((int)currentx, (int)currenty, (int)math.ceiling((printdoc.defaultpagesettings.papersize.width - currentx)), (int)math.ceiling((measure.height * rows))));
if (isprintline)//如果换行
{
currenty = currenty + measure.height * rows;
currentx = 0;
}
else
{
currenty = currenty + measure.height * (rows - 1);
currentx = (measure.width % (printdoc.defaultpagesettings.papersize.width - currentx)) + currentx;
}
}
else
{
//居中打印一行
//计算打印前的留白宽度
float blank = (printdoc.defaultpagesettings.papersize.width - measure.width) / 2.0f;
currentx = currentx + blank;
graphic.drawstring(prnstr, defaultfont, defaultbrush, currentx, currenty);
if (isprintline)//如果换行
{
currentx = 0;
currenty = currenty + measure.height;
}
else
{
currentx = currentx + measure.width;
}
}
}
/// <summary>
/// 打印表格,自适应没列的宽度
/// </summary>
/// <param name="prndgv"></param>
/// <param name="isprintline"></param>
public void printdatagridview(datagridview prndgv, font titlefont, brush titlebrush, color titlebackgroup, bool isprintline = true)
{
if (prndgv == null)
{
return;
}
prndgv.allowusertoaddrows = false;
//记录每一列的宽度
int[] columnwidths = new int[prndgv.columncount];
//******************取每列的最大宽度***********************
//先计算表头的宽度
for (int i = 0; i < prndgv.columncount; i++)
{
string celvalue = prndgv.columns[i].headertext;
sizef measure = graphic.measurestring(celvalue, titlefont);
columnwidths[i] = (int)math.ceiling(measure.width);//把打印表头所占的宽度 先放到columnwidths里面
}
//计算表中数据打印的最大宽度
for (int i = 0; i < prndgv.rows.count; i++)
{
for (int j = 0; j < prndgv.columncount; j++)
{
string celvalue = prndgv[j, i].value.tostring();
sizef measure = graphic.measurestring(celvalue, defaultfont);
if (columnwidths[j] < measure.width)//如果宽度小于打印宽度,则把长的打印宽度赋值给列宽
{
columnwidths[j] = (int)math.ceiling(measure.width);
}
}
}
//如果表格的宽度小于纸张的宽度,表格没列的宽度加大
int allcolumswidth = 0;
for (int i = 0; i < prndgv.columncount; i++)
{
allcolumswidth += columnwidths[i];//把打印表头所占的宽度 先放到columnwidths里面
}
if (allcolumswidth + prndgv.columncount < printpaper.width)
{
int columnaddwidth = (printpaper.width - allcolumswidth - prndgv.columncount) / prndgv.columncount;
for (int i = 0; i < prndgv.columncount; i++)
{
columnwidths[i] += columnaddwidth;
}
}
//*************************************************************
currentx = 0;
int titleheight = (int)math.ceiling(graphic.measurestring("1e{(汗", titlefont).height);
//打印表头
for (int i = 0; i < prndgv.columncount; i++)
{
string celvalue = prndgv.columns[i].headertext;
//打印背景
graphic.fillrectangle(new solidbrush(titlebackgroup), new rectangle((int)currentx, (int)currenty, columnwidths[i], titleheight));
//打印内容
graphic.drawstring(celvalue, titlefont, titlebrush, currentx, currenty);
//打印表格边框
graphic.drawrectangle(new pen(titlebrush), new rectangle((int)currentx, (int)currenty, columnwidths[i], titleheight));
currentx = currentx + columnwidths[i];
}
currentx = 0;
currenty = currenty + titleheight;
int contentheight = (int)math.ceiling(graphic.measurestring("1e{(汗", defaultfont).height);
//打印内容
for (int i = 0; i < prndgv.rows.count; i++)
{
for (int j = 0; j < prndgv.columncount; j++)
{
string celvalue = prndgv[j, i].value.tostring();//打印内容
graphic.drawstring(celvalue, defaultfont, defaultbrush, currentx, currenty);//打印表格边框
graphic.drawrectangle(new pen(defaultbrush), new rectangle((int)currentx, (int)currenty, columnwidths[j], contentheight));
currentx = currentx + columnwidths[j];
}
currentx = 0;
currenty = currenty + contentheight;
}
}
}
调用示例代码
private void printdocument1_printpage(object sender, printpageeventargs e)
{
printcore print = new printcore(printdocument1, e.graphics, new font("宋体", 14));
if (print.error != null)
{
e.cancel = true;
messagebox.show(print.error);
return;
}
print.iscenter = true;
print.defaultfont = new font("宋体", 16);
print.printstring("定积分落实到减肥了减肥了圣诞节死减", true);
print.iscenter = false;
print.defaultfont = new font("宋体", 14);
print.printstring("111定积分落实到减定积分落实到减肥了圣诞节死定了减肥了束带结发连锁店减肥了哦定积分落实到减肥了圣诞节死定了减肥了束带结发连锁店减肥了哦肥了圣诞节死定了减肥了束带结发连锁店减肥了哦");
print.printdatagridview(datagridview1,new font("宋体", 18),brushes.black,defaultbackcolor);
}
总结:以上打印有两个小问题没有处理。一个是关于分页,一个是当表格的宽度过长,超过了页面的宽度,没有进行换行处理。
另附上源码
作者:bonker