Imprimer ZPL sur l'imprimante Zebra via C # .NET – Bien choisir son serveur d impression
Author: Titanfall —
Short summary: je développe un websockt pour ce cas ZPLwebSocket Téléchargez le fichier et décompressez. Exécutez SetUp.exe sur le PC client. Accédez aux services et lancez «Servicio de Impresion desde Navegador» ouvrez trysocket.html avec GoogleChrome ou mozilla écrire le nom de l'imprimante locale cliquez sur le bouton 'enviar' afficher les messages du serveur c'est le code javascript […]
Quick overview
- Site
- Tutos GameServer
- Canonical URL
- https://tutos-gameserver.fr/2020/03/12/imprimer-zpl-sur-limprimante-zebra-via-c-net-bien-choisir-son-serveur-d-impression/
- LLM HTML version
- https://tutos-gameserver.fr/2020/03/12/imprimer-zpl-sur-limprimante-zebra-via-c-net-bien-choisir-son-serveur-d-impression/llm
- LLM JSON version
- https://tutos-gameserver.fr/2020/03/12/imprimer-zpl-sur-limprimante-zebra-via-c-net-bien-choisir-son-serveur-d-impression/llm.json
- Manifest
- https://tutos-gameserver.fr/llm-endpoints-manifest.json
- Estimated reading time
- 7 minutes (414 seconds)
- Word count
- 1380
Key points
- je développe un websockt pour ce cas ZPLwebSocket Téléchargez le fichier et décompressez.
- Exécutez SetUp.exe sur le PC client.
- Accédez aux services et lancez «Servicio de Impresion desde Navegador» ouvrez trysocket.html avec GoogleChrome ou mozilla écrire le nom de l'imprimante locale cliquez sur le bouton 'enviar' afficher les messages du serveur c'est le code javascript sur la page.
- $ (document) .ready (function () var connection = new WebSocket ('ws: // localhost: 2645 / service /'); const reader = new FileReader (); $ ('.
Primary visual
Structured content
je développe un websockt pour ce cas ZPLwebSocket
Téléchargez le fichier et décompressez. Exécutez SetUp.exe sur le PC client. Accédez aux services et lancez «Servicio de Impresion desde Navegador» ouvrez trysocket.html avec GoogleChrome ou mozilla écrire le nom de l'imprimante locale cliquez sur le bouton 'enviar'
afficher les messages du serveur c'est le code javascript sur la page. $ (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', fonction (événement) reader.readAsText (event.data); );
reader.addEventListener ('loadend', (e) => const text = e.srcElement.result; console.log (texte); $ (". serverResponse"). val (texte); );
);
c'est le code de socket c # pour exécuter sur ConsoleApp: Programme de cours {
serveur statique statique Server.WebsocketServer websocketServer; System.Diagnostics.EventLog statique statique eventLog1 = new EventLog (); static void Main (chaîne[] args) if (! System.Diagnostics.EventLog.SourceExists ("MySource")) System.Diagnostics.EventLog.CreateEventSource ( "MySource", "MyNewLog");
eventLog1.Source = "MySource"; eventLog1.Log = "MyNewLog";
websocketServer = nouveau Server.WebsocketServer (); websocketServer.LogMessage + = WebsocketServer_LogMessage;
websocketServer.Start ("http: // localhost: 2645 / tryservice /");
Console.Read ();
void privé statique WebsocketServer_LogMessage (expéditeur d'objet, Server.WebsocketServer.LogMessageEventArgs e) // eventLog1.WriteEntry (e.Message); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine (e.Message); Console.ForegroundColor = ConsoleColor.White; classe publique WebsocketServer { événement public OnLogMessage LogMessage; délégué public void OnLogMessage (expéditeur d'objet, LogMessageEventArgs e); Classe public class LogMessageEventArgs: EventArgs chaîne publique Message get; ensemble; public LogMessageEventArgs (chaîne Message) this.Message = Message;
bool public commencé = faux; async public void Start (chaîne httpListenerPrefix) HttpListener httpListener = new HttpListener (); httpListener.Prefixes.Add (httpListenerPrefix); httpListener.Start (); LogMessage (ceci, nouveau LogMessageEventArgs ("Listening ...")); commencé = vrai;
pendant (commencé) HttpListenerContext httpListenerContext = attendre httpListener.GetContextAsync (); if (httpListenerContext.Request.IsWebSocketRequest) ProcessRequest (httpListenerContext); autre httpListenerContext.Response.StatusCode = 400; httpListenerContext.Response.Close (); LogMessage (ceci, nouveau LogMessageEventArgs ("Closed ..."));
public void Stop () commencé = faux;
Liste privée _printers = nouvelle liste(); Liste publique Imprimantes get _printers.Clear (); foreach (chaîne imp dans System.Drawing.Printing.PrinterSettings.InstalledPrinters) _printers.Add (imp); return _printers;
async privé void ProcessRequest (HttpListenerContext httpListenerContext) { WebSocketContext webSocketContext = null;
essayer webSocketContext = attendre httpListenerContext.AcceptWebSocketAsync (subProtocol: null); LogMessage (ceci, nouveau LogMessageEventArgs ("Connecté")); capture (exception e) httpListenerContext.Response.StatusCode = 500; httpListenerContext.Response.Close (); LogMessage (ceci, nouveau LogMessageEventArgs (String.Format ("Exception: 0", e))); revenir;
WebSocket webSocket = webSocketContext.WebSocket; essayer {
while (webSocket.State == WebSocketState.Open) {
ArraySegment buffer = new ArraySegment(nouvel octet[8192]);
WebSocketReceiveResult result = null;
en utilisant (var ms = new System.IO.MemoryStream ()) { faire résultat = attendre webSocket.ReceiveAsync (tampon, 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(r); bool valid = true; octet[] toBytes = Encoding.UTF8.GetBytes ("Erreur ..."); ;
si (t! = null) if (t.Impresora.Trim () == string.Empty) var printers = ""; Printers.ForEach (print => imprimantes + = imprimer + " n"; );
toBytes = Encoding.UTF8.GetBytes ("No se Indicó la Impresora nLas Impresoras disponibles son: n" + imprimantes); valide = faux; sinon si (! Printers.Contains (t.Impresora)) var printers = ""; Printers.ForEach (print => imprimantes + = imprimer + " n"; );
toBytes = Encoding.UTF8.GetBytes ("Impresora no valida nLas Impresoras disponibles son: n" + imprimantes); valide = faux;
if (t.nombre.Trim () == string.Empty) toBytes = Encoding.UTF8.GetBytes ("Aucun indicateur du nombre de documents"); valide = faux; if (t.code == null) toBytes = Encoding.UTF8.GetBytes ("Aucune donnée de foin para enviar a la Impresora"); valide = faux;
if (valide && 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 ...");
attendre webSocket.SendAsync (nouveau ArraySegment(toBytes, 0, int.Parse (toBytes.Length.ToString ())), WebSocketMessageType.Binary, result.EndOfMessage, CancellationToken.None);
autre toBytes = Encoding.UTF8.GetBytes ("Erreur ..."); attendre webSocket.SendAsync (nouveau ArraySegment(toBytes, 0, int.Parse (toBytes.Length.ToString ())), WebSocketMessageType.Binary, result.EndOfMessage, CancellationToken.None); } } } } capture (exception e) LogMessage (ceci, nouveau LogMessageEventArgs (String.Format ("Exception: 0 nLinea: 1", e, e.StackTrace))); enfin if (webSocket! = null) webSocket.Dispose (); }
}
public class Datos énumération publique TipoArchivo zpl, pdf, doc, json, text chaîne publique nombre get; ensemble; code de chaîne publique get; ensemble; public TipoArchivo Tipo get; ensemble; = TipoArchivo.text; chaîne publique Impresora get; ensemble; = "";
}
le lien RAWPrinterClass: Classe public class RawPrinter { // Structure et déclarations d'API: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public class DOCINFOA [MarshalAs(UnmanagedType.LPStr)] chaîne publique pDocName; [MarshalAs(UnmanagedType.LPStr)] chaîne publique pOutputFile; [MarshalAs(UnmanagedType.LPStr)] chaîne publique pDataType; [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] externe statique externe bool OpenPrinter ([MarshalAs(UnmanagedType.LPStr)] chaîne szPrinter, ref IntPtr hPriknter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public statique externe 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)] externe statique externe 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)] externe statique externe bool EndPagePrinter (IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public statique externe bool WritePrinter (IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, ref Int32 dwWritten);
// SendBytesToPrinter () // Lorsque la fonction reçoit un nom d'imprimante et un tableau non géré // d'octets, la fonction envoie ces octets à la file d'attente d'impression. // Renvoie vrai en cas de succès, faux en cas d'échec. bool statique public SendBytesToPrinter (chaîne szPrinterName, IntPtr pBytes, Int32 dwCount, chaîne DocName = "") Int32 dwError = 0; Int32 dwWritten = 0; IntPtr hPrinter = new IntPtr (0); DOCINFOA di = nouveau DOCINFOA (); bool bSuccess = false; // Supposons un échec sauf si vous réussissez spécifiquement di.pDocName = string.IsNullOrEmpty (DocName)? "Mon document RAW C # .NET": DocName; di.pDataType = "RAW";
// Ouvrez l'imprimante. if (OpenPrinter (szPrinterName.Normalize (), ref hPrinter, IntPtr.Zero)) // Démarrer un document. if (StartDocPrinter (hPrinter, 1, di)) // Démarrer une page. if (StartPagePrinter (hPrinter)) // Écrivez vos octets. bSuccess = WritePrinter (hPrinter, pBytes, dwCount, ref dwWritten); EndPagePrinter (hPrinter); EndDocPrinter (hPrinter); ClosePrinter (hPrinter); // Si vous n'avez pas réussi, GetLastError peut donner plus d'informations // pourquoi pas. if (bSuccess == false) dwError = Marshal.GetLastWin32Error (); return bSuccess;
bool statique public SendFileToPrinter (chaîne szPrinterName, chaîne szFileName) // Ouvrez le fichier. FileStream fs = new FileStream (szFileName, FileMode.Open); // Créez un BinaryReader sur le fichier. BinaryReader br = nouveau BinaryReader (fs); // Dim un tableau d'octets assez grand pour contenir le contenu du fichier. Octet[] octets = nouvel octet[fs.Length]; bool bSuccess = false; // Votre pointeur non géré. IntPtr pUnmanagedBytes = new IntPtr (0); int nLength = 0;
nLength = Convert.ToInt32 (fs.Length); // Lire le contenu du fichier dans le tableau. bytes = br.ReadBytes (nLength); // Alloue de la mémoire non managée pour ces octets. pUnmanagedBytes = Marshal.AllocCoTaskMem (nLength); // Copiez le tableau d'octets gérés dans le tableau non géré. Marshal.Copy (octets, 0, pUnmanagedBytes, nLength); // Envoie les octets non gérés à l'imprimante. bSuccess = SendBytesToPrinter (szPrinterName, pUnmanagedBytes, nLength); // Libérez la mémoire non managée que vous avez allouée précédemment. Marshal.FreeCoTaskMem (pUnmanagedBytes); return bSuccess; bool statique public SendStringToPrinter (chaîne szPrinterName, chaîne szString, chaîne DocName = "") IntPtr pBytes = default (IntPtr); Int32 dwCount = par défaut (Int32); // Combien de caractères contient la chaîne? dwCount = szString.Length; // Supposons que l'imprimante attend du texte ANSI, puis convertissez // la chaîne en texte ANSI. pBytes = Marshal.StringToCoTaskMemAnsi (szString); // Envoie la chaîne ANSI convertie à l'imprimante. var t = SendBytesToPrinter (szPrinterName, pBytes, dwCount, DocName); Marshal.FreeCoTaskMem (pBytes); return t; }
Click to rate this post! [Total: 0 Average: 0]
Topics and keywords
Themes: Serveur d'impression
License & attribution
License: CC BY-ND 4.0.
Attribution required: yes.
Manifest: https://tutos-gameserver.fr/llm-endpoints-manifest.json
LLM Endpoints plugin version 1.1.2.