技术开发 频道

C#中进行文本打印


【IT168技术文档】

  问题描述:
    做了个记事本程序,要求能按标准打印其中的文档,包括在每行文字数目上进行控制等。
解决方法:
  一、搞清楚打印的过程:
  1、定义PrintDocument类,并且声明其PrintPage事件。
private void PrintDocument() { printDocument = new PrintDocument(); printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage); }
  2、实现PrintPage事件(关键):
/**//// <summary> /// 用来处理打印过程的核心事件。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <remarks></remarks> 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 = richTextBox1.Font;//获取打印字体 SolidBrush brush = new SolidBrush(Color.Black);//刷子 linesPerPage = e.MarginBounds.Height / charFont.GetHeight(graphic);//每页可打印的行数 //countNum记录全局行数,currentPageLine记录当前打印页行数。 while (countNum < richTextBox1.Lines.Length) { if (currentPageLine < linesPerPage) { line = richTextBox1.Lines[countNum].ToString(); if (line.Length <= 50) { yPosition = topMargin + (currentPageLine * charFont.GetHeight(graphic)); //绘制当前行 graphic.DrawString(line, charFont, brush, leftMargin, yPosition, new StringFormat()); countNum++; currentPageLine++; } else { //拆分后的行数 int moreLine = line.Length / 50 + 1; string tempLine; for (int i = 0; i < moreLine; i++) { //获得当前行的子串 if ((line.Length - i * 50) >= 50) { tempLine = line.Substring(i * 50, 50); } else { tempLine = line.Substring(i * 50, line.Length - i * 50); } yPosition = topMargin + (currentPageLine * charFont.GetHeight(graphic)); //绘制当前行 graphic.DrawString(tempLine, charFont, brush, leftMargin, yPosition, new StringFormat()); //当前打印页行数加1 currentPageLine++; } //总行数加1 countNum++; } } else { line = null; break; } } //一页显示不完时自动重新调用此方法 if (line == null) { e.HasMorePages = true; } else { e.HasMorePages = false; } //每次打印完后countNum清0; if (countNum >= richTextBox1.Lines.Length) { countNum = 0; } }
0
相关文章