简体   繁体   中英

How to convert escape characters to ANSI from string in XML

When i use a Windows service written in C# to send a raw string to a receipt printer that uses escape sequences to initiate features within the printer. Such as:

\\x1b\\x64\\x02

to operate the paper cutter.

I'm using a receipt template file on another server and placing the text, base 64 encoded, into XML to give it to the Windows service. The problem is that the text is literally printed on the receipt when extracting it from the XML and it's something to do with the escape characters not being translated.

I'm guessing that when i type those escape sequences into Visual Studio, it represents the ANSI character right there in the string (because it works when i do it that way and then the paper cutter triggers).

How would i translate the string containing escape sequences into the proper format for use within the C# Windows service? The goal is to type these simple escape sequences into a template file and then convert them properly on the other end.

C# code i have at the moment that is trying to decode base 64 and then convert to ANSI encoding:

byte[] data = Convert.FromBase64String(content);
content = Encoding.Default.GetString(data);

byte[] utf8Bytes = Encoding.UTF8.GetBytes(content);
content = Encoding.GetEncoding("Windows-1252").GetString(utf8Bytes);

return RawPrinterHelper.SendStringToPrinter(getConfig().receiptPrinter, content);

Here is the content of the test receipt that is received by the service:

XHgxYlx4MWRceDYxXHgxIE1OSG9tZU91dGxldC5jb20yMzAwIFdlc3QgSGlnaHdheSAxMw0KQnVybnN2aWxsZSwgTU4gNTUzMzcNCjk1Mi0yNzktMTU4Nw0KDQpceDFiXHgxZFx4NjFceDBceDFiXHg0NFx4Mlx4MTBceDIyXHgwIERhdGU6IDIwMTctMDYtMTVceDkgVGltZTogMzo0NmFtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tIA0KXHgxYlx4NDUgU0FMRSANClx4MWJceDQ2

When i base 64 encode \\x7 for example,

  • From within the service: Bw== (as ASCII)
  • From within the service: BwA= (as Unicode)
  • From a string in php: XHg3

So i've found a solution that requires a small amount of change to the template:

On the template side, using PHP, I convert the \\x7 style unicode reference to  and then before i base 64 encode it:

$receipt_str = mb_convert_encoding($receipt_str, 'UTF-8', 'HTML-ENTITIES');

This is working so far. I'm just not sure if there is a better way or if there are limits to this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM