• C# ZPL


    转载: https://www.cnblogs.com/Moosdau/archive/2009/10/16/1584627.html

    ZPL(Zebra Programming Language) 是斑马公司(做条码打印机的公司)自己设计的语言, 由于斑马打印机是如此普遍, 以至于据我所见所知, 条码打印机全部都是斑马的, 所以控制条码打印机几乎就变成了对ZPL的使用.

    总的逻辑分为以下两步:

    (1)编写ZPL指令

    (2)把ZPL作为C#的字符串, 由C#把它送至连接打印机的端口.

    namespace Barcode_Print
    {
        /// <summary>
        /// 本类使用说明:
        /// 将一行ZPL指令作为string参数传给write函数即可
        /// </summary>
        class LPTControl
        {
            [StructLayout(LayoutKind.Sequential)]
            private struct OVERLAPPED
            {
                int Internal;
                int InternalHigh;
                int Offset;
                int OffSetHigh;
                int hEvent;
            }
    
            [DllImport("kernel32.dll")]
            private static extern int CreateFile(
            string lpFileName,
            uint dwDesiredAccess,
            int dwShareMode,
            int lpSecurityAttributes,
            int dwCreationDisposition,
            int dwFlagsAndAttributes,
            int hTemplateFile
            );
    
    
            [DllImport("kernel32.dll")]
            private static extern bool WriteFile(
            int hFile,
            byte[] lpBuffer,
            int nNumberOfBytesToWrite,
            out   int lpNumberOfBytesWritten,
            out   OVERLAPPED lpOverlapped
            );
    
    
            [DllImport("kernel32.dll")]
            private static extern bool CloseHandle(
            int hObject
            );
    
    
            private int iHandle;
            public bool Open()
            {
                iHandle = CreateFile("lpt1", 0x40000000, 0, 0, 3, 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);
            }
         
        } 
    }

    这个类封装了对并口的操作, 它的使用方法为:

    LPTControl lpt = new LPTControl();
    
                string cmd = "^XA ^MD30^LH60,10^FO20,10^ACN,18,10^BY1.4,3,50^BC,,Y,N^FD01008D004Q-0^FS^XZ";
    
                if (!lpt.Open())
                {
                    Response.Write("未能连接打印机,请确认打印机是否安装正确并接通电源。");
                    return;
    
                }
    
                lpt.Write(cmd);
    
                if (!lpt.Close())
                {
                    if (!lpt.Open())
                    {
                        Response.Write("未能连接打印机,请确认打印机是否安装正确并接通电源。");
                        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的横坐标设置得大一些就行了.

    具体的指令详细解释, 及要实现其它功能, 可下载 ZPL II Programming Guide, 这本书写得非常详细. (如链接不能下载, google书名即可)

    -------------------------------------

    将指令发送到打印机的代码, 上述做法仅限于打印机在本地,且接在并口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方法即可, 第一个参数是打印机的名称(驱动中显示的名称), 第二个参数是命令。
  • 相关阅读:
    【洛谷5052】[COCI2017-2018#7] Go(区间DP)
    【洛谷6564】[POI2007] 堆积木KLO(树状数组优化DP)
    【洛谷6940】[ICPC2017 WF] Visual Python++(扫描线)
    【洛谷6939】[ICPC2017 WF] Tarot Sham Boast(PGF结论题)
    【洛谷4123】[CQOI2016] 不同的最小割(最小割树)
    初学最小割树
    【洛谷6122】[NEERC2016] Mole Tunnels(模拟费用流)
    【洛谷6936】[ICPC2017 WF] Scenery(思维)
    【洛谷2805】[NOI2009] 植物大战僵尸(最大权闭合子图)
    【洛谷1393】Mivik 的标题(容斥+border性质)
  • 原文地址:https://www.cnblogs.com/lab-zj/p/13992677.html
Copyright © 2020-2023  润新知