如何在C#中实现DATAGRIDVIEW 数据打印
分享下关于 C#中 实现打印功能的代码 希望对初学者有所帮助
关于打印格式感觉很痛苦 我一般选择两种方式 一种是通过 DRAWING 格式,另外一种通过HTML代码来控制,都特别麻烦,不知道各位高手能否提供一些更好的建议?
第一步 基本操作
定义 一个C#提供的 PrintDocument 对象
private PrintDocument printDocument;
第二步
//写一个方法 对打印事件进行初始化
下载:
Init.cs
- private void PrintDocument ()
- {
- printDocument = new PrintDocument () ;
- printDocument . PrintPage += new PrintPageEventHandler ( printDocument_PrintPage ) ;
- }
第三步
事件响应方法
下载:
Action.cs
- private void printDocument_PrintPage ( object sender , PrintPageEventArgs e )
- {
- //StringReader lineReader = new StringReader(textBox.Text);
- Graphics graphic = e . Graphics ; //获取绘图对象
- float linesPerPage = 0 ; //页面行号
- float yPosition = 0 ; //绘制字符串的纵向位置
- float leftMargin = e . MarginBounds . Left ; //左边距
- float topMargin = e . MarginBounds . Top ; //上边距
- string line = string . Empty ; //读取的行字符串
- int currentPageLine = 0 ; //当前页读取的行数
- Font charFont = button1 . Font ; //获取打印字体
- SolidBrush brush = new SolidBrush ( Color . Black ) ; //刷子
- linesPerPage = e . MarginBounds . Height / charFont . GetHeight ( graphic ) ; //每页可打印的行数
- //countNum记录全局行数,currentPageLine记录当前打印页行数。
- // graphic.DrawString("水费通知单", charFont, brush, 360, 100, new StringFormat());
- //房产地址textbox3
- //租户名字textbox2
- // 上次缴费记录 textbox5
- //费用到期 textbox7
- //合同开始时间 textbox4
- //合同到期时间 textbox6
- //月租金 textbox8
- //月管理费 textbox9
- //缴费租金 textbox11
- //缴费管理费 textbox10
- //总计 textbox12
- graphic . DrawString ( " 武大教育发展有限公司房屋租金缴费登记 " , charFont , brush , 300 , 100 , new StringFormat ()) ;
- graphic . DrawString ( " 租户: " + this . textBox2 . Text , charFont , brush , 100 , 140 , new StringFormat ()) ;
- graphic . DrawString ( " 合同号: " + this . textBox1 . Text , charFont , brush , 100 , 180 , new StringFormat ()) ;
- graphic . DrawString ( " 房产地址: " + this . textBox3 . Text , charFont , brush , 100 , 220 , new StringFormat ()) ;
- graphic . DrawString ( " 月租金: " + this . textBox8 . Text , charFont , brush , 100 , 260 , new StringFormat ()) ;
- graphic . DrawString ( " 月管理费: " + this . textBox9 . Text , charFont , brush , 100 , 300 , new StringFormat ()) ;
- graphic . DrawString ( " 上次缴费至: " + this . textBox7 . Text , charFont , brush , 100 , 340 , new StringFormat ()) ;
- graphic . DrawString ( " 本次缴费至: " + this . dateTimePicker1 . Text , charFont , brush , 100 , 370 , new StringFormat ()) ;
- graphic . DrawString ( " 租金: " + this . textBox11 . Text , charFont , brush , 100 , 410 , new StringFormat ()) ;
- graphic . DrawString ( " 管理费: " + this . textBox10 . Text , charFont , brush , 100 , 450 , new StringFormat ()) ;
- graphic . DrawString ( " 合计: " + this . textBox12 . Text , charFont , brush , 100