博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用C#通过888-TT打印中文标签
阅读量:4006 次
发布时间:2019-05-24

本文共 8585 字,大约阅读时间需要 28 分钟。

        由于C#的String编码是unicode的(utf-16), 而888-TT则对中文字符认的是GBK,所以在打印前需要将utf16转为gbk.

private static byte[] utf16_gbk(string text)        {            //声明字符集               System.Text.Encoding utf16, gb2312;            //utf16               utf16 = System.Text.Encoding.GetEncoding("UTF-16");            //gb2312               gb2312 = System.Text.Encoding.GetEncoding("GBK");            byte[] lvbytes = utf16.GetBytes(text);            lvbytes = System.Text.Encoding.Convert(utf16, gb2312, lvbytes);            return lvbytes;        }
下面是rawprinterhelper的类, 通过它可以将原始内容直接输出至指定的打印机:

using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Drawing;using System.Drawing.Printing;using System.Windows.Forms;using System.Runtime.InteropServices;namespace ZPLPrinter{    class RawPrinterHelper    {        // 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 = "PLM/ZeBra 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 SendUtf8StringToPrinter(string szPrinterName, string szString)        {            // by default System.String is UTF-16 / Unicode            byte[] bytes = Encoding.Unicode.GetBytes(szString);            // convert this to UTF-8. This is a lossy conversion and you might lose some chars            bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, bytes);            int bCount = bytes.Length;            // allocate some unmanaged memory            IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(bCount);            // copy the byte[] into the memory pointer            System.Runtime.InteropServices.Marshal.Copy(bytes, 0, ptr, bCount);            // Send the converted byte[] to the printer.            SendBytesToPrinter(szPrinterName, ptr, bCount);            // free the unmanaged memory            System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr);            // it worked! Happy cry.            return true;        }        public static bool SendBufferToPrinter(string szPrinterName, byte[] pvBuffer)        {                        int bCount = pvBuffer.Length;            // allocate some unmanaged memory            IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(bCount);            // copy the byte[] into the memory pointer            System.Runtime.InteropServices.Marshal.Copy(pvBuffer, 0, ptr, bCount);            // Send the converted byte[] to the printer.            SendBytesToPrinter(szPrinterName, ptr, bCount);            // free the unmanaged memory            System.Runtime.InteropServices.Marshal.FreeCoTaskMem(ptr);            // it worked! Happy cry.            return true;        }        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);            //pBytes = Marshal.StringToCoTaskMemUni(szString);            // Send the converted ANSI string to the printer.            SendBytesToPrinter(szPrinterName, pBytes, dwCount);            Marshal.FreeCoTaskMem(pBytes);            return true;        }    }}
下面是调用例子:

private void button2_Click(object sender, EventArgs e)        {            String lvPrinter = config.getValue("setting", "printer", "");            String lvStr = "\nN\nA10,0,0,8,1,1,N,\"1不良现象不良现象不2\"\nP\n";            byte[] lvBuffer = utf16_gbk(lvStr);           // File.WriteAllBytes("d:\\temp\\a.txt", lvBuffer);            RawPrinterHelper.SendBufferToPrinter(lvPrinter, lvBuffer);        }

转载地址:http://fzkfi.baihongyu.com/

你可能感兴趣的文章
Hashtable和HashMap的区别
查看>>
深入MySQL数据库的索引
查看>>
wml表单提交
查看>>
Log4J的配置详解
查看>>
JSP中EL表达式无效问题
查看>>
java中关于时间日期操作的常用函数
查看>>
用Eclipse MyEclipse WebLogic8.1开发第一个Web程序
查看>>
HTTP深入浅出
查看>>
http协议技术资料
查看>>
MyEclipse安装aptana插件的问题
查看>>
Android环境搭建_转载
查看>>
JS操作SELECT表单大全,赋默认值,取值,增,删等
查看>>
浅谈BigDecimal类在电子商务中至关重要的地位!
查看>>
输出的数字的格式DecimalFormat的方法用途
查看>>
程序员的激情其实是一种痛苦
查看>>
如何使用spring的作用域:
查看>>
Tomcat DBCP 连接池参数说明
查看>>
hibernate集合映射inverse和cascade详解
查看>>
Android自定义控件系列一:如何测量控件尺寸
查看>>
Android自定义控件系列二:如何自定义属性
查看>>