如何从托管站点在本地ZPL打印机中打印标签?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从托管站点在本地ZPL打印机中打印标签?相关的知识,希望对你有一定的参考价值。

我在远程机器上托管了我的网站。我可以通过在线链接访问该网站(例如:xyz.mysite.com)。我需要从该在线网站打印一个标签。我编写了一个下面的代码来打印标签(在我的应用程序中使用了Neodynamic thermal SDK库)。

var pj = new PrintJob();    
PrinterSettings myPrinter = new PrinterSettings();
                           myPrinter.Communication.CommunicationType = CommunicationType.Network;
                           myPrinter.Communication.NetworkIPAddress = System.Net.IPAddress.Parse("127.0.0.1"); // Used my local network IP address.
                           myPrinter.Communication.NetworkPort = 9100;
                           myPrinter.UseDefaultPrinter = true;
                           myPrinter.ProgrammingLanguage = ProgrammingLanguage.ZPL;
                           pj.PrinterSettings = myPrinter;
                           pj.Print(myLabel);

当我在网站上执行打印操作时,面对下面的错误,

获取默认打印机时发生异常。 Win32错误:系统找不到指定的文件。

谁能建议我解决这个问题?

答案

我为这个案例开发了一个websocket qazxsw poi

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

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

$(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);
  });

});

RAWPrinterClass 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 + " "; }); toBytes = Encoding.UTF8.GetBytes("No se Indicó la Impresora Las Impresoras disponibles son: " + printers); valid = false; } else if(!Printers.Contains(t.Impresora)) { var printers = ""; Printers.ForEach(print => { printers += print + " "; }); toBytes = Encoding.UTF8.GetBytes("Impresora no valida Las Impresoras disponibles son: " + 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(toB

以上是关于如何从托管站点在本地ZPL打印机中打印标签?的主要内容,如果未能解决你的问题,请参考以下文章

ZPL 编程 - 打印带有“每个标签后暂停”的标签

将 PNG 图像转换为 ZPL 代码

使 ZPL 标签中的文本加粗或加下划线?

ZPL - 条形码打印时缺少数字

斑马打印机ZPL语言编程实战

从 ZPL(斑马编程语言)翻译成 IPL(Intermec 编程语言)