C# EPL USB 指令打印

Posted fairystepwgl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# EPL USB 指令打印相关的知识,希望对你有一定的参考价值。

 1 private void btnPrinter_Click(object sender, EventArgs e)
 2         {
 3 
 4            #region ESC 热敏图像点阵像素点读取打印
 5 
 6             //Bitmap bitmap = new Bitmap(@"D:\\450X100.bmp");
 7             //NetPOSPrinter netPOSPrinter = new NetPOSPrinter();
 8             //netPOSPrinter.PrintPic(bitmap);
 9 
10             #endregion
11 
12             #region EPL USB 打印
13             //Bitmap img = new Bitmap(@"D:\\450X100.bmp");
14             //ZebraPrintHelper.PrinterType = DeviceType.DRV;
15             //ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.EPL;
16             //ZebraPrintHelper.PrinterName = "ZDesigner GK888t (EPL)";
17             //byte[] imgByte = ImageToByte.ImgToByt(img);
18             //ZebraPrintHelper.PrintGraphics(imgByte);
19 
20             #endregion
21 
22             #region ZPL II 打印指令
23             //^XA^CFD
24             //^POI
25             //^LH330,10
26             //^FO50,50
27             //^FDSMARTDIGITAL^FS
28             //^FO50,75
29             //^FD021-51871630^FS
30             //^XZ
31 
32             //StringBuilder sb = new StringBuilder();
33             //sb.Append("^XA^CFD");
34             //sb.Append("^POI");
35             //sb.Append("^LH330,10");
36             //sb.Append("^FO50,50");
37             //sb.Append("^FDSMARTDIGITAL^FS");
38             //sb.Append("^FO50,75");
39             //sb.Append("^FD021-51871630^FS");
40             //sb.Append("^XZ");
41 
42             //byte[] cmd = Encoding.Default.GetBytes(sb.ToString());
43 
44             #endregion
45 
46             #region EPL USB 指令打印
47             ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.EPL;
48             ZebraPrintHelper.PrinterName = "ZDesigner GK888t (EPL)";
49             ZebraPrintHelper.PrinterType = DeviceType.DRV;
50             
51             string cmd = "N" + "\\r\\n" +
52                 "Q400,025" + "\\n\\r" +
53                 "A140,45,0,8,1,1,N,\\"古典黄芥沫调味酱\\"" + "\\r\\n" +
54                 "A140,90,0,8,1,1,N,\\"规格:\\"" + "\\r\\n" +
55                 "A240,95,0,4,1,1,N,\\"" + "100ML/瓶" + "\\"" + "\\r\\n" +
56                 "A140,135,0,8,1,1,N,\\"生产日期:\\"" + "\\r\\n" +
57                 "A300,140,0,4,1,1,N,\\"" + "2015-10-02" + "\\"" + "\\r\\n" +
58                 "B140,180,0,1,3,2,100,B,\\"" + "8957891234567895789588535" + "\\"" + "\\r\\n" +
59                 "P1" + "\\r\\n";
60 
61             ZebraPrintHelper.PrintCommand(cmd.ToString());
62             #endregion
63         }
   1 using Microsoft.Win32.SafeHandles;
   2 using System;
   3 using System.Collections.Generic;
   4 using System.Drawing;
   5 using System.Drawing.Imaging;
   6 using System.IO;
   7 using System.IO.Ports;
   8 using System.Net;
   9 using System.Net.Sockets;
  10 using System.Runtime.InteropServices;
  11 using System.Text;
  12 
  13 namespace ZebraLibrary
  14 {
  15     /// <summary>
  16     /// 斑马打印助手,支持LPT/COM/USB/TCP四种模式,适用于标签、票据、条码打印。
  17     /// </summary>
  18     public static class ZebraPrintHelper
  19     {
  20         #region 定义API方法
  21 
  22         #region 写打印口(LPT)方法
  23         private const short FILE_ATTRIBUTE_NORMAL = 0x80;
  24         private const short INVALID_HANDLE_VALUE = -1;
  25         private const uint GENERIC_READ = 0x80000000;
  26         private const uint GENERIC_WRITE = 0x40000000;
  27         private const uint CREATE_NEW = 1;
  28         private const uint CREATE_ALWAYS = 2;
  29         private const uint OPEN_EXISTING = 3;
  30         [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  31         private static extern SafeFileHandle CreateFile(string strFileName,
  32             uint dwDesiredAccess,
  33             uint dwShareMode,
  34             IntPtr intptrSecurityAttributes,
  35             uint dwCreationDisposition,
  36             uint dwFlagsAndAttributes,
  37             IntPtr intptrTemplateFile);
  38         #endregion
  39 
  40         [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  41         public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string printerName, out IntPtr intptrPrinter, IntPtr intptrPrintDocument);
  42 
  43         [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  44         public static extern bool ClosePrinter(IntPtr intptrPrinter);
  45 
  46         [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  47         public static extern bool StartDocPrinter(IntPtr intptrPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DocInfo docInfo);
  48 
  49         [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  50         public static extern bool EndDocPrinter(IntPtr intptrPrinter);
  51 
  52         [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  53         public static extern bool StartPagePrinter(IntPtr intptrPrinter);
  54 
  55         [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  56         public static extern bool EndPagePrinter(IntPtr intptrPrinter);
  57 
  58         [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  59         public static extern bool WritePrinter(IntPtr intptrPrinter, IntPtr intptrBytes, Int32 count, out Int32 written);
  60         #endregion  
  61  
  62         #region 定义私有字段
  63 
  64         /// <summary>  
  65         /// 线程锁,防止多线程调用。  
  66         /// </summary>  
  67         private static object SyncRoot = new object();
  68 
  69         /// <summary>  
  70         /// 字节流传递时采用的字符编码  
  71         /// </summary>  
  72         private static readonly Encoding TransferFormat = Encoding.GetEncoding("iso-8859-1");
  73 
  74         #endregion
  75 
  76         #region 定义属性
  77         public static int Port { get; set; }
  78         public static string PrinterName { get; set; }
  79         public static bool IsWriteLog { get; set; }
  80         public static DeviceType PrinterType { get; set; }
  81         public static ProgrammingLanguage PrinterProgrammingLanguage { get; set; }
  82 
  83         public static float TcpLabelMaxHeightCM { get; set; }
  84         public static int TcpPrinterDPI { get; set; }
  85         public static string TcpIpAddress { get; set; }
  86         public static int TcpPort { get; set; }
  87         public static int Copies { get; set; }  
  88 
  89         /// <summary>  
  90         /// 日志保存目录,WEB应用注意不能放在BIN目录下。  
  91         /// </summary>  
  92         public static string LogsDirectory { get; set; }
  93 
  94         private static byte[] GraphBuffer { get; set; }
  95         private static int GraphWidth { get; set; }
  96         private static int GraphHeight { get; set; }
  97 
  98         private static int RowSize
  99         {
 100             get
 101             {
 102                 return (((GraphWidth) + 31) >> 5) << 2;
 103             }
 104         }
 105 
 106         private static int RowRealBytesCount
 107         {
 108             get
 109             {
 110                 if ((GraphWidth % 8) > 0)
 111                 {
 112                     return GraphWidth / 8 + 1;
 113                 }
 114                 else
 115                 {
 116                     return GraphWidth / 8;
 117                 }
 118             }
 119         }
 120         #endregion  
 121 
 122         #region 静态构造方法
 123         static ZebraPrintHelper()
 124         {
 125             GraphBuffer = new byte[0];
 126             IsWriteLog = false;
 127             LogsDirectory = "logs";
 128         }
 129         #endregion
 130 
 131         #region 定义发送原始数据到打印机的方法
 132         private static bool SendBytesToPrinter(string printerName, IntPtr intptrBytes, Int32 count)
 133         {
 134             Int32 error = 0, written = 0;
 135             IntPtr intptrPrinter = new IntPtr(0);
 136             DocInfo docInfo = new DocInfo();
 137             bool bSuccess = false;
 138 
 139             docInfo.DocName = ".NET RAW Document";
 140             docInfo.DataType = "RAW";
 141 
 142             // Open the printer.  
 143             if (OpenPrinter(printerName.Normalize(), out intptrPrinter, IntPtr.Zero))
 144             {
 145                 // Start a document.  
 146                 if (StartDocPrinter(intptrPrinter, 1, docInfo))
 147                 {
 148                     // Start a page.  
 149                     if (StartPagePrinter(intptrPrinter))
 150                     {
 151                         // Write your bytes.  
 152                         bSuccess = WritePrinter(intptrPrinter, intptrBytes, count, out written);
 153                         EndPagePrinter(intptrPrinter);
 154                     }
 155                     EndDocPrinter(intptrPrinter);
 156                 }
 157                 ClosePrinter(intptrPrinter);
 158             }
 159             // If you did not succeed, GetLastError may give more information  
 160             // about why not.  
 161             if (bSuccess == false)
 162             {
 163                 error = Marshal.GetLastWin32Error();
 164             }
 165             return bSuccess;
 166         }
 167 
 168         public static bool SendFileToPrinter(string printerName, string fileName)
 169         {
 170             // Open the file.  
 171             FileStream fs = new FileStream(fileName, FileMode.Open);
 172             // Create a BinaryReader on the file.  
 173             BinaryReader br = new BinaryReader(fs);
 174             // Dim an array of bytes big enough to hold the file\'s contents.  
 175             Byte[] bytes = new Byte[fs.Length];
 176             bool bSuccess = false;
 177             // Your unmanaged pointer.  
 178             IntPtr pUnmanagedBytes = new IntPtr(0);
 179             int nLength;
 180 
 181             nLength = Convert.ToInt32(fs.Length);
 182             // Read the contents of the file into the array.  
 183             bytes = br.ReadBytes(nLength);
 184             // Allocate some unmanaged memory for those bytes.  
 185             pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
 186             // Copy the managed byte array into the unmanaged array.  
 187             Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
 188             // Send the unmanaged bytes to the printer.  
 189             bSuccess = SendBytesToPrinter(printerName, pUnmanagedBytes, nLength);
 190             // Free the unmanaged memory that you allocated earlier.  
 191             Marshal.FreeCoTaskMem(pUnmanagedBytes);
 192             return bSuccess;
 193         }
 194 
 195         public static bool SendBytesToPrinter(string printerName, byte[] bytes)
 196         {
 197             bool bSuccess = false;
 198             IntPtr pUnmanagedBytes = new IntPtr(0);
 199             int nLength = bytes.Length;
 200             // Allocate some unmanaged memory for those bytes.  
 201             pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
 202             // Copy the managed byte array into the unmanaged array.  
 203             Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
 204             // Send the unmanaged bytes to the printer.  
 205             bSuccess = SendBytesToPrinter(printerName, pUnmanagedBytes, nLength);
 206             // Free the unmanaged memory that you allocated earlier.  
 207             Marshal.FreeCoTaskMem(pUnmanagedBytes);
 208             return bSuccess;
 209         }
 210 
 211         public static bool SendStringToPrinter(string printerName, string text)
 212         {
 213             IntPtr pBytes;
 214             Int32 dwCount;
 215             // How many characters are in the string?  
 216             dwCount = (text.Length + 1) * Marshal.SystemMaxDBCSCharSize;
 217             // Assume that the printer is expecting ANSI text, and then convert  
 218             // the string to ANSI text.  
 219             pBytes = Marshal.StringToCoTaskMemAnsi(text);
 220             // Send the converted ANSI string to the printer.  
 221             SendBytesToPrinter(printerName, pBytes, dwCount);
 222             Marshal.FreeCoTaskMem(pBytes);
 223             return true;
 224         }
 225         #endregion  
 226 
 227         #region 日志记录方法
 228         private static void WriteLog(string text, LogType logType)
 229         {
 230             string endTag = string.Format("\\r\\n{0}\\r\\n", new string(\'=\', 80));
 231             string path = string.Format("{0}\\\\{1}-{2}.log", LogsDirectory, DateTime.Now.ToString("yyyy-MM-dd"), logType);
 232             if (!Directory.Exists(LogsDirectory))
 233             {
 234                 Directory.CreateDirectory(LogsDirectory);
 235             }
 236             if (logType == LogType.Error)
 237             {
 238                 File.AppendAllText(path, string.Format("{0}{1}", text, endTag), Encoding.Default);
 239             }
 240             if (logType == LogType.Print)
 241             {
 242                 if (text.StartsWith("N\\r\\nGW"))
 243                 {
 244                     using (FileStream fs = new FileStream(path, FileMode.Append))
 245                     {
 246                         byte[] bytes = TransferFormat.GetBytes(text);
 247                         byte[] tag = TransferFormat.GetBytes(endTag);
 248                         fs.Write(bytes, 0, bytes.Length);
 249                         fs.Write(tag, 0, tag.Length);
 250                         fs.Close();
 251                     }
 252                 }
 253                 else
 254 以上是关于C# EPL USB 指令打印的主要内容,如果未能解决你的问题,请参考以下文章

怎么向斑马条码打印机发送指令啊 usb接口

C#调用斑马打印机打印条码标签(支持COMLPTUSBTCP连接方式和ZPLEPLCPCL指令)

在linux上通过usb发送原始数据

EPL - 控制 128 条码长度

如何将打印指令保存在电脑上,最后USB连接斑马打印机打印条码

ESim(EPL 模拟器):不知道如何将数据发送到打印机