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方法即可, 第一個參數是打印機的名稱(驅動中顯示的名稱), 第二個參數是命令。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM