在窗体上拖拽进一个 printDocument 控件,双击该控件,在该空间的 click 事件中添加:
private void PrintButton_Click(object sender, EventArgs e)
{
listBox1.SelectedIndex = 0;
printDocument1.Print();
}
上面的listBox1控件里有我要打印的内容
printDocument1.Print() 方法:
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics; //获得绘图对象
float linesPerPage = 0; //页面的行号
float yPosition = 0; //绘制字符串的纵向位置
int count = 0; //行计数器
float leftMargin = 100; //左边距
int lineHeight = 40;
Font printFont = new Font("宋体",18); //当前的打印字体
Font TitleFont = new Font("黑体", 24);
SolidBrush myBrush = new SolidBrush(Color.Black);//刷子
//linesPerPage = e.MarginBounds.Height / printFont.GetHeight(g);//每页可打印的行数
linesPerPage = e.MarginBounds.Height / lineHeight;//每页可打印的行数
g.DrawString("共和县2019年公共住房公开配租摇号结果", TitleFont, myBrush, 70, 80, new StringFormat());
g.DrawString("序号 姓名 身份证号 楼号", printFont, myBrush, 90, 160, new StringFormat());
//逐行的循环打印一页
while (count < 15 && listBox1.SelectedIndex < listBox1.Items.Count)
{
yPosition = 200 + (count * lineHeight);
g.DrawString(listBox1.SelectedItem.ToString().Replace("|", " "), printFont, myBrush, leftMargin, yPosition, new StringFormat());
if (listBox1.SelectedIndex != 72)
{
listBox1.SelectedIndex++;
}
else
{
break;
}
count++;
}
g.DrawString("公证处: 监察局:", printFont, myBrush, leftMargin, 800, new StringFormat());
g.DrawString("群众摇号代表:", printFont, myBrush, leftMargin, 940, new StringFormat());
// 注意:使用本段代码前,要在该窗体的类中定义lineReader对象:
// StringReader lineReader = null;
//如果本页打印完成而line不为空,说明还有没完成的页面,这将触发下一次的打印事件。在下一次的打印中lineReader会
//自动读取上次没有打印完的内容,因为lineReader是这个打印方法外的类的成员,它可以记录当前读取的位置
if (listBox1.SelectedIndex != 72)
e.HasMorePages = true;
else
{
e.HasMorePages = false;
// 重新初始化lineReader对象,不然使用打印预览中的打印按钮打印出来是空白页
//lineReader = new StringReader(str); // textBox是你要打印的文本框的内容
}
}