记事本打印功能的一段代码

最近要做一个合同打印的功能,合同中的文字是富文本,有一定格式,但是不限填写的内容.在网上也没有找到相关的文章,下面写了一个记事本打印的功能, 不过只能做到都是采用相同的字体,可以换页处理.
string strPrintText;
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
System.Drawing.Font font = new Font("宋体", 14);
Graphics g = e.Graphics;
float cyFont = font.GetHeight(g);
StringFormat strfmt = new StringFormat();
RectangleF rectfFull, rectfText;
int iChars, iLines;

if (g.VisibleClipBounds.X < 0)
{
rectfFull = e.MarginBounds;
}
else
{
rectfFull = new RectangleF(
e.MarginBounds.Left - (e.PageBounds.Width -
g.VisibleClipBounds.Width) / 2,
e.MarginBounds.Top - (e.PageBounds.Height -
g.VisibleClipBounds.Height) / 2,
e.MarginBounds.Width, e.MarginBounds.Height);
}

rectfText = RectangleF.Inflate(rectfFull, 0, -2 * cyFont);//去掉二行,可以打印标题和页码

int iDisplayLines = (int)Math.Floor(rectfText.Height / cyFont); //计算可以打印的行数
rectfText.Height = iDisplayLines * cyFont; //计算可以正式打印的高度

strfmt.Trimming = StringTrimming.Word;


if (strPrintText.Length == 0)
{
e.Cancel = true;
return;
}
g.DrawString(strPrintText, font, Brushes.Black,rectfText, strfmt); //所有文字全部打印

g.MeasureString(strPrintText, font, rectfText.Size, strfmt, out iChars, out iLines); //获取该区域能打印了多少个字符
strPrintText = strPrintText.Substring(iChars); //把打印过的字符去掉,下次就没有了.
e.HasMorePages = (strPrintText.Length >0);//判断是否还有字要打印.

}

private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{

strPrintText = richTextBox1.Text;
}

对于富文本的处理,不知有没有好的办法.

你可能感兴趣的:(记事本)