第一步:确保电脑已经下载了打印机驱动,并且本地可以正常使用打印机
第二部:上代码
1.添加button按钮,因为是测试用的,所以选择创建的项目是web页面,页面类型为web窗体。
2.添加按钮点击事件:<asp:Button runat=“server” Text=“打印测试” id=“printTest” OnClick=“printTest_Click”/>
3:编写后台代码记录如下:
using System;
using System.Drawing;
using System.Drawing.Printing;
namespace PrintContrl
{
public partial class print : System.Web.UI.Page
{
//需要显示的行数
int rowCount = 5;
//每行高度
int rowCol = 40;
private int count = 40;//打印条数
private int currentPrint = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 打印测试
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void printTest_Click(object sender, EventArgs e)
{
PrintDocument print = new PrintDocument();
print.PrintPage += new PrintPageEventHandler(printDocument_PrintA4Page);
string name = "CAB SQUIX 4.3/300";
print.PrinterSettings.PrinterName = name;
print.DefaultPageSettings.Landscape = true;//设置横向打印,不设置默认是纵向的
print.PrintController = new System.Drawing.Printing.StandardPrintController();
int printCount = count / (rowCount - 1) + ((count % (rowCount - 1)) != 0 ? 1 : 0);
for (int i = 1; i <= printCount; i++)
{
currentPrint = i;
print.Print();
}
}
/// <summary>
/// 打印页面内容填充
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void printDocument_PrintA4Page(object sender, PrintPageEventArgs e)
{
Font titleFont = new Font("黑体", 18, System.Drawing.FontStyle.Bold);//标题字体
Font fntTxt = new Font("宋体", 10, System.Drawing.FontStyle.Regular);//正文文字
System.Drawing.Brush brush = new SolidBrush(System.Drawing.Color.Black);//画刷
System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Black); //线条颜色
System.Drawing.Point po = new System.Drawing.Point(10, 10);
try
{
e.Graphics.DrawString("标题", titleFont, brush, new System.Drawing.Point(20, 40));
e.Graphics.DrawString("logo", titleFont, brush, new System.Drawing.Point(200, 40));
//画横线
Point[] point = { new Point(20, 50), new Point(200, 50) };
e.Graphics.DrawLines(pen, point);
e.Graphics.DrawString("本次打印时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"), fntTxt, brush, new System.Drawing.Point(750, rowCount * rowCol + 85));
//画矩形
e.Graphics.DrawRectangle(pen, 20, 70, 90, rowCount * rowCol);
//划横线
for (int i = 0; i < this.rowCount - 1; i++)
{
Point[] points = { new Point(20, 70 + (i + 1) * this.rowCol), new Point(110, 70 + (i + 1) * this.rowCol) };
e.Graphics.DrawLines(pen, points);
}
//划竖线
Point[] points1 = { new Point(60, 70), new Point(60, 70 + this.rowCol * this.rowCount) };
e.Graphics.DrawLines(pen, points1);
//头部
e.Graphics.DrawString("产品编号", fntTxt, brush, new System.Drawing.Point(25, 75));
e.Graphics.DrawString("1000034", fntTxt, brush, new System.Drawing.Point(65, 75));
}
catch (Exception ex)
{
throw ex;
}
}
}
}
备注:本实例主要通过PrintDocument对象对打印机实现控制