其实两年前我做过此类东西, 但是当时既没做笔记 , 后来又找不着代码了, 于是乎, 上个月又要做条码打印时, 整个地又重来了一遍.
在网上查资料时, 发现好几款控件, 下载下来一看, 体积之大远超我想像, 用法也一点都不简单, 很不满, 其实ZPL语言相当简单, 与其向项目中引入这么一个不知道怎么写的控件, 还不如自己写几行ZPL代码.
ZPL(Zebra Programming Language) 是斑马公司(做条码打印机的公司)自己设计的语言, 由于斑马打印机是如此普遍, 以至于据我所见所知, 条码打印机全部都是斑马的, 所以控制条码打印机几乎就变成了对ZPL的使用.
总的逻辑分为以下两步:
(1)编写ZPL指令
(2)把ZPL作为C#的字符串, 由C#把它送至连接打印机的端口.
其中, 用C#把字符串送并口的写法是固定的, 这部分的代码如下:
public class Printer { [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] private struct OVERLAPPED { int Internal; int InternalHigh; int Offset; int OffSetHigh; int hEvent; } [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern int CreateFile( string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile ); [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool WriteFile( int hFile, byte[] lpBuffer, int nNumberOfBytesToWrite, out int lpNumberOfBytesWritten, out OVERLAPPED lpOverlapped ); [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool CloseHandle( int hObject ); private int iHandle; public bool Open() { iHandle = CreateFile("LPT1:", (uint)FileAccess.ReadWrite, 0, 0, (int)FileMode.Open, 0, 0); if (iHandle != -1) { return true; } else { return false; } } public bool Write(string Mystring) { if (iHandle != -1) { int i; OVERLAPPED x; byte[] mybyte = System.Text.Encoding.Default.GetBytes(Mystring); return WriteFile(iHandle, mybyte, mybyte.Length, out i, out x); } else { throw new Exception("端口未打开!"); } } public bool Close() { return CloseHandle(iHandle); } }
这个类封装了对并口的操作, 它的使用方法为:
var printer = new Printer(); if (!printer.Open()) { GB.IO.SetError("未能连接打印机,请确认打印机是否安装正确并接通电源。"); return; } printer.Write(cmd); if (!printer.Close()) { GB.IO.SetError("未能关闭与打印机之间的连接,这可能意味着严重的错误,请重启电脑及打印机。"); return; }
其中, cmd即是构造好的ZPL指令.
现在来看一段示意ZPL指令.
^XA
^MD30
^LH60,10
^FO20,10
^ACN,18,10
^BY1.4,3,50
^BC,,Y,N
^FD01008D004Q-0^FS
^XZ
这是一段能够实际执行的指令串, 下面逐行解释.
第一句^XA和最后一句^XZ分别代表一个指令块的开始和结束, 是固定的东西.
^MD是设置色带颜色的深度, 取值范围从-30到30, 上面的示意指令将颜色调到了最深.
^LH是设置条码纸的边距的, 这个东西在实际操作上来回试几次即可.
^FO是设置条码左上角的位置的, 这个对程序员应该很容易理解. 0,0 代表完全不留边距.
^ACN是设置字体的. 因为在条码下方会显示该条码的内容, 所以这里要设一下字体. 这个字体跟条码无关.
^BY是设置条码样式的, 这是最重要的一个东西, 1.4是条码的缩放级别, 这个数值下打出的条码很小, 3是条码中粗细柱的比例, 50是条码高度.
^BC是打印code128的指令, 具体参数详见ZPL的说明书.
^FD设置要打印的内容, ^FS表示换行.
所以上述语句最终的效果就是打印出一个值为01008D004Q-0的条码, 高度为50.
以上可以看出, ZPL的指令方式很简单, 实际上, 如果打印要求不复杂的话, 基本上也就用得上上述的几个指令了,
其它的指令虽然很多, 但是基本上可以无视.
其实即使要打图形之类的东西, 也并不复杂, 例如GB可以打印出来一个边框, GC打印一个圆圈等. 其它的自定义图案需要先把图案上传至打印机,
指令部分只要选择已上传的图案, 选择方式跟上面的字体选择类似, 也很简单.
在实践中, 常常会需要一次横打两张, 其实可以把一排的两张想像成一张, 连续执行两个打印命令, 把第二个FO的横坐标设置得大一些就行了.
例如:
^XA
^FO20,10
^FD001^FS
^FO60,10
^FD002^FS
^XZ
第一对FO/FD命令打印左侧, 第二对FO/FD命令打印右侧.
具体的指令详细解释, 及要实现其它功能, 可下载 ZPL II Programming Guide, 这本书写得非常详细. (如链接不能下载, google书名即可)
----------2013/9/18 更新
将指令发送到打印机的代码, 上述做法仅限于打印机在本地,且接在并口1上面,如果打印机在远程, 或者打印机不是并口的, 可以通过驱动程序来发送指令。
这要求首先在操作系统中装好打印机驱动,调试无误以后, 记录下驱动中打印机的名称, 然后向此打印机发送指令, 与打印机驱动通信的类如下:
public class RemotePrinter { // Structure and API declarions: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class DOCINFOA { [MarshalAs(UnmanagedType.LPStr)] public string pDocName; [MarshalAs(UnmanagedType.LPStr)] public string pOutputFile; [MarshalAs(UnmanagedType.LPStr)] public string pDataType; } [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd); [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool ClosePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di); [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool EndDocPrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool StartPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool EndPagePrinter(IntPtr hPrinter); [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten); // SendBytesToPrinter() // When the function is given a printer name and an unmanaged array // of bytes, the function sends those bytes to the print queue. // Returns true on success, false on failure. public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount) { Int32 dwError = 0, dwWritten = 0; IntPtr hPrinter = new IntPtr(0); DOCINFOA di = new DOCINFOA(); bool bSuccess = false; // Assume failure unless you specifically succeed. di.pDocName = "My C#.NET RAW Document"; di.pDataType = "RAW"; // Open the printer. if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero)) { // Start a document. if (StartDocPrinter(hPrinter, 1, di)) { // Start a page. if (StartPagePrinter(hPrinter)) { // Write your bytes. bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten); EndPagePrinter(hPrinter); } EndDocPrinter(hPrinter); } ClosePrinter(hPrinter); } // If you did not succeed, GetLastError may give more information // about why not. if (bSuccess == false) { dwError = Marshal.GetLastWin32Error(); } return bSuccess; } public static bool SendFileToPrinter(string szPrinterName, string szFileName) { // Open the file. FileStream fs = new FileStream(szFileName, FileMode.Open); // Create a BinaryReader on the file. BinaryReader br = new BinaryReader(fs); // Dim an array of bytes big enough to hold the file's contents. Byte[] bytes = new Byte[fs.Length]; bool bSuccess = false; // Your unmanaged pointer. IntPtr pUnmanagedBytes = new IntPtr(0); int nLength; nLength = Convert.ToInt32(fs.Length); // Read the contents of the file into the array. bytes = br.ReadBytes(nLength); // Allocate some unmanaged memory for those bytes. pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength); // Copy the managed byte array into the unmanaged array. Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength); // Send the unmanaged bytes to the printer. bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength); // Free the unmanaged memory that you allocated earlier. Marshal.FreeCoTaskMem(pUnmanagedBytes); return bSuccess; } public static bool SendStringToPrinter(string szPrinterName, string szString) { IntPtr pBytes; Int32 dwCount; // How many characters are in the string? dwCount = szString.Length; // Assume that the printer is expecting ANSI text, and then convert // the string to ANSI text. pBytes = Marshal.StringToCoTaskMemAnsi(szString); // Send the converted ANSI string to the printer. SendBytesToPrinter(szPrinterName, pBytes, dwCount); Marshal.FreeCoTaskMem(pBytes); return true; } }
在调用时, 只要调用RemotePrinter.SendStringToPrinter方法即可, 第一个参数是打印机的名称(驱动中显示的名称), 第二个参数是命令。
---------------------------------------------
作者:夏狼哉
博客:http://www.cnblogs.com/Moosdau
如需引用,敬请保留作者信息,谢谢