如何通过USB使用C#发送原始ZPL斑马打印机

如何通过USB使用C#发送原始ZPL斑马打印机

本文介绍了如何通过USB使用C#发送原始ZPL斑马打印机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个初学者的C#程序员。我有我需要通过USB发送原始命令斑马打印机LP 2844和使其工作的项目。我做了很多研究,试图找出一个办法做到这一点。我使用的是从代码,但它没有工作。根据我的测试,似乎我发出命令到打印机,但它并没有回应,打印。我不知道这种想法。有人可以帮我吗?



我使用的按钮,直接将命令发送

 私人无效button2_Click(对象发件人,EventArgs五)
{
字符串s =A50,50,0,2,1,1,N,\9129302\ ;

//允许用户选择一个打印机。
PrintDialog类PD =新PrintDialog类();
pd.PrinterSettings =新PrinterSettings();
如果(DialogResult.OK == pd.ShowDialog(本))
{
//寄打印机专用打印机。
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName,S);
MessageBox.Show(数据发送到打印机。);
}
}


解决方案

修改:为了解决您的更新,您遇到的问题是,你正在使用 SendStringToPrinter 它发送一个ANSI字符串(终止空)字符串到打印机这是不是有什么打印机期待。根据官方第23页(这是你真的这样做,不ZPL根据您的例子)。



So you must either modify SendStringToPrinter to send a \n at the end of the string instead of a \0 or you must build the ASCII byte array yourself and use RawPrinterHelper.SendBytesToPrinter yourself (like I did in my original answer below).

So to fix your simple posted example we change out your function call, we also must tell the printer to actually print by sending a P1\n

private void button2_Click(object sender, EventArgs e)
{
    string s = "A50,50,0,2,1,1,N,\"9129302\"\n";
    s += "P1\n";

    // Allow the user to select a printer.
    PrintDialog pd = new PrintDialog();
    pd.PrinterSettings = new PrinterSettings();
    if (DialogResult.OK == pd.ShowDialog(this))
    {
        var bytes = Encoding.ASCII.GetBytes(s);
        // Send a printer-specific to the printer.
        RawPrinterHelper.SendBytesToPrinter(pd.PrinterSettings.PrinterName, bytes, bytes.Length);
        MessageBox.Show("Data sent to printer.");
    }
}

//elsewhere
public static class RawPrinterHelper
{
    //(Snip) The rest of the code you already have from http://support.microsoft.com/kb/322091

    [DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, byte[] pBytes, Int32 dwCount, out Int32 dwWritten );


    private static bool SendBytesToPrinter(string szPrinterName, byte[] bytes, Int32 dwCount)
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false;

        di.pDocName = "Zebra Label";
        di.pDataType = "RAW";


        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            if (StartDocPrinter(hPrinter, 1, di))
            {
                if (StartPagePrinter(hPrinter))
                {
                    bSuccess = WritePrinter(hPrinter, bytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        if (bSuccess == false)
        {
            dwError = Marshal.GetLastWin32Error();
            throw new Win32Exception(dwError);
        }
        return bSuccess;
    }
}


I did this with Zebra's older EPL2 language, but it should be very similar to what you need to do with ZPL. Perhaps it will get you started in the right direction.

public class Label
{
    #region Print logic. Taken from http://support.microsoft.com/kb/322091

    //Snip stuff unchanged from the KB example.

    [DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, byte[] pBytes, Int32 dwCount, out Int32 dwWritten );

    private static bool SendBytesToPrinter(string szPrinterName, byte[] Bytes, Int32 dwCount)
    {
        Int32 dwError = 0, dwWritten = 0;
        IntPtr hPrinter = new IntPtr(0);
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false;

        di.pDocName = "Zebra Label";
        di.pDataType = "RAW";


        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            if (StartDocPrinter(hPrinter, 1, di))
            {
                if (StartPagePrinter(hPrinter))
                {
                    bSuccess = WritePrinter(hPrinter, Bytes, dwCount, out dwWritten);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }
        if (bSuccess == false)
        {
            dwError = Marshal.GetLastWin32Error();
            throw new Win32Exception(dwError);
        }
        return bSuccess;
    }
    #endregion

    public byte[] CreateCompleteCommand(bool headerAndFooter)
    {
        List<byte> byteCollection = new List<byte>();

        //Static header content describing the label.
        if (headerAndFooter)
        {
            byteCollection.AddRange(Encoding.ASCII.GetBytes("\nN\n"));
            byteCollection.AddRange(Encoding.ASCII.GetBytes(String.Format("S{0}\n", this.Speed)));
            byteCollection.AddRange(Encoding.ASCII.GetBytes(String.Format("D{0}\n", this.Density)));
            byteCollection.AddRange(Encoding.ASCII.GetBytes(String.Format("q{0}\n", this.LabelHeight)));
            if (this.AdvancedLabelSizing)
            {
                byteCollection.AddRange(Encoding.ASCII.GetBytes(String.Format("Q{0},{1}\n", this.LableLength, this.GapLength)));
            }
        }

        //The content of the label.
        foreach (var command in this.Commands)
        {
            byteCollection.AddRange(command.GenerateByteCommand());
        }

        //The footer content of the label.
        if(headerAndFooter)
            byteCollection.AddRange(Encoding.ASCII.GetBytes(String.Format("P{0}\n", this.Pages)));

        return byteCollection.ToArray();
    }

    public bool PrintLabel(string printer)
    {
        byte[] command = this.CreateCompleteCommand(true);
        return SendBytesToPrinter(printer, command, command.Length);
    }

    public List<Epl2CommandBase> Commands { get; private set; }

    //Snip rest of the code.
}

public abstract partial class Epl2CommandBase
{
    protected Epl2CommandBase() { }

    public virtual byte[] GenerateByteCommand()
    {
        return Encoding.ASCII.GetBytes(CommandString + '\n');
    }
    public abstract string CommandString { get; set; }
}


public class Text : Epl2CommandBase
{
    public override string CommandString
    {
        get
        {
            string printText = TextValue;
            if (Font == Fonts.Pts24)
                printText = TextValue.ToUpperInvariant();
            printText = printText.Replace("\\", "\\\\"); // Replace \ with \\
            printText = printText.Replace("\"", "\\\""); // replace " with \"
            return String.Format("A{0},{1},{2},{3},{4},{5},{6},\"{7}\"", X, Y, (byte)TextRotation, (byte)Font, HorziontalMultiplier, VertricalMultiplier, Reverse, printText);
        }
        set
        {
            GenerateCommandFromText(value);
        }
    }

    private void GenerateCommandFromText(string command)
    {
        if (!command.StartsWith(GetFactoryKey()))
            throw new ArgumentException("Command must begin with " + GetFactoryKey());
        string[] commands = command.Substring(1).Split(',');
        this.X = int.Parse(commands[0]);
        this.Y = int.Parse(commands[1]);
        this.TextRotation = (Rotation)byte.Parse(commands[2]);
        this.Font = (Fonts)byte.Parse(commands[3]);
        this.HorziontalMultiplier = int.Parse(commands[4]);
        this.VertricalMultiplier = int.Parse(commands[5]);
        this.ReverseImageColor = commands[6].Trim().ToUpper() == "R";
        string message = String.Join(",", commands, 7, commands.Length - 7);
        this.TextValue = message.Substring(1, message.Length - 2); // Remove the " at the beginning and end of the string.
    }

    //Snip
}

这篇关于如何通过USB使用C#发送原始ZPL斑马打印机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:25