其他分享
首页 > 其他分享> > .net 通过蓝牙调用佳博标签打印机

.net 通过蓝牙调用佳博标签打印机

作者:互联网

  最近公司有个需求,需要使用程序打印一张标签,标签内容为一张二维码以及对应的描述信息,并且,要贴在注射器上面,然后供扫码机扫描识别。看到这个需求的第一瞬间,我的想法就是很简单,生成一张图片上面是二维码,下面是描述信息,然后拉起浏览器的打印。咔咔写完了后,测试一下打印,非常的模糊,反复调整了大小还是不行。最后问了一下公司的大佬,大佬说可以直接用打印机指令去生成二维码,直接用图片打印存在缩放的问题。OK,说干就干,找客服要了编程手册,开始写代码。

框架为 .net framework 4.5.2

class Program
    {
        static void Main(string[] args)
        {

            if (args == null || args.Length < 2)
            {
                Console.WriteLine($"【error】打印失败,参数错误!");
                return;
            }

            string code = args[0];
            var content = args[1].Split('$');
            string printrName = "Printer_0E92";
            string pin = "0000";
            if (args.Length >= 3)
            {
                printrName = args[2];
            }
            if (args.Length >= 4)
            {
                printrName = args[3];
            }

            Print(code, content, printrName, pin);
        }

        static void Print(string code, string[] content, string printrName, string pin)
        {
            BluetoothClient client = new BluetoothClient();

            BluetoothDeviceInfo device = client.PairedDevices.FirstOrDefault(x => x.DeviceName.Equals(printrName));

            if (!device.Authenticated)
            {
                BluetoothSecurity.PairRequest(device.DeviceAddress, pin);
            }

            device.Refresh();

            try
            {
                client.Connect(device.DeviceAddress, BluetoothService.SerialPort);
            }
            catch (Exception)
            {
                Console.WriteLine($"【error】无法连接到打印机,请检查打印机!");
                client.Close();
                return;
            }

            var stream = client.GetStream();
            StreamWriter sw = new StreamWriter(stream, Encoding.GetEncoding(54936));
            sw.Write("SIZE 50 mm,70 mm\r\n");//标签尺寸
            sw.Write("GAP 2 mm\r\n");//间距
            sw.Write("CLS\r\n");//清空缓冲区
            sw.Write($"QRCODE 220,50,L,4,A,0,\"{code}\"\r\n");

            var lines = GetLines(content[0]);

            foreach (var item in lines)
            {
                sw.Write($"TEXT 20,{170 + (item.index * 30)},\"TSS24.BF2\",0,1,1,\"{item.message}\"\r\n");
            }

            sw.Write($"TEXT 20,{170 + (lines.Count * 30)},\"TSS24.BF2\",0,1,1,\"{content[1]}\"\r\n");
            sw.Write("PRINT 1,1\r\n");
            sw.Flush();
            sw.Close();
            client.Close();

            Console.WriteLine($"【success】打印成功");
        }

        /// <summary>
        /// 每行16个字,获取每行的数据
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        static List<CodeTextModel> GetLines(string message)
        {
            var result = new List<CodeTextModel>();
            if (message.Length > 16)
            {
                var line = Math.Ceiling(message.Length / 16 * 1.0);
                var length = Math.Ceiling(message.Length / line);
                for (int i = 0; i < line; i++)
                {
                    var t = new CodeTextModel();
                    if (i == line - 1)
                    {
                        t.message = message.Substring(i * (int)length, message.Length - (i * (int)length));
                    }
                    else
                    {
                        t.message = message.Substring(i * (int)length, (int)length);
                    }
                    t.index = i;
                    result.Add(t);
                }
            }
            else
            {
                var t = new CodeTextModel();
                t.message = message;
                t.index = 0;
                result.Add(t);
            }
            return result;
        }
    }
internal class CodeTextModel
    {
        internal int index { get; set; }

        internal string message { get; set; }
    }

  试着打印了一下,很清晰,但是我们项目是.net core 2.2的,我试了一下调用蓝牙的库 InTheHand.Net.Bluetooth 直接抛异常,不支持。改用了3.1版本还是不行。那只能用Process 来调用,并且接收命令行的输出当作返回值,判断是否成功。


 private object locker = new object();
 Process p;


public void StartPrint(string code, string content, string content1) { lock (locker) { string fileName = AppContext.BaseDirectory + "/BluetoothPrinter/"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { fileName += "BluetoothPrinter.exe"; } Task.Factory.StartNew(() => { p = new Process(); p.StartInfo.FileName = fileName; p.StartInfo.Arguments = $"\"{code}\" \"{content}${content1}\""; p.StartInfo.WorkingDirectory = AppContext.BaseDirectory + "BluetoothPrinter/"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = false; p.StartInfo.CreateNoWindow = false; p.OutputDataReceived += P_OutputDataReceived; p.Start(); p.PriorityClass = ProcessPriorityClass.High; p.PriorityBoostEnabled = true; p.BeginOutputReadLine(); p.WaitForExit(); }); } }
private void P_OutputDataReceived(object s, DataReceivedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(e.Data)) return;
            if (!string.IsNullOrWhiteSpace(e.Data) && e.Data.StartsWith("【data】"))
            {
                //处理正确
            }
            else if (e.Data.StartsWith("【error】"))
            {
                //处理错误
            }
        }    

 

标签:佳博,string,sw,args,蓝牙,var,StartInfo,net,message
来源: https://www.cnblogs.com/Yuuuuu/p/16362007.html