C# 小票打印機 ESC命令行方式打印

        private void btnPrinter_Click(object sender, EventArgs e)
        {

           #region ESC 熱敏圖像點陣像素點讀取打印

            //Bitmap bitmap = new Bitmap(@"D:\450X100.bmp");
            //NetPOSPrinter netPOSPrinter = new NetPOSPrinter();
            //netPOSPrinter.PrintPic(bitmap);

            #endregion

            #region EPL USB 打印
            //Bitmap img = new Bitmap(@"D:\450X100.bmp");
            //ZebraPrintHelper.PrinterType = DeviceType.DRV;
            //ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.EPL;
            //ZebraPrintHelper.PrinterName = "ZDesigner GK888t (EPL)";
            //byte[] imgByte = ImageToByte.ImgToByt(img);
            //ZebraPrintHelper.PrintGraphics(imgByte);

            #endregion

            #region ZPL II 打印指令
            //^XA^CFD
            //^POI
            //^LH330,10
            //^FO50,50
            //^FDSMARTDIGITAL^FS
            //^FO50,75
            //^FD021-51871630^FS
            //^XZ

            //StringBuilder sb = new StringBuilder();
            //sb.Append("^XA^CFD");
            //sb.Append("^POI");
            //sb.Append("^LH330,10");
            //sb.Append("^FO50,50");
            //sb.Append("^FDSMARTDIGITAL^FS");
            //sb.Append("^FO50,75");
            //sb.Append("^FD021-51871630^FS");
            //sb.Append("^XZ");

            //byte[] cmd = Encoding.Default.GetBytes(sb.ToString());

            #endregion

            #region EPL USB 指令打印
            ZebraPrintHelper.PrinterProgrammingLanguage = ProgrammingLanguage.EPL;
            ZebraPrintHelper.PrinterName = "ZDesigner GK888t (EPL)";
            ZebraPrintHelper.PrinterType = DeviceType.DRV;
            
            string cmd = "N" + "\r\n" +
                "Q400,025" + "\n\r" +
                "A140,45,0,8,1,1,N,\"古典黃芥沫調(diào)味醬\"" + "\r\n" +
                "A140,90,0,8,1,1,N,\"規(guī)格:\"" + "\r\n" +
                "A240,95,0,4,1,1,N,\"" + "100ML/瓶" + "\"" + "\r\n" +
                "A140,135,0,8,1,1,N,\"生產(chǎn)日期:\"" + "\r\n" +
                "A300,140,0,4,1,1,N,\"" + "2015-10-02" + "\"" + "\r\n" +
                "B140,180,0,1,3,2,100,B,\"" + "8957891234567895789588535" + "\"" + "\r\n" +
                "P1" + "\r\n";

            ZebraPrintHelper.PrintCommand(cmd.ToString());
            #endregion
        } using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;

namespace ZebraLibrary
{
    /// <summary>
    /// 斑馬打印助手左刽,支持LPT/COM/USB/TCP四種模式,適用于標簽酌媒、票據(jù)悠反、條碼打印。
    /// </summary>
    public static class ZebraPrintHelper
    {
        #region 定義API方法

        #region 寫打印口(LPT)方法
        private const short FILE_ATTRIBUTE_NORMAL = 0x80;
        private const short INVALID_HANDLE_VALUE = -1;
        private const uint GENERIC_READ = 0x80000000;
        private const uint GENERIC_WRITE = 0x40000000;
        private const uint CREATE_NEW = 1;
        private const uint CREATE_ALWAYS = 2;
        private const uint OPEN_EXISTING = 3;
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern SafeFileHandle CreateFile(string strFileName,
            uint dwDesiredAccess,
            uint dwShareMode,
            IntPtr intptrSecurityAttributes,
            uint dwCreationDisposition,
            uint dwFlagsAndAttributes,
            IntPtr intptrTemplateFile);
        #endregion

        [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string printerName, out IntPtr intptrPrinter, IntPtr intptrPrintDocument);

