您好,登錄后才能下訂單哦!
之前打印都是用串口,現(xiàn)在很多打印機都是USB接口的,換了USB接口的打印機后,USB接口的程序一直沒辦法打印,后來調(diào)用廠商的DLL, 但很麻煩,在網(wǎng)上找了很多,都沒有找到合適的,之后參考了PrintDocument類一些打印方法,測試成功,貼出代碼,如有不對的地方,和需要優(yōu)化的,請指出。
首先:
//定義一個字符串流,用來接收所要打印的數(shù)據(jù)
private StringReader sr;
//str要打印的數(shù)據(jù)
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;
}
調(diào)用Print(string str)方法就可以打印啦!
例: StringBuilder sb = new StringBuilder();
sb.Append(" 益民停車場管理系統(tǒng) \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接口的打印機都可以調(diào)用,前提是一定要將打印機設(shè)為默認打印機。如果要關(guān)閉打印機,可設(shè)一個BOOL變量,如果為true則調(diào)用,否則不調(diào)用。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。