Serveur d'impression

impression – Imprimer des codes à barres d'une page Web vers une imprimante Zebra – Serveur d’impression

Le 3 mai 2019 - 7 minutes de lecture

essayez de créer un WebSocket qui contrôle l’impression côté client et envoie les données avec ajax de la page à localhost.

/// websocket
en utilisant le système;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;

Serveur d'espace de noms
{
    programme de classe
    
        WebsocketServer statique public ws;
        static void Main (chaîne[] args)
        
            ws = new Server.WebsocketServer ();
            ws.LogMessage + = Ws_LogMessage;
            ws.Start ("http: // localhost: 2645 / service /");
            Console.WriteLine ("Appuyez sur n'importe quelle touche pour quitter ...");
            Console.ReadKey ();
        

        void statique privé Ws_LogMessage (expéditeur de l'objet, WebsocketServer.LogMessageEventArgs e)
        
            Console.WriteLine (e.Message);
        
    

    classe publique WebsocketServer
    {
        événement public OnLogMessage LogMessage;
        délégué public void OnLogMessage (Expéditeur d'objet, LogMessageEventArgs e);
        Classe publique LogMessageEventArgs: EventArgs
        
            chaîne publique Message get; ensemble; 
            public LogMessageEventArgs (chaîne Message)
            
                this.Message = Message;
            
        

        bool public started = false;
        public async void Start (chaîne httpListenerPrefix)
        
            HttpListener httpListener = new HttpListener ();
            httpListener.Prefixes.Add (httpListenerPrefix);
            httpListener.Start ();
            LogMessage (this, new LogMessageEventArgs ("Listening ..."));
            commencé = vrai;

            alors que (commencé)
            
                HttpListenerContext httpListenerContext = wait httpListener.GetContextAsync ();
                if (httpListenerContext.Request.IsWebSocketRequest)
                
                    ProcessRequest (httpListenerContext);
                
                autre
                
                    httpListenerContext.Response.StatusCode = 400;
                    httpListenerContext.Response.Close ();
                    LogMessage (this, new LogMessageEventArgs ("Closed ..."));
                
            
        

        public void Stop ()
        
            commencé = faux;
        
        ProcessRequest (HttpListenerContext httpListenerContext)
        {
            WebSocketContext webSocketContext = null;

            essayer
            
                webSocketContext = wait httpListenerContext.AcceptWebSocketAsync (subProtocol: null);
                LogMessage (this, nouveau LogMessageEventArgs ("Connecté"));
            
            catch (Exception e)
            
                httpListenerContext.Response.StatusCode = 500;
                httpListenerContext.Response.Close ();
                LogMessage (this, new 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 resultat = null;

                    using (var ms = new System.IO.MemoryStream ())
                    {
                        faire
                        
                            result = wait 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 (""); ;

                                si (t! = null)
                                
                                    if (t.printer.Trim () == string.Empty)
                                    
                                        var imprimantes = "";
                                        foreach (var imp dans System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                                        
                                            imprimantes + = imp + " n";
                                        

                                        toBytes = Encoding.UTF8.GetBytes ("Aucune indication sur l'impression  nLas Impresoras disponibles:" + imprimantes);
                                        valide = faux;
                                    
                                    if (t.name.Trim () == string.Empty)
                                    
                                        toBytes = Encoding.UTF8.GetBytes ("Aucune indication sur le document");
                                        valide = faux;
                                    
                                    if (t.code == null)
                                    
                                        toBytes = Encoding.UTF8.GetBytes ("Aucune donnée n'est affichée à la suite de l'impression");
                                        valide = faux;
                                    


                                    si (valide)
                                    
                                        print.RawPrinter.SendStringToPrinter (t.printer, t.code, t.name);
                                        toBytes = Encoding.UTF8.GetBytes ("Correcto ...");
                                    

                                    attendez webSocket.SendAsync (nouvel ArraySegment(toBytes, 0, int.Parse (toBytes.Length.ToString ())), WebSocketMessageType.Binary, result.EndOfMessage, CancellationToken.None);
                                
                                autre
                                
                                    toBytes = Encoding.UTF8.GetBytes ("Erreur ...");
                                    attendez webSocket.SendAsync (nouvel ArraySegment(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))));
            
            enfin
            
                si (webSocket! = null)
                    webSocket.Dispose ();
            
        }
    }

    classe publique Datos
    
        nom de chaîne publique get; ensemble; 
        code de chaîne publique get; ensemble; 
        chaîne publique imprimante get; ensemble;  = "";
    
}

impression brute:

using Microsoft.VisualBasic;
en utilisant le système;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;

print de l'espace de noms
{
    Classe publique RawPrinter
    {
        // Déclarations de structure et d'API:
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        classe publique 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)]
        public statique extern bool OpenPrinter ([MarshalAs(UnmanagedType.LPStr)]
chaîne szPrinter, réf IntPtr hPriknter, IntPtr pd);

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

        [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public statique externe bool StartDocPrinter (IntPtr hPrinter, niveau Int32, [In(), MarshalAs(UnmanagedType.LPStruct)]
DOCINFOA di);

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

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

        [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public statique extern 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 true en cas de succès, false en cas d'échec.
        public bool statique SendBytesToPrinter (chaîne szPrinterName, pbits IntPtr, dwCount Int32, chaîne DocName = "")
        
            Int32 dwError = 0;
            Int32 dwWritten = 0;
            IntPtr hPrinter = new IntPtr (0);
            DOCINFOA di = new DOCINFOA ();
            bool bSuccess = false;
            // Suppose l'échec sauf si vous y parvenez.
            di.pDocName = string.IsNullOrEmpty (DocName)? "Mon document RAW C # .NET": DocName;
            di.pDataType = "RAW";

            // Ouvre l'imprimante.
            if (OpenPrinter (szPrinterName.Normalize (), réf hPrinter, IntPtr.Zero))
            
                // Démarrer un document.
                if (StartDocPrinter (hPrinter, 1, di))
                
                    // Démarrer une page.
                    if (StartPagePrinter (hPrinter))
                    
                        // Ecrivez 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 ();
            
            retourner bSuccess;
        

        public bool statique SendFileToPrinter (string szPrinterName, string szFileName)
        
            // ouvre le fichier.
            FileStream fs = new FileStream (szFileName, FileMode.Open);
            // Crée un BinaryReader sur le fichier.
            BinaryReader br = new BinaryReader (fs);
            // Dimette 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);
            // Lit le contenu du fichier dans le tableau.
            octets = br.ReadBytes (nLength);
            // Alloue de la mémoire non géré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ère la mémoire non gérée que vous avez allouée précédemment.
            Marshal.FreeCoTaskMem (pUnmanagedBytes);
            retourner bSuccess;
        
        public bool statique SendStringToPrinter (string szPrinterName, string szString, string DocName = "")
        
            IntPtr pBytes = default (IntPtr);
            Int32 dwCount = default (Int32);
            // Combien de caractères y a-t-il dans la chaîne?
            dwCount = szString.Length;
            // Supposons que l'imprimante attend du texte ANSI, puis convertit
            // la chaîne en texte ANSI.
            pBytes = Marshal.StringToCoTaskMemAnsi (szString);
            // Envoie la chaîne ANSI convertie à l'imprimante.
            SendBytesToPrinter (szPrinterName, pBytes, dwCount, DocName);
            Marshal.FreeCoTaskMem (pBytes);
            retourne vrai;
        
    }
}

page html:









    

puis envoyez un code ZPL à partir de HTML (écrivez ceci sur du code textarea);

^ XA
^ FO200,50 ^ BY2 ^ B3N, N, 80, Y, N ^ FD0123456789 ^ FS
^ PQ1 ^ XZ

Commentaires

Laisser un commentaire

Votre commentaire sera révisé par les administrateurs si besoin.