之前打印都是用串口,现在很多打印机都是USB接口的,换了USB接口的打印机后,USB接口的程序一直没办法打印,后来调用厂商的DLL, 但很麻烦,在网上找了很多,都没有找到合适的,之后参考了PrintDocument类一些打印方法,测试成功,贴出代码,如有不对的地方,和需要优化的,请指出。
创新互联建站是网站建设技术企业,为成都企业提供专业的网站设计、网站建设,网站设计,网站制作,网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制适合企业的网站。十多年品质,值得信赖!
首先:
//定义一个字符串流,用来接收所要打印的数据
private StringReader sr;
//str要打印的数据
public bool Print(string str)
{
bool result = true;
try
{
sr = new StringReader(sb.ToString());
PrintDocument pd = new PrintDocument();
pd.PrintController = new System.Drawing.Printing.StandardPrintController();
pd.DefaultPageSettings.Margins.Top = 2;
pd.DefaultPageSettings.Margins.Left = 0;
pd.DefaultPageSettings.PaperSize.Width = 320;
pd.DefaultPageSettings.PaperSize.Height = 5150;
pd.PrinterSettings.PrinterName = pd.DefaultPageSettings.PrinterSettings.PrinterName;//默认打印机
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.Print();
}
catch (Exception ex)
{
result = false;
}
finally
{
if (sr != null)
sr.Close();
}
return result;
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
Font printFont = new Font("Arial", 9);//打印字体
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
String line = "";
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
while (count < linesPerPage && ((line = sr.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
调用Print(string str)方法就可以打印啦!
例: StringBuilder sb = new StringBuilder();
sb.Append(" 益民停车场管理系统 \n");
sb.Append("*************************************\n");
sb.Append("进场时间:" + DateTime.Now.ToString() + "\n");
sb.Append("出场时间:" + DateTime.Now.AddHours(2).ToString() + "\n");
sb.Append("停车时长: 2 小时\n");
sb.Append("停车收费: 5 元\n");
sb.Append("*************************************\n");
Print(string sb.toString());
另外:此方法不管是串口,并口,还是USB接口的打印机都可以调用,前提是一定要将打印机设为默认打印机。如果要关闭打印机,可设一个BOOL变量,如果为true则调用,否则不调用。
网站题目:C#小票打印(通用)
文章源于:http://scyingshan.cn/article/iegodg.html