Search code examples
c#winformsasciiescpos

Escape commands / ByteArray to Readable Text C#


I have developed a POS application using C#, for receipt printing, I'm using PrinterUtility library from NuGet, it converts a string to ByteArray, saves it and sends it to a receipt printer to print it. since I don't have a receipt printer, how can I convert the generated file to a readable text? I opened the result file using notepad++ and content is shown in the picture attached

click on the link to view the image

I wonder if this ByteArray result can be rendered as text and shown in a RichTextBox or if there is any way to create a virtual receipt printer that can display the result?

Your help will be appreciated.

Link to the File Click Here To Download The File


Solution

  • Try this simple parser.
    It detects SOH (Start of Heading) and GS (Group Separator) escape codes and ignores/skips NUL and ESC code and their connected identifier, if any.
    The parsing terminates when all bytes are read or a ETX (End of Text) code is found.

    It's a pretty simple nested while loop, so you can easily adapt it, to handle special cases.

    The parsed chars are added to a StringBuilder object.

    ► Note that this handles only ASCII chars. For languages that don't use ASCII chars, you need to build an array of bytes (not an array of chars with a StringBuilder), then use Encoding.[Some Encoding].GetString([Parsed Byte Array]) to decode the array of bytes to a .Net string format.

    Use a monospaced Font (Consolas, Courier New etc.) in your RichTextBox.

    var bytes = [Your Byte Array];
    var charBuffer = new StringBuilder(bytes.Length);
    
    int nul = 0x00;   // NULL char
    int soh = 0x01;   // Start of Heading
    int etx = 0x03;   // End of Text
    int esc = 0x1B;   // Escape
    int gs  = 0x1D;   // Group Separator
    
    int pos = 0;
    while (pos < bytes.Length) {
        byte byteValue = bytes[pos];
        if (byteValue == soh || byteValue == gs || byteValue == nul) {
            pos += byteValue == gs ? 3 : 1;
            if (pos == etx) break;
    
            while (bytes[pos] != gs && bytes[pos] != esc) {
                charBuffer.Append((char)bytes[pos]);
                pos += 1;
            }
        }
        pos += 1;
    }
    richTextBox1.Text = charBuffer.ToString();