繁体   English   中英

通过C#.NET将ZPL打印到Zebra打印机

[英]Print ZPL to Zebra Printer via C#.NET

我正在建立一个网站,该网站会将ZPL代码打印到Zebra打印机“ 140XiIII”上。 具体如下:

  1. 打印机通过并行端口连接到计算机。

  2. 打印机未连接到网络。

  3. 网站管理员希望尽可能避免使用Javascript,而应专注于C#。

我曾尝试使用.NET代码中的代码将ZPL发送到Zebra打印机 ,并声明它将在任何端口上运行。 我遍历代码,没有任何错误,但是也没有任何内容发送到打印机。

我试图破译和使用InpOut32 / 64 DLL,尽管这比我微不足道的学习所能理解的更为复杂。

其他选项要么需要将打印机连接到网络,要么已过时,并且由于不再在Windows代码中而不再是一个选项。

谢谢。

我建议尝试以下方法:

  • 登录服务器,最好以将服务设置为运行用户的身份登录。
  • 确保您的Zebra打印机作为本地打印机安装,并且打印机名称正确。
  • 从打印机属性中打印测试页。
  • 手动打印ZPL:

net use lpt1 "printer shared name" print "C:\\Users\\serviceuser\\desktop\\label.txt"

如果您尝试上述方法并且可以正常工作,那么您链接的代码不起作用会让我感到惊讶。

我为此案例开发了一个websockt ZPLwebSocket

  1. 下载文件并解压缩。
  2. 在客户端PC上运行SetUp.exe。
  3. 转到服务并启动“ Navegador的服务式”
  4. 使用GoogleChrome或mozilla打开trysocket.html
  5. 输入本地打印机的名称
  6. 点击按钮“ enviar”
  7. 显示服务器的消息

    这是页面上的javascriptcode。

     $(document).ready(function () { var connection = new WebSocket('ws://localhost:2645/service/'); const reader = new FileReader(); $('.sendZPL').on('click', function () { var tosend = { TipoArchivo: 0, nombre: "Etiqueta de Prueba", code: $(".sendZPL").val(), Tipo: 4, Impresora: $(".impresora").val() } connection.send(JSON.stringify(tosend)); }); connection.addEventListener('message', function (event) { reader.readAsText(event.data); }); reader.addEventListener('loadend', (e) => { const text = e.srcElement.result; console.log(text); $(".serverResponse").val(text); }); }); 

这是要在ConsoleApp上运行的套接字代码c#:

class Program
{

    private static Server.WebsocketServer websocketServer;
    private static System.Diagnostics.EventLog eventLog1= new EventLog();
    static void Main( string[] args )
    {
        if (!System.Diagnostics.EventLog.SourceExists( "MySource" ))
        {
            System.Diagnostics.EventLog.CreateEventSource(
                "MySource", "MyNewLog" );
        }

        eventLog1.Source = "MySource";
        eventLog1.Log = "MyNewLog";


        websocketServer = new Server.WebsocketServer();
        websocketServer.LogMessage += WebsocketServer_LogMessage; 

        websocketServer.Start( "http://localhost:2645/tryservice/" );

        Console.Read();
    }



    private static void WebsocketServer_LogMessage( object sender, Server.WebsocketServer.LogMessageEventArgs e )
    {
        // eventLog1.WriteEntry( e.Message );
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine( e.Message );
        Console.ForegroundColor = ConsoleColor.White;
    }
public  class WebsocketServer
{
    public event OnLogMessage LogMessage;
    public delegate void OnLogMessage(Object sender, LogMessageEventArgs e);
    public class LogMessageEventArgs : EventArgs
    {
        public string Message { get; set; }
        public LogMessageEventArgs(string Message) {
            this.Message = Message;
        }
    }

    public bool started = false;
    public async void Start(string httpListenerPrefix)
    {
        HttpListener httpListener = new HttpListener();
        httpListener.Prefixes.Add(httpListenerPrefix);
        httpListener.Start();
        LogMessage(this, new LogMessageEventArgs("Listening..."));
        started = true;

        while (started)
        {
            HttpListenerContext httpListenerContext = await httpListener.GetContextAsync();
            if (httpListenerContext.Request.IsWebSocketRequest)
            {
                ProcessRequest(httpListenerContext);
            }
            else
            {
                httpListenerContext.Response.StatusCode = 400;
                httpListenerContext.Response.Close();
                LogMessage(this, new LogMessageEventArgs("Closed..."));
            }
        }
    }

    public void Stop()
    {
        started = false;
    }

    private List<string> _printers = new List<string>();
    public List<string> Printers { get
        {
            _printers.Clear();
            foreach (string imp in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                _printers.Add(imp);
            }
            return _printers;
        }
    }

