之前打印都是用串口,现在很多打印机都是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则调用,否则不调用。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。