        [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool ClosePrinter(IntPtr intptrPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartDocPrinter(IntPtr intptrPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DocInfo docInfo);

        [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndDocPrinter(IntPtr intptrPrinter);

        [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool StartPagePrinter(IntPtr intptrPrinter);

        [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool EndPagePrinter(IntPtr intptrPrinter);

        [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool WritePrinter(IntPtr intptrPrinter, IntPtr intptrBytes, Int32 count, out Int32 written);
        #endregion  
 
        #region 定義私有字段

        /// <summary>  
        /// 線程鎖馍佑,防止多線程調(diào)用斋否。  
        /// </summary>  
        private static object SyncRoot = new object();

        /// <summary>  
        /// 字節(jié)流傳遞時采用的字符編碼  
        /// </summary>  
        private static readonly Encoding TransferFormat = Encoding.GetEncoding("iso-8859-1");

        #endregion

        #region 定義屬性
        public static int Port { get; set; }
        public static string PrinterName { get; set; }
        public static bool IsWriteLog { get; set; }
        public static DeviceType PrinterType { get; set; }
        public static ProgrammingLanguage PrinterProgrammingLanguage { get; set; }

        public static float TcpLabelMaxHeightCM { get; set; }
        public static int TcpPrinterDPI { get; set; }
        public static string TcpIpAddress { get; set; }
        public static int TcpPort { get; set; }
        public static int Copies { get; set; }  

        /// <summary>  
        /// 日志保存目錄,WEB應用注意不能放在BIN目錄下拭荤。  
        /// </summary>  
        public static string LogsDirectory { get; set; }

        private static byte[] GraphBuffer { get; set; }
        private static int GraphWidth { get; set; }
        private static int GraphHeight { get; set; }

        private static int RowSize
        {
            get
            {
                return (((GraphWidth) + 31) >> 5) << 2;
            }
        }

        private static int RowRealBytesCount
        {
            get
            {
                if ((GraphWidth % 8) > 0)
                {
                    return GraphWidth / 8 + 1;
                }
                else
                {
                    return GraphWidth / 8;
                }
            }
        }
        #endregion  

        #region 靜態(tài)構造方法
        static ZebraPrintHelper()
        {
            GraphBuffer = new byte[0];
            IsWriteLog = false;
            LogsDirectory = "logs";
        }
        #endregion

        #region 定義發(fā)送原始數(shù)據(jù)到打印機的方法
        private static bool SendBytesToPrinter(string printerName, IntPtr intptrBytes, Int32 count)
        {
            Int32 error = 0, written = 0;
            IntPtr intptrPrinter = new IntPtr(0);
            DocInfo docInfo = new DocInfo();
            bool bSuccess = false;

            docInfo.DocName = ".NET RAW Document";
            docInfo.DataType = "RAW";

            // Open the printer.  
            if (OpenPrinter(printerName.Normalize(), out intptrPrinter, IntPtr.Zero))
            {
                // Start a document.  
                if (StartDocPrinter(intptrPrinter, 1, docInfo))
                {
                    // Start a page.  
                    if (StartPagePrinter(intptrPrinter))
                    {
                        // Write your bytes.  
                        bSuccess = WritePrinter(intptrPrinter, intptrBytes, count, out written);
                        EndPagePrinter(intptrPrinter);
                    }
                    EndDocPrinter(intptrPrinter);
                }
                ClosePrinter(intptrPrinter);
            }
            // If you did not succeed, GetLastError may give more information  
            // about why not.  
            if (bSuccess == false)
            {
                error = Marshal.GetLastWin32Error();
            }
            return bSuccess;
        }

        public static bool SendFileToPrinter(string printerName, string fileName)
        {
            // Open the file.  
            FileStream fs = new FileStream(fileName, 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(printerName, pUnmanagedBytes, nLength);
            // Free the unmanaged memory that you allocated earlier.  
            Marshal.FreeCoTaskMem(pUnmanagedBytes);
            return bSuccess;
        }

        public static bool SendBytesToPrinter(string printerName, byte[] bytes)
        {
            bool bSuccess = false;
            IntPtr pUnmanagedBytes = new IntPtr(0);
            int nLength = bytes.Length;
            // 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(printerName, pUnmanagedBytes, nLength);
            // Free the unmanaged memory that you allocated earlier.  
            Marshal.FreeCoTaskMem(pUnmanagedBytes);
            return bSuccess;
        }

        public static bool SendStringToPrinter(string printerName, string text)
        {
            IntPtr pBytes;
            Int32 dwCount;
            // How many characters are in the string?  
            dwCount = (text.Length + 1) * Marshal.SystemMaxDBCSCharSize;
            // Assume that the printer is expecting ANSI text, and then convert  
            // the string to ANSI text.  
            pBytes = Marshal.StringToCoTaskMemAnsi(text);
            // Send the converted ANSI string to the printer.  
            SendBytesToPrinter(printerName, pBytes, dwCount);
            Marshal.FreeCoTaskMem(pBytes);
            return true;
        }
        #endregion  

        #region 日志記錄方法
        private static void WriteLog(string text, LogType logType)
        {
            string endTag = string.Format("\r\n{0}\r\n", new string('=', 80));
            string path = string.Format("{0}\\{1}-{2}.log", LogsDirectory, DateTime.Now.ToString("yyyy-MM-dd"), logType);
            if (!Directory.Exists(LogsDirectory))
            {
                Directory.CreateDirectory(LogsDirectory);
            }
            if (logType == LogType.Error)
            {
                File.AppendAllText(path, string.Format("{0}{1}", text, endTag), Encoding.Default);
            }
            if (logType == LogType.Print)
            {
                if (text.StartsWith("N\r\nGW"))
                {
                    using (FileStream fs = new FileStream(path, FileMode.Append))
                    {
                        byte[] bytes = TransferFormat.GetBytes(text);
                        byte[] tag = TransferFormat.GetBytes(endTag);
                        fs.Write(bytes, 0, bytes.Length);
                        fs.Write(tag, 0, tag.Length);
                        fs.Close();
                    }
                }
                else
                {
                    File.AppendAllText(path, string.Format("{0}{1}", text, endTag), Encoding.Default);
                }
            }
        }

        private static void WriteLog(byte[] bytes, LogType logType)
        {
            string endTag = string.Format("\r\n{0}\r\n", new string('=', 80));
            string path = string.Format("{0}\\{1}-{2}.log", LogsDirectory, DateTime.Now.ToString("yyyy-MM-dd"), logType);
            if (!Directory.Exists(LogsDirectory))
            {
                Directory.CreateDirectory(LogsDirectory);
            }
            if (logType == LogType.Error)
            {
                File.AppendAllText(path, string.Format("{0}{1}", Encoding.Default.GetString(bytes), endTag), Encoding.Default);
            }
            if (logType == LogType.Print)
            {
                string transferFormat = TransferFormat.GetString(bytes);
                if (transferFormat.StartsWith("N\r\nGW"))
                {
                    using (FileStream fs = new FileStream(path, FileMode.Append))
                    {
                        byte[] tag = TransferFormat.GetBytes(endTag);
                        fs.Write(bytes, 0, bytes.Length);
                        fs.Write(tag, 0, tag.Length);
                        fs.Close();
                    }
                }
                else
                {
                    File.AppendAllText(path, string.Format("{0}{1}", Encoding.Default.GetString(bytes), endTag), Encoding.Default);
                }
            }
        }
        #endregion  

        #region 封裝方法茵臭,方便調(diào)用。
        public static bool PrintWithCOM(string cmd, int port, bool isWriteLog)
        {
            PrinterType = DeviceType.COM;
            Port = port;
            IsWriteLog = isWriteLog;
            return PrintCommand(cmd);
        }

        public static bool PrintWithCOM(byte[] bytes, int port, bool isWriteLog, ProgrammingLanguage progLanguage)
        {
            PrinterType = DeviceType.COM;
            Port = port;
            IsWriteLog = isWriteLog;
            PrinterProgrammingLanguage = progLanguage;
            return PrintGraphics(bytes);
        }

        public static bool PrintWithLPT(string cmd, int port, bool isWriteLog)
        {
            PrinterType = DeviceType.LPT;
            Port = port;
            IsWriteLog = isWriteLog;
            return PrintCommand(cmd);
        }

        public static bool PrintWithLPT(byte[] bytes, int port, bool isWriteLog, ProgrammingLanguage progLanguage)
        {
            PrinterType = DeviceType.LPT;
            Port = port;
            IsWriteLog = isWriteLog;
            PrinterProgrammingLanguage = progLanguage;
            return PrintGraphics(bytes);
        }

        public static bool PrintWithDRV(string cmd, string printerName, bool isWriteLog)
        {
            PrinterType = DeviceType.DRV;
            PrinterName = printerName;
            IsWriteLog = isWriteLog;
            return PrintCommand(cmd);
        }

        public static bool PrintWithDRV(byte[] bytes, string printerName, bool isWriteLog, ProgrammingLanguage progLanguage)
        {
            PrinterType = DeviceType.DRV;
            PrinterName = printerName;
            IsWriteLog = isWriteLog;
            PrinterProgrammingLanguage = progLanguage;
            return PrintGraphics(bytes);
        }
        #endregion  

        #region 打印ZPL舅世、EPL指令
        public static bool PrintCommand(string cmd)
        {
            lock (SyncRoot)
            {
                bool result = false;
                try
                {
                    switch (PrinterType)
                    {
                        case DeviceType.COM:
                            result = comPrint(Encoding.Default.GetBytes(cmd));
                            break;
                        case DeviceType.LPT:
                            result = lptPrint(Encoding.Default.GetBytes(cmd));
                            break;
                        case DeviceType.DRV:
                            result = drvPrint(Encoding.Default.GetBytes(cmd));
                            break;
                        case DeviceType.TCP:
                            result = tcpPrint(Encoding.Default.GetBytes(cmd));
                            break;  
                    }
                    if (!string.IsNullOrEmpty(cmd) && IsWriteLog)
                    {
                        WriteLog(cmd, LogType.Print);
                    }
                }
                catch (Exception ex)
                {
                    //記錄日志  
                    if (IsWriteLog)
                    {
                        WriteLog(string.Format("{0} => {1}\r\n{2}", DateTime.Now, ex.Message, ex), LogType.Error);
                    }
                }
                finally
                {
                    GraphBuffer = new byte[0];
                }
                return result;
            }
        }
        #endregion  

        #region 打印圖像字節(jié)流
        public static bool PrintGraphics(byte[] graph)
        {
            lock (SyncRoot)
            {
                bool result = false;
                try
                {
                    GraphBuffer = graph;
                    byte[] cmdBytes = new byte[0];
                    if (PrinterProgrammingLanguage == ProgrammingLanguage.ZPL)
                    {
                        cmdBytes = getZPLBytes();
                    }
                    if (PrinterProgrammingLanguage == ProgrammingLanguage.EPL)
                    {
                        cmdBytes = getEPLBytes();
                    }
                    if (PrinterProgrammingLanguage == ProgrammingLanguage.CPCL)
                    {
                        cmdBytes = getCPCLBytes();
                    }
                    switch (PrinterType)
                    {
                        case DeviceType.COM:
                            result = comPrint(cmdBytes);
                            break;
                        case DeviceType.LPT:
                            result = lptPrint(cmdBytes);
                            break;
                        case DeviceType.DRV:
                            result = drvPrint(cmdBytes);
                            break;
                        case DeviceType.TCP:
                            result = tcpPrint(cmdBytes);
                            break;  
                    }
                    if (cmdBytes.Length > 0 && IsWriteLog)
                    {
                        WriteLog(cmdBytes, LogType.Print);
                    }
                }
                catch (Exception ex)
                {
                    //記錄日志  
                    if (IsWriteLog)
                    {
                        WriteLog(string.Format("{0} => {1}\r\n{2}", DateTime.Now, ex.Message, ex), LogType.Error);
                    }
                }
                finally
                {
                    GraphBuffer = new byte[0];
                }
                return result;
            }
        }
        #endregion  

        #region COM/LPT/DRV三種模式打印方法
        private static bool drvPrint(byte[] cmdBytes)
        {
            bool result = false;
            try
            {
                if (!string.IsNullOrEmpty(PrinterName))
                {
                    result = SendBytesToPrinter(PrinterName, cmdBytes);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        private static bool comPrint(byte[] cmdBytes)
        {
            bool result = false;
            SerialPort com = new SerialPort(string.Format("{0}{1}", PrinterType, Port), 9600, Parity.None, 8, StopBits.One);
            try
            {
                com.Open();
                com.Write(cmdBytes, 0, cmdBytes.Length);
                result = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (com.IsOpen)
                {
                    com.Close();
                }
            }
            return result;
        }

        private static bool lptPrint(byte[] cmdBytes)
        {
            bool result = false;
            FileStream fileStream = null;
            StreamWriter streamWriter = null;
            SafeFileHandle handle = null;
            try
            {
                handle = CreateFile(string.Format("{0}{1}", PrinterType, Port), GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                if (!handle.IsInvalid)
                {
                    fileStream = new FileStream(handle, FileAccess.ReadWrite);
                    streamWriter = new StreamWriter(fileStream, Encoding.Default);
                    streamWriter.Write(cmdBytes);
                    result = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream = null;
                }
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (handle != null)
                {
                    handle.Close();
                    handle = null;
                }
            }
            return result;
        }

        private static bool tcpPrint(byte[] cmdBytes) 
        {
            bool result = false;
            TcpClient tcp = null;
            try
            {
                IPAddress ip = IPAddress.Parse(TcpIpAddress);
                IPEndPoint iport = new IPEndPoint(ip, TcpPort);//9100為小票打印機指定端口
                tcp = new TcpClient(iport);
                tcp.SendTimeout = 1000;
                tcp.ReceiveTimeout = 1000;
                if (tcp.Connected)
                {
                    tcp.Client.Send(cmdBytes);
                    result = true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("打印失敗旦委,請檢查打印機或網(wǎng)絡設置。", ex);
            }
            finally
            {
                if (tcp != null)
                {
                    if (tcp.Client != null)
                    {
                        tcp.Client.Close();
                        tcp.Client = null;
                    }
                    tcp.Close();
                    tcp = null;
                }
            }
            return result;  
        }
        #endregion  

        #region 生成ZPL圖像打印指令
        private static byte[] getZPLBytes()
        {
            byte[] result = new byte[0];
            byte[] bmpData = getBitmapData();
            string textBitmap = string.Empty;
            string textHex = BitConverter.ToString(bmpData).Replace("-", string.Empty);
            for (int i = 0; i < GraphHeight; i++)
            {
                textBitmap += textHex.Substring(i * RowRealBytesCount * 2, RowRealBytesCount * 2) + "\r\n";
            }
            string text = string.Format("~DGR:IMAGE.GRF,{0},{1},\r\n{2}^XGR:IMAGE.GRF,1,1^FS\r\n^IDR:IMAGE.GRF\r\n",
                GraphHeight * RowRealBytesCount,
                RowRealBytesCount,
                textBitmap);
            result = Encoding.Default.GetBytes(text);
            return result;
        }
        #endregion

        #region 生成EPL圖像打印指令
        private static byte[] getEPLBytes()
        {
            byte[] result = new byte[0];
            byte[] buffer = getBitmapData();
            string text = string.Format("N\r\nGW{0},{1},{2},{3},{4}\r\nP\r\n",
                0,
                0,
                RowRealBytesCount,
                GraphHeight,
                TransferFormat.GetString(buffer));
            result = TransferFormat.GetBytes(text);
            return result;
        }
        #endregion  

        #region 生成CPCL圖像打印指令
        public static byte[] getCPCLBytes()
        {
            //GRAPHICS Commands  
            //Bit-mapped graphics can be printed by using graphics commands. ASCII hex (hexadecimal) is  
            //used for expanded graphics data (see example). Data size can be reduced to one-half by utilizing the  
            //COMPRESSED-GRAPHICS commands with the equivalent binary character(s) of the hex data. When  
            //using CG, a single 8 bit character is sent for every 8 bits of graphics data. When using EG two characters  
            //(16 bits) are used to transmit 8 bits of graphics data, making EG only half as efficient. Since this data is  
            //character data, however, it can be easier to handle and transmit than binary data.  
            //Format:  
            //{command} {width} {height} {x} {y} {data}  
            //where:  
            //{command}: Choose from the following:  
            //EXPANDED-GRAPHICS (or EG): Prints expanded graphics horizontally.  
            //VEXPANDED-GRAPHICS (or VEG): Prints expanded graphics vertically.  
            //COMPRESSED-GRAPHICS (or CG): Prints compressed graphics horizontally.  
            //VCOMPRESSED-GRAPHICS (or VCG): Prints compressed graphics vertically.  
            //{width}: Byte-width of image.  
            //{height} Dot-height of image.  
            //{x}: Horizontal starting position.  
            //{y}: Vertical starting position.  
            //{data}: Graphics data.  
            //Graphics command example  
            //Input:  
            //! 0 200 200 210 1  
            //EG 2 16 90 45 F0F0F0F0F0F0F0F00F0F0F0F0F0F0F0F  
            //F0F0F0F0F0F0F0F00F0F0F0F0F0F0F0F  
            //FORM  
            //PRINT  

            byte[] bmpData = getBitmapData();
            int bmpDataLength = bmpData.Length;
            for (int i = 0; i < bmpDataLength; i++)
            {
                bmpData[i] ^= 0xFF;
            }
            string textHex = BitConverter.ToString(bmpData).Replace("-", string.Empty);
            string text = string.Format("! {0} {1} {2} {3} {4}\r\nEG {5} {6} {7} {8} {9}\r\nFORM\r\nPRINT\r\n",
                0, //水平偏移量  
                TcpPrinterDPI, //橫向DPI  
                TcpPrinterDPI, //縱向DPI  
                (int)(TcpLabelMaxHeightCM / 2.54f * TcpPrinterDPI), //標簽最大像素高度=DPI*標簽紙高度(英寸)  
                Copies, //份數(shù)  
                RowRealBytesCount, //圖像的字節(jié)寬度  
                GraphHeight, //圖像的像素高度  
                0, //橫向的開始位置  
                0, //縱向的開始位置  
                textHex
                );
            return Encoding.UTF8.GetBytes(text);
        }
        #endregion

        #region 獲取單色位圖數(shù)據(jù)
        /// <summary>  
        /// 獲取單色位圖數(shù)據(jù)(1bpp)雏亚,不含文件頭缨硝、信息頭丙躏、調(diào)色板三類數(shù)據(jù)步氏。  
        /// </summary>  
        /// <returns></returns>  
        private static byte[] getBitmapData()
        {
            MemoryStream srcStream = new MemoryStream();
            MemoryStream dstStream = new MemoryStream();
            Bitmap srcBmp = null;
            Bitmap dstBmp = null;
            byte[] srcBuffer = null;
            byte[] dstBuffer = null;
            byte[] result = null;
            try
            {
                srcStream = new MemoryStream(GraphBuffer);
                srcBmp = Bitmap.FromStream(srcStream) as Bitmap;
                srcBuffer = srcStream.ToArray();
                GraphWidth = srcBmp.Width;
                GraphHeight = srcBmp.Height;
                dstBmp = srcBmp.Clone(new Rectangle(0, 0, srcBmp.Width, srcBmp.Height), PixelFormat.Format1bppIndexed);
                dstBmp.Save(dstStream, ImageFormat.Bmp);
                dstBuffer = dstStream.ToArray();

                int bfSize = BitConverter.ToInt32(dstBuffer, 2);
                int bfOffBits = BitConverter.ToInt32(dstBuffer, 10);
                int bitmapDataLength = bfSize - bfOffBits;
                result = new byte[GraphHeight * RowRealBytesCount];

                //讀取時需要反向讀取每行字節(jié)實現(xiàn)上下翻轉(zhuǎn)的效果,打印機打印順序需要這樣讀取眠副。  
                for (int i = 0; i < GraphHeight; i++)
                {
                    Array.Copy(dstBuffer, bfOffBits + (GraphHeight - 1 - i) * RowSize, result, i * RowRealBytesCount, RowRealBytesCount);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (srcStream != null)
                {
                    srcStream.Dispose();
                    srcStream = null;
                }
                if (dstStream != null)
                {
                    dstStream.Dispose();
                    dstStream = null;
                }
                if (srcBmp != null)
                {
                    srcBmp.Dispose();
                    srcBmp = null;
                }
                if (dstBmp != null)
                {
                    dstBmp.Dispose();
                    dstBmp = null;
                }
            }
            return result;
        }
        #endregion  

        #region 擴展

        #region CPCL命令打印24位bmp
        private static string get24BitBmpData(string filePath)
        {
            Bitmap bmp = new Bitmap(filePath);
            byte[] bitArray = { 128, 64, 32, 16, 8, 4, 2, 1 };
            string imgTxt = "";
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
            BitmapData data = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            IntPtr firstPix = data.Scan0;

            int rowByteCount = bmp.Width * 3;
            int filledCount = data.Stride - rowByteCount;
            int bytes = data.Stride * data.Height;//Math.Ceiling((double)bmp.Width / 8)
            byte[] rgbValues = new byte[bytes];
            System.Runtime.InteropServices.Marshal.Copy(firstPix, rgbValues, 0, bytes);

            int printRowByteCount = Convert.ToInt32(Math.Ceiling((double)(bmp.Width) / 8));
            int printRowByteFillCount = 4 - (printRowByteCount % 4);
            //int bitFillCount = 8 - (bmp.Width % 8);
            byte[] printData = new byte[(printRowByteCount + printRowByteFillCount) * bmp.Height];

            int byteCount = 0;
            int bitCount = 0;
            int rowPoint = 0;
            for (int i = 0; i < rgbValues.Length; i += 3)
            {
                int rgbValue = rgbValues[i] + rgbValues[i + 1] + rgbValues[i + 2];
                if (rgbValue != (255 * 3))
                {
                    printData[byteCount] = Convert.ToByte(printData[byteCount] | bitArray[bitCount]);
                }
                if (bitCount == 7)
                {
                    bitCount = 0;
                    byteCount++;
                }
                else
                {
                    bitCount++;
                }
                if ((rowPoint + 3) == rowByteCount)
                {
                    rowPoint = 0;
                    if (bitCount > 0)
                    {
                        byteCount++;
                    }
                    bitCount = 0;
                    byteCount += printRowByteFillCount;
                    i = i + filledCount;
                }
                else
                {
                    rowPoint += 3;
                }
            }

            foreach (byte byteData in printData)
            {
                string hexStr = Convert.ToString(byteData, 16);
                if (hexStr.Length == 1)
                {
                    hexStr = '0' + hexStr;
                }
                imgTxt += hexStr;
            }
            bmp.UnlockBits(data);
            return imgTxt.ToUpper();
        }

        public static void Printer(string bitbmpPath) 
        {
            string CRNL = "\r\n";
            string imgTxt = get24BitBmpData(bitbmpPath);
            string cmddata = "! 0 200 200 300 1" + CRNL +
                            "EG " + 24 + " " + 50 + " 10 10 " + imgTxt + CRNL +
                            "FORM" + CRNL +
                            "PRINT" + CRNL;
            try
            {
                string ipAddress = "192.168.1.212";
                int port = 9100;

                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(ipAddress, port);

                // Write CPCL String to connection
                System.IO.StreamWriter writer =new System.IO.StreamWriter(client.GetStream());
                writer.Write(cmddata);
                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();
            }
            catch (Exception)
            {
                // Catch Exception
            }
        }
        #endregion

        #endregion
    }

    #region 定義設備類型枚舉
    public enum DeviceType
    {
        COM = 0,
        LPT = 1,
        DRV = 2,
        TCP = 3
    }
    #endregion

    #region 定義打印機指令類型枚舉
    public enum ProgrammingLanguage
    {
        ZPL = 0,
        EPL = 1,
        CPCL = 2
    }
    #endregion

    #region 定義日志類型枚舉
    public enum LogType
    {
        Print = 0,
        Error = 1
    }
    #endregion

    #region 定義打印文檔信息類
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class DocInfo
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public string DocName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string OutputFile;
        [MarshalAs(UnmanagedType.LPStr)]
        public string DataType;
    }
    #endregion

    #region 定義圖像設備信息類
    public class DeviceInfo
    {
        #region 屬性說明
        /* 
        ColorDepth  
            圖像輸出支持的顏色范圍的像素深度。有效值為 1宜岛、4长踊、8、24 和 32萍倡。默認值為 24身弊。僅對 TIFF 呈現(xiàn)支持 ColorDepth,對于其他圖像輸出格式報表服務器將忽略此設置列敲。 
 
        注意:  
        對于此版本的 SQL Server阱佛,此設置的值將被忽略,且通常將 TIFF 圖像呈現(xiàn)為 24 位戴而。 
  
        Columns  
            要為報表設置的列數(shù)凑术。此值將覆蓋報表的原始設置。 
  
        ColumnSpacing  
            要為報表設置的列間距填硕。此值將覆蓋報表的原始設置麦萤。 
  
        DpiX  
            輸出設備在 X 方向的分辨率鹿鳖。默認值為 96扁眯。 
  
        DpiY  
            輸出設備在 Y 方向的分辨率。默認值為 96翅帜。 
  
        EndPage  
            要呈現(xiàn)的報表的最后一頁姻檀。默認值為 StartPage 的值。 
  
        MarginBottom  
            要為報表設置的下邊距值涝滴,以英寸為單位绣版。您必須包含一個整數(shù)或小數(shù)值,后跟“in”(例如歼疮,1in)杂抽。此值將覆蓋報表的原始設置。 
  
        MarginLeft  
            要為報表設置的左邊距值韩脏,以英寸為單位缩麸。您必須包含一個整數(shù)或小數(shù)值,后跟“in”(例如赡矢,1in)杭朱。此值將覆蓋報表的原始設置。 
  
        MarginRight  
            要為報表設置的右邊距值吹散,以英寸為單位弧械。您必須包含一個整數(shù)或小數(shù)值,后跟“in”(例如空民,1in)刃唐。此值將覆蓋報表的原始設置。 
  
        MarginTop  
            要為報表設置的上邊距值,以英寸為單位唁桩。您必須包含一個整數(shù)或小數(shù)值闭树,后跟“in”(例如,1in)荒澡。此值將覆蓋報表的原始設置报辱。 
  
        OutputFormat  
            圖形設備接口 (GDI) 支持的輸出格式之一:BMP、EMF单山、GIF碍现、JPEG、PNG 或 TIFF米奸。 
  
        PageHeight  
            要為報表設置的頁高昼接,以英寸為單位。您必須包含一個整數(shù)或小數(shù)值悴晰,后跟“in”(例如慢睡,11in)。此值將覆蓋報表的原始設置铡溪。 
  
        PageWidth  
            要為報表設置的頁寬漂辐,以英寸為單位。您必須包含一個整數(shù)或小數(shù)值棕硫,后跟“in”(例如髓涯,8.5in)。此值將覆蓋報表的原始設置哈扮。 
  
        StartPage  
            要呈現(xiàn)的報告的第一頁纬纪。值為 0 指示將呈現(xiàn)所有頁。默認值為 1滑肉。  
         */
        #endregion

        public enum GDIOutputFormat { BMP, EMF, GIF, JPEG, PNG, TIFF }

        public int ColorDepth { get; set; }
        public int Columns { get; set; }
        public int ColumnSpacing { get; set; }
        public int DpiX { get; set; }
        public int DpiY { get; set; }
        public int EndPage { get; set; }
        public int MarginBottom { get; set; }
        public int MarginLeft { get; set; }
        public int MarginRight { get; set; }
        public int MarginTop { get; set; }
        public GDIOutputFormat OutputFormat { get; set; }
        public int PageHeight { get; set; }
        public int PageWidth { get; set; }
        public int StartPage { get; set; }

        private const string xmlFormater = @"<DeviceInfo>  
                <ColorDepth>{0}</ColorDepth>  
                <Columns>{1}</Columns>  
                <ColumnSpacing>{2}</ColumnSpacing>  
                <DpiX>{3}</DpiX>  
                <DpiY>{4}</DpiY>  
                <EndPage>{5}</EndPage>  
                <MarginBottom>{6}</MarginBottom>  
                <MarginLeft>{7}</MarginLeft>  
                <MarginRight>{8}</MarginRight>  
                <MarginTop>{9}</MarginTop>  
                <OutputFormat>{10}</OutputFormat>  
                <PageHeight>{11}</PageHeight>  
                <PageWidth>{12}</PageWidth>  
                <StartPage>{13}</StartPage>  
                </DeviceInfo>";

        public DeviceInfo()
        {
            this.ColorDepth = 24;
            this.Columns = 0;
            this.StartPage = 1;
            this.EndPage = 1;
        }

        public string GetDeviceInfo()
        {
            string result = string.Format(xmlFormater,
                this.ColorDepth,
                this.Columns,
                this.ColumnSpacing,
                this.DpiX,
                this.DpiY,
                this.EndPage,
                this.MarginBottom,
                this.MarginLeft,
                this.MarginRight,
                this.MarginTop,
                this.OutputFormat,
                this.PageHeight,
                this.PageWidth,
                this.StartPage);
            return result;
        }

        public string GetDeviceInfoForImage()
        {
            string result = string.Format("<DeviceInfo><StartPage>{0}</StartPage><EndPage>{1}</EndPage><OutputFormat>{2}</OutputFormat><DpiX>{3}</DpiX><DpiY>{4}</DpiY></DeviceInfo>",
                this.StartPage,
                this.EndPage,
                this.OutputFormat,
                this.DpiX,
                this.DpiY);
            return result;
        }
    }
    #endregion
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末包各,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子靶庙,更是在濱河造成了極大的恐慌问畅,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件惶洲,死亡現(xiàn)場離奇詭異按声,居然都是意外死亡,警方通過查閱死者的電腦和手機恬吕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門签则,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人铐料,你說我怎么就攤上這事渐裂〔蜓” “怎么了?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵柒凉,是天一觀的道長族阅。 經(jīng)常有香客問我,道長膝捞,這世上最難降的妖魔是什么坦刀? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮蔬咬,結(jié)果婚禮上鲤遥,老公的妹妹穿的比我還像新娘。我一直安慰自己林艘,他們只是感情好盖奈,可當我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著狐援,像睡著了一般钢坦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上啥酱,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天爹凹,我揣著相機與錄音,去河邊找鬼懈涛。 笑死逛万,一個胖子當著我的面吹牛泳猬,可吹牛的內(nèi)容都是我干的批钠。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼得封,長吁一口氣:“原來是場噩夢啊……” “哼埋心!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起忙上,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤拷呆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后疫粥,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體茬斧,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年梗逮,在試婚紗的時候發(fā)現(xiàn)自己被綠了项秉。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡慷彤,死狀恐怖娄蔼,靈堂內(nèi)的尸體忽然破棺而出怖喻,到底是詐尸還是另有隱情,我是刑警寧澤岁诉,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布锚沸,位于F島的核電站,受9級特大地震影響涕癣,放射性物質(zhì)發(fā)生泄漏哗蜈。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一坠韩、第九天 我趴在偏房一處隱蔽的房頂上張望恬叹。 院中可真熱鬧,春花似錦同眯、人聲如沸绽昼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽硅确。三九已至,卻和暖如春明肮,著一層夾襖步出監(jiān)牢的瞬間菱农,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工柿估, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留循未,地道東北人。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓秫舌,卻偏偏與公主長得像的妖,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子足陨,可洞房花燭夜當晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容