    private async void ProcessRequest(HttpListenerContext httpListenerContext)
    {
        WebSocketContext webSocketContext = null;

        try
        {
            webSocketContext = await httpListenerContext.AcceptWebSocketAsync(subProtocol: null);
            LogMessage(this, new LogMessageEventArgs("Connected"));
        }
        catch (Exception e)
        {
            httpListenerContext.Response.StatusCode = 500;
            httpListenerContext.Response.Close();
            LogMessage(this, new LogMessageEventArgs(String.Format("Exception: {0}", e)));
            return;
        }

        WebSocket webSocket = webSocketContext.WebSocket;
        try
        {


            while (webSocket.State == WebSocketState.Open)
            {

                ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);

                WebSocketReceiveResult result = null;

                using (var ms = new System.IO.MemoryStream())
                {
                    do
                    {
                        result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
                        ms.Write(buffer.Array, buffer.Offset, result.Count);
                    }
                    while (!result.EndOfMessage);

                    ms.Seek(0, System.IO.SeekOrigin.Begin);

                    if (result.MessageType == WebSocketMessageType.Text)
                    {
                        using (var reader = new System.IO.StreamReader(ms, Encoding.UTF8))
                        {
                            var r = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                            var t = Newtonsoft.Json.JsonConvert.DeserializeObject<Datos>(r);
                            bool valid = true;
                            byte[] toBytes = Encoding.UTF8.GetBytes("Error..."); ;

                            if (t != null)
                            {
                                if (t.Impresora.Trim() == string.Empty)
                                {
                                    var printers = "";
                                    Printers.ForEach(print => {
                                        printers += print + "\n";
                                    });

                                    toBytes = Encoding.UTF8.GetBytes("No se Indicó la Impresora\nLas Impresoras disponibles son:\n" + printers);
                                    valid = false;
                                }
                                else if(!Printers.Contains(t.Impresora))
                                {
                                    var printers = "";
                                    Printers.ForEach(print =>
                                    {
                                        printers += print + "\n";
                                    });

                                    toBytes = Encoding.UTF8.GetBytes("Impresora no valida\nLas Impresoras disponibles son:\n" + printers);
                                    valid = false;
                                }


                                if (t.nombre.Trim() == string.Empty)
                                {
                                    toBytes = Encoding.UTF8.GetBytes("No se Indicó el nombre del Documento");
                                    valid = false;
                                }
                                if (t.code== null)
                                {
                                    toBytes = Encoding.UTF8.GetBytes("No hay datos para enviar a la Impresora");
                                    valid = false;
                                }


                                if (valid && print.RawPrinter.SendStringToPrinter(t.Impresora, t.code, t.nombre))
                                {
                                    LogMessage(this, new LogMessageEventArgs(String.Format("Enviado: {0} => {1} => {2}", t.Impresora, t.nombre, t.code)));
                                    toBytes = Encoding.UTF8.GetBytes("Correcto...");
                                }

                                await webSocket.SendAsync(new ArraySegment<byte>(toBytes, 0, int.Parse(toBytes.Length.ToString())), WebSocketMessageType.Binary, result.EndOfMessage, CancellationToken.None);


                            }
                            else
                            {
                                toBytes = Encoding.UTF8.GetBytes("Error...");
                                await webSocket.SendAsync(new ArraySegment<byte>(toBytes, 0, int.Parse(toBytes.Length.ToString())), WebSocketMessageType.Binary, result.EndOfMessage, CancellationToken.None);
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogMessage(this, new LogMessageEventArgs(String.Format("Exception: {0} \nLinea:{1}", e, e.StackTrace)));
        }
        finally
        {
            if (webSocket != null)
                webSocket.Dispose();
        }
    }


}

public class Datos {
    public enum TipoArchivo { zpl, pdf, doc, json, text}
    public string nombre { get; set; }
    public string code { get; set; }
    public TipoArchivo Tipo { get; set; } = TipoArchivo.text;
    public string Impresora { get; set; } = "";
}


}

RAWPrinterClass 链接

 public class RawPrinter
    {
        // 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, ref IntPtr hPriknter, 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, ref 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, string DocName = "")
        {
            Int32 dwError = 0;
            Int32 dwWritten = 0;
            IntPtr hPrinter = new IntPtr(0);
            DOCINFOA di = new DOCINFOA();
            bool bSuccess = false;
            // Assume failure unless you specifically succeed.
            di.pDocName = string.IsNullOrEmpty(DocName) ? "My C#.NET RAW Document" : DocName;
            di.pDataType = "RAW";

            // Open the printer.
            if (OpenPrinter(szPrinterName.Normalize(), ref 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, ref 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 = 0;

            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, string DocName = "")
        {
            IntPtr pBytes = default(IntPtr);
            Int32 dwCount = default(Int32);
            // 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.
            var t= SendBytesToPrinter(szPrinterName, pBytes, dwCount, DocName);
            Marshal.FreeCoTaskMem(pBytes);
            return t;
        }
    }

对于我们要涵盖的特定情况,似乎正确的答案是,鉴于我们受到的限制,无法使用斑马打印机进行打印。 由于此打印机未连接到网络,因此我们必须使用能够满足我们需求的独立桌面应用程序。

感谢所有协助并提出他们想法和想法的人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM