views:

982

answers:

2

Is there a way to send ZPL (Zebra Programming Language) to a printer in .NET?

I have the code to do this in Delphi, but it is not pretty and I would rather not try to recreate it in .NET as it is.


Answer from the post in the accepted answer:

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess,
    uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition,
    uint dwFlagsAndAttributes, IntPtr hTemplateFile);

    private void Print()
    {
        // Command to be sent to the printer
        string command = "^XA^FO10,10,^AO,30,20^FDFDTesting^FS^FO10,30^BY3^BCN,100,Y,N,N^FDTesting^FS^XZ";

        // Create a buffer with the command
        Byte[] buffer = new byte[command.Length];
        buffer = System.Text.Encoding.ASCII.GetBytes(command);
        // Use the CreateFile external func to connect to the LPT1 port
        SafeFileHandle printer = CreateFile("LPT1:", FileAccess.ReadWrite, 0, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
        // Aqui verifico se a impressora é válida
        if (printer.IsInvalid == true)
        {
            return;
        }

        // Open the filestream to the lpt1 port and send the command
        FileStream lpt1 = new FileStream(printer, FileAccess.ReadWrite);
        lpt1.Write(buffer, 0, buffer.Length);
        // Close the FileStream connection
        lpt1.Close();

    }
+1  A: 

Take a look at this thread.

Darin Dimitrov
A: 

I've managed a project that does this with sockets for years. Zebra's typically use port 6101. I'll look through the code and post what I can.

public void SendData(string zpl)
{
    NetworkStream ns = null;
    Socket socket = null;

    try
    {
        if (printerIP == null)
        {
            /* IP is a string property for the printer's IP address. */
            /* 6101 is the common port of all our Zebra printers. */
            printerIP = new IPEndPoint(IPAddress.Parse(IP), 6101);  
        }

        socket = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream,
            ProtocolType.Tcp);
        socket.Connect(printerIP);

        ns = new NetworkStream(socket);

        byte[] toSend = Encoding.ASCII.GetBytes(zpl);
        ns.Write(toSend, 0, toSend.Length);
    }
    finally
    {
        if (ns != null)
            ns.Close();

        if (socket != null && socket.Connected)
            socket.Close();
    }
}
Austin Salonen
Zebra Mobile printers use port 6101 (QL, RW, MZ, etc). Larger printers usually use port 9100.
James Van Huis