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

如需引用,敬请保留作者信息,谢谢

C#打印条码与ZPL的更多相关文章

  1. BarTender 通过ZPL命令操作打印机打印条码, 操作RFID标签

    注:    由于工作需要, 也是第一次接触到打印机的相关内容, 凑巧, 通过找了很多资料和帮助后, 也顺利的解决了打印标签的问题 (标签的表面信息[二维码,条形码, 文字] 和 RFID标签的EPC写 ...

  2. 吉特仓库管理系统- 斑马打印机 ZPL语言的腐朽和神奇

    上一篇文章说到了.NET中的打印机,在PrintDocument类也暴露一些本质上上的问题,前面也提到过了,虽然使用PrintDcoument打印很方便.对应条码打印机比如斑马等切刀指令,不依赖打印机 ...

  3. C#调用斑马打印机打印条码标签(支持COM、LPT、USB、TCP连接方式和ZPL、EPL、CPCL指令)【转】

    原文地址:http://blog.csdn.net/ldljlq/article/details/7338772 在批量打印商品标签时一般都要加上条码或图片,而这类应用大多是使用斑马打印机,所以我也遇 ...

  4. ZPL打印中文信息

    博客来源:http://www.cnblogs.com/Geton/p/3595312.html 相信各位在实际的项目中,需要开发打条码模块的也会有不少,很多同行肯定也一直觉得斑马打印机很不错,但是Z ...

  5. C# WinForm程序打印条码 Code39码1

    做WinForm程序需要打印条码,为了偷懒不想自己写生成条码的程序在网上下载一个标准的39码的字体,在程序里面换上这个条码字体即可打印条码了. 最重要的一点作为记录: 如果想把“123456789”转 ...

  6. C#打印条码BarTender SDK打印之路和离开之路(web平凡之路)

    从来没想过自己会写一篇博客,鉴于这次从未知的探索到一个个难点的攻破再到顺利打印,很想记录这些点滴,让后人少走弯路. 下面走进正题. 需求:取数据库里的相应的字段数据,并生成条形码,可以批量.单条打印. ...

  7. C#-利用ZPL语言完毕条形码的生成和打印

     近期由于公司项目的须要,研究了一项对我来说算是新的技术-条形码的生成和打印.由于之前没有接触过这方面的知识,所以刚開始还有点小迷茫和小兴奋,只是一步一步来,问题总会解决的.如今来总结一下做条形码 ...

  8. C# 通过Bartender模板打印条码,二维码, 文字, 及操作RFID标签等。

    1.在之前写的一篇文章中, 有讲到如何利用ZPL命令去操作打印里,  后面发现通过模板的方式会更加方便快捷, 既不用去掌握ZPL的实现细节, 就可以轻松的调用实现打印的功能. 解决方案: 1.网络下载 ...

  9. C#调用TSC条码打印机打印条码

    #region 调用TSC打印机打印条码 /// <summary> /// 调用TSC打印机打印条码 /// </summary> /// <param name=&q ...

随机推荐

  1. DashPathEffect

    DashPathEffect 可以实现以动画的形式画线的效果. 通过setPathEffect()方法为画笔Paint对象设置绘制路径的特效. PathEffect pathEffect=new Da ...

  2. LabVIEW之生产者/消费者模式--队列操作 彭会锋

    LabVIEW之生产者/消费者模式--队列操作 彭会锋 本文章主要是对学习LabVIEW之生产者/消费者模式的学习笔记,其中涉及到同步控制技术-队列.事件.状态机.生产者-消费者模式,这几种技术在在本 ...

  3. SPSS数据分析—对数线性模型

    我们之前讲Logistic回归模型的时候说过,分类数据在使用卡方检验的时候,当分类过多或者每个类别的水平数过多时,单元格会划分的非常细,有可能会导致大量单元格频数很小甚至为0,并且卡方检验虽然可以分析 ...

  4. 【LeetCode】#344 Reverse String

    [Question] Write a function that takes a string as input and returns the string reversed. Example: G ...

  5. 实验三——for 语句及分支结构else-if

    1.本节课学习到的知识点:在本次课中,我学习了for语句的使用,认识了for语句的执行流,明确了三种表达式的意义.以及最常用的实现多分支的else-if语句. 2.实验过程中遇到的问题及解决方法:在本 ...

  6. Hprose question

    1 在服务端 接口的开发中 如果定义了index()方法 中间不能够有参数,否则报错. 2 接口方法中的参数 最好使用单参数 如fun($uid ) 或者 如果需要多个参数 fun($param){$ ...

  7. 字符串0.在php和js中转换为布尔类型 值是false还是true

    在php 中 $a = '0'; $b = (bool)$a; var_dump($a);//输出false 在js中官方说明: Note:If the value parameter is omit ...

  8. Const关键字

    const const是一个C语言的关键字,它限定一个变量不允许被改变.使用const在一定程度上可以提高程序的安全性和可靠性.另外,在观看别人代码的时候,清晰理解const所起的作用,对理解对方的程 ...

  9. ArcGIS操作Excel文件没有注册类解决办法

    在ArcGIS Desktop中进行表连接时选择了一张excel表,但添加该表时报错: 原因是机器上缺少Office的数据驱动. ArcGIS 支持 : Excel 2003 以及更早版本的 .xls ...

  10. sql sever跨数据库复制数据的方法【转】

    1,用Opendatasource系统函数 详细的用法已经注释在sql代码中了.这个是在sqlserver到sqlserver之间的倒数据.2005,2008,2012应该都是适用的. --从远程服务 ...