PrintLabel.cs 22.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
using Microsoft.VisualBasic.ApplicationServices;
using PrintLabel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Management;
using System.Net.NetworkInformation;
using System.Printing;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;

namespace Asa
{
    public class PrintLabel
    {
        public delegate void PrintStatusEvent(PrinterStatus sta, string msg);
        public event PrintStatusEvent PrintStatusChanged;

        private System.Threading.Thread tRun;

        string dir;
        public PrintLabel(string dir, int dpi = 100)
        {
            Common.MULTIPLE = dpi;
            Common.LabelPrint = new BLL.LabelPrint();
            this.dir = dir;
            Common.LabelPrint.Load(dir);
        }

        /// <summary>
        /// 加载标签
        /// </summary>
        /// <param name="labelName"></param>
        public void LoadLabel(string labelName)
        {
            Common.LabelPrint.LabelName = labelName;
        }

        /// <summary>
        /// 编辑标签
        /// </summary>
        public void EditLabel()
        {
            FrmLabel frm = new FrmLabel();
            frm.ShowDialog();
        }

        public string[] GetLabelName()
        {
            return Common.LabelPrint.GetName();
        }

        public string[] GetPrinterName()
        {
            List<string> list = new List<string>();
            foreach (string ss in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                list.Add(ss);
            return list.ToArray();
        }

        /// <summary>
        /// 打印机
        /// </summary>
        /// <param name="name">打印机名字</param>
        /// <param name="landscape">打印方向,横向纵向</param>
        public void Printer(string name, bool landscape)
        {
            Common.LabelPrint.PrinterName = name;
            Common.LabelPrint.PrintLandscape = landscape;
        }

        public void SetResolution(int printerDPI)
        {
            Common.MULTIPLE = printerDPI;
            Common.LabelPrint = new BLL.LabelPrint();
            Common.LabelPrint.Load(dir);
        }

        public bool Rotate180 { set => Common.LabelPrint.Rotate180 = value; get => Common.LabelPrint.Rotate180; }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Bitmap Print(Dictionary<string, string> key)
        {
            Bitmap bmp = Common.LabelPrint.PrintLast(key, out string[] codeContent);
            tRun = new System.Threading.Thread(new System.Threading.ThreadStart(GetStatus));
            tRun.Start();
            return bmp;
        }
        public Bitmap PrintPreview(Dictionary<string, string> key)
        {
            //Common.LabelPrint.labelIdx = 1;
            Bitmap bmp = Common.LabelPrint.PrintPreview(key, out string[] code);
            return bmp;
        }
        /// <summary>
        /// 打印机状态
        /// </summary>
        public enum PrinterStatus
        {
            /// <summary>
            /// 其他
            /// </summary>
            Other = 1,
            /// <summary>
            /// 未知
            /// </summary>
            Unknown,
            /// <summary>
            /// 空闲
            /// </summary>
            Idle,
            /// <summary>
            /// 正在打印中
            /// </summary>
            Printing,
            /// <summary>
            /// 预热
            /// </summary>
            Preheat,
            /// <summary>
            /// 停止打印
            /// </summary>
            Stop,
            /// <summary>
            /// 打印中
            /// </summary>
            Print,
            /// <summary>
            /// 离线
            /// </summary>
            Offline
        }




        /// <summary>
        /// 获取打印机的当前状态
        /// </summary>
        public void GetStatus()
        {
            int n = 0;
            int timeout = 0;
            string msg = "无";
            PrinterStatus sta = PrinterStatus.Other;
            string path = "win32_printer.DeviceId='" + Common.LabelPrint.PrinterName + "'";
            ManagementObject printer = new ManagementObject(path);

            while (true)
            {
                int ret = (int)PrinterStatus.Idle;
                try
                {
                    printer.Get();
                    ret = Convert.ToInt32(printer.Properties["PrinterStatus"].Value);
                }
                catch { }
                sta = (PrinterStatus)ret;
                switch(sta)
                {
                    case PrinterStatus.Other:
                        msg = "其他";
                        n = 3;
                        break;
                    case PrinterStatus.Unknown:
                        msg = "未知";
                        n = 3;
                        break;
                    case PrinterStatus.Stop:
                        msg = "停止";
                        n = 3;
                        break;
                    case PrinterStatus.Offline:
                        msg = "离线";
                        n = 3;
                        break;
                    case PrinterStatus.Preheat:
                        msg = "预热";
                        break;
                    case PrinterStatus.Print:
                        msg = "打印中";
                        n = 1;
                        break;
                    case PrinterStatus.Printing:
                        msg = "打印中";
                        n = 1;
                        break;
                    case PrinterStatus.Idle:
                        if (n == 1)
                        {
                            msg += ",空闲";
                            n = 2;
                        }
                        break;
                    default:
                        msg = "default";
                        n = 3;
                        break;
                }
                if (n == 3 || n == 2)
                    break;
                timeout += 500;
                System.Threading.Thread.Sleep(500);

                if (timeout >= 15000)
                    break;
            }
            PrintStatusChanged?.Invoke(sta, msg);

        }

        private void GetPrintStatus()
        {
            PrintQueue pq = LocalPrintServer.GetDefaultPrintQueue();
            switch (pq.QueueStatus)
            {
                //正常状态
                case PrintQueueStatus.None:
                    Console.WriteLine("正常运行");
                    break;
                //纸未取走
                case PrintQueueStatus.OutputBinFull:
                    Console.WriteLine("未取走");
                    break;
                //缺纸
                case PrintQueueStatus.PaperOut:
                    Console.WriteLine("缺纸");
                    break;
                //打印
                case PrintQueueStatus.Printing:
                    Console.WriteLine("正在打印");
                    break;
                default:
                    Console.WriteLine(pq.QueueStatus);
                    break;
            }

        }
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="key"></param>
        /// <returns>是否打印成功</returns>
        public bool PrintToTsc(Dictionary<string, string> key,int x,int y,out TscStauts tscStauts)
        {
            tscStauts = CheckTscStatus();
            if (tscStauts != 0) {
                var err = (TscStauts)tscStauts;
                Console.WriteLine($"Error: {err}");
                return false;
            }
            var t = Task.Run(() =>
            {
                Bitmap bmp = null;
                try
                {
                    bmp = PrintPreview(key);                    
                    var mm = Common.PxToMM(bmp.Width);
                    var nn = Common.PxToMM(bmp.Height);
                    TSCLIB_DLL.openport("USB");
                    SendCommand("GETSENSOR(\"PEEL\")");
                    SendCommand($"SIZE {mm:0.00} mm, {nn:0.00} mm");
                    SendCommand("GAP 3 mm,0.3 mm");
                    SendCommand("SET CUTTER OFF");
                    SendCommand("SET RIBBON OFF");  //使用碳带
                    SendCommand("SET ENCODER OFF"); //碳带编码器检测
                    SendCommand("OFFSET -10 mm"); //出纸偏移
                    SendCommand("SPEED 9"); //速度最大15
                    SendCommand("DENSITY 15"); //浓度
                    SendCommand("DIRECTION 1");
                    SendCommand("SET PEEL OFF");
                    TSCLIB_DLL.clearbuffer();
                    TSCLIB_DLL.sendpicture(x, y, bmp);
                    TSCLIB_DLL.printlabel("1", "1");
                    TSCLIB_DLL.closeport();
                    Task.Delay(350).Wait();
                }
                catch (Exception e) { }
                finally {
                    bmp?.Dispose();
                }
            });
            t.Wait(1000);
            tscStauts = CheckTscStatus();
            Console.WriteLine("After print:" + tscStauts);
            if (tscStauts == TscStauts.打印中 || tscStauts == TscStauts.准备就绪 || tscStauts == TscStauts.None)
                return true;
            else {
                return false;
            }            
            //Console.WriteLine("usbportqueryprinter:" + TSCLIB_DLL.usbportqueryprinter());
        }

        void SendCommand(string command)
        {
            Console.WriteLine(TSCLIB_DLL.sendcommand(command));
        }

        Task<Bitmap> printt;
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="key"></param>
        /// <returns>是否打印成功</returns>
        public bool PrintToTsc_New(Dictionary<string, string> key, TscConfig tscConfig, out TscStauts tscStauts,out Bitmap bitmap)
        {
            bitmap = null;
            tscStauts = CheckTscStatus();
            if (tscStauts != 0)
            {
                var err = (TscStauts)tscStauts;
                Console.WriteLine($"Error: {err}");
                return false;
            }
            printt=Task.Run(new Func<Bitmap>(() =>
            {
                Bitmap bmp = null;
                try
                {
                    bmp = PrintPreview(key);
                    bmp.Save(Path.Combine(System.Windows.Forms.Application.StartupPath, "label.bmp"));
                    var mm = Common.PxToMM(bmp.Width);
                    var nn = Common.PxToMM(bmp.Height);

                    TSCSDK.driver TSCLIB_DLL = new TSCSDK.driver();
                    TSCLIB_DLL.openport(tscConfig.PrinterName);
                    TSCLIB_DLL.sendcommand($"SIZE {mm:0.00} mm, {nn:0.00} mm");
                    //TSCLIB_DLL.sendcommand($"GAP {tscConfig.Gap} mm,{tscConfig.GapOffset} mm");
                    //TSCLIB_DLL.sendcommand("SET STRIPER ON");//撕纸状态
                    //TSCLIB_DLL.sendcommand("SET CUTTER OFF");//裁剪模式
                    //TSCLIB_DLL.sendcommand("SET PEEL OFF");//剥离模式
                    //TSCLIB_DLL.sendcommand("SET RIBBON OFF");  //使用碳带
                    //TSCLIB_DLL.sendcommand("SET ENCODER OFF"); //碳带编码器检测
                    //TSCLIB_DLL.sendcommand($"OFFSET {tscConfig.Offset} mm"); //出纸偏移
                    //TSCLIB_DLL.sendcommand($"SPEED {tscConfig.Speed}"); //速度最大15
                    //TSCLIB_DLL.sendcommand($"DENSITY {tscConfig.Density}"); //浓度最大15 
                    //TSCLIB_DLL.sendcommand($"DIRECTION {tscConfig.Direction}");
                    
                    TSCLIB_DLL.clearbuffer();
                    TSCLIB_DLL.sendpicture(tscConfig.x, tscConfig.y, bmp);
                    TSCLIB_DLL.printlabel("1", "1");
                    TSCLIB_DLL.closeport();                    
                    //Task.Delay(350).Wait();
                    //bmp.Save(System.Windows.Forms.Application.StartupPath + $"\\PrintImage\\{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff")}.jpg");
                    return bmp;
                }
                catch (Exception e) 
                {
                    return bmp;
                }
                finally
                {
                    //bmp?.Dispose();
                }
            }));            
            tscStauts = CheckTscStatus();
            Console.WriteLine("After print:" + tscStauts);
            Task.Delay(500).Wait();
            if (printt.IsCompleted)
            {
                bitmap = printt.Result;
            }
            if (tscStauts == TscStauts.打印中 || tscStauts == TscStauts.准备就绪 || tscStauts == TscStauts.None)
            {
               
                return true;
            }               
            else
            {
                return false;
            }
            //Console.WriteLine("usbportqueryprinter:" + TSCLIB_DLL.usbportqueryprinter());
        }      

        /// <summary>
        /// X400机器使用此打印方法
        /// </summary>
        /// <param name="key"></param>
        /// <param name="tscConfig"></param>
        /// <param name="tscStauts"></param>
        /// <returns></returns>
        public bool PrintToTsc_X400(Dictionary<string, string> key, TscConfig tscConfig, out TscStauts tscStauts)
        {
            tscStauts = CheckTscStatus();
            if (tscStauts != 0)
            {
                var err = (TscStauts)tscStauts;
                Console.WriteLine($"Error: {err}");
                return false;
            }
            Task.Run(() =>
            {
                Bitmap bmp = null;
                try
                {
                    bmp = PrintPreview(key);
                    var mm = Common.PxToMM(bmp.Width);
                    var nn = Common.PxToMM(bmp.Height);
                    TSCSDK.driver TSCLIB_DLL = new TSCSDK.driver();
                    TSCLIB_DLL.openport(tscConfig.PrinterName);
                    TSCLIB_DLL.sendcommand($"SIZE {mm:0.00} mm, {nn:0.00} mm");
                    TSCLIB_DLL.sendcommand($"GAP {tscConfig.Gap} mm,{tscConfig.GapOffset} mm");//默认值2 0
                    TSCLIB_DLL.sendcommand($"SPEED {tscConfig.Speed}");//速度
                    TSCLIB_DLL.sendcommand($"DENSITY {tscConfig.Density}"); //浓度最大15             
                    TSCLIB_DLL.sendcommand("SET RIBBON OFF");
                    TSCLIB_DLL.sendcommand($"DIRECTION {tscConfig.Direction},{tscConfig.Directions}");//默认值为1,0
                    TSCLIB_DLL.sendcommand("REFERENCE 0,0");
                    TSCLIB_DLL.sendcommand($"OFFSET {tscConfig.Offset} mm"); //出纸偏移                               
                    TSCLIB_DLL.sendcommand("SET STRIPER OFF");//撕纸状态
                    TSCLIB_DLL.sendcommand("SET CUTTER OFF");
                    TSCLIB_DLL.sendcommand("SET PEEL ON");//剥纸模式
                    TSCLIB_DLL.clearbuffer();
                    TSCLIB_DLL.sendpicture(tscConfig.x, tscConfig.y, bmp);
                    TSCLIB_DLL.printlabel("1", "1");
                    TSCLIB_DLL.closeport();
                    Task.Delay(350).Wait();
                }
                catch (Exception)
                {
                }
                finally
                {
                    bmp?.Dispose();
                }
            });
            tscStauts = CheckTscStatus();
            Console.WriteLine("After print:" + tscStauts);
            if (tscStauts == TscStauts.打印中 || tscStauts == TscStauts.准备就绪 || tscStauts == TscStauts.None)
                return true;
            else
            {
                return false;
            }
            //Console.WriteLine("usbportqueryprinter:" + TSCLIB_DLL.usbportqueryprinter());
        }

        /// <summary>
        /// 完整的打印逻辑
        /// </summary>
        /// <param name="key"></param>
        /// <param name="tscConfig"></param>
        /// <param name="tscStauts"></param>
        /// <returns></returns>
        public bool PrintToTsc_X6(Dictionary<string, string> key, TscConfig tscConfig, out TscStauts tscStauts)
        {
            Bitmap bmp = null;
            try
            {
                bmp = PrintPreview(key);
                var mm = Common.PxToMM(bmp.Width);
                var nn = Common.PxToMM(bmp.Height);
                TSCSDK.driver TSCLIB_DLL = new TSCSDK.driver();
                TSCLIB_DLL.openport(tscConfig.PrinterName);
                TSCLIB_DLL.sendcommand($"SIZE 59.9 mm, 39.9 mm");
                TSCLIB_DLL.sendcommand($"GAP 2 mm,0 mm");
                TSCLIB_DLL.sendcommand($"SPEED 11");//速度
                TSCLIB_DLL.sendcommand($"DENSITY 15"); //浓度最大15             
                TSCLIB_DLL.sendcommand("SET RIBBON OFF");
                TSCLIB_DLL.sendcommand($"DIRECTION 1,0");
                TSCLIB_DLL.sendcommand("REFERENCE 0,0");
                TSCLIB_DLL.sendcommand($"OFFSET 10 mm"); //出纸偏移                               
                TSCLIB_DLL.sendcommand("SET STRIPER ON");
                TSCLIB_DLL.sendcommand("SET CUTTER OFF");
                //TSCLIB_DLL.sendcommand("SET PEEL ON");
                TSCLIB_DLL.clearbuffer();
                TSCLIB_DLL.sendpicture(tscConfig.x, tscConfig.y, bmp);
                TSCLIB_DLL.printlabel("1", "1");
                TSCLIB_DLL.closeport();
                Task.Delay(350).Wait();
            }
            catch (Exception)
            {
            }
            finally
            {
                bmp?.Dispose();
            }
            tscStauts = TscStauts.打印中;
            return true;
            //Console.WriteLine("usbportqueryprinter:" + TSCLIB_DLL.usbportqueryprinter());
        }

        public bool PrintCommandToTsc(string command, TscConfig tscConfig, out TscStauts tscStauts)
        {
            tscStauts = CheckTscStatus();
            if (tscStauts != 0)
            {
                var err = (TscStauts)tscStauts;
                Console.WriteLine($"Error: {err}");
                return false;
            }
            var printt = Task.Run(() =>
            {                
                try
                {
                    TSCSDK.driver TSCLIB_DLL = new TSCSDK.driver();
                    TSCLIB_DLL.openport(tscConfig.PrinterName);
                    var commands = command.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < commands.Length; i++) {
                        if (!commands[i].StartsWith("PRINT"))
                            TSCLIB_DLL.sendcommand(commands[i].Trim());
                        else
                            TSCLIB_DLL.printlabel("1", "1");
                    }
                    TSCLIB_DLL.closeport();

                }
                catch (Exception e)
                {
                }
                finally
                {
                    //bmp?.Dispose();
                }
            });
            tscStauts = CheckTscStatus();
            Console.WriteLine("After print:" + tscStauts);
            Task.Delay(500).Wait();
            if (printt.IsCompleted)
            {
            }
            if (tscStauts == TscStauts.打印中 || tscStauts == TscStauts.准备就绪 || tscStauts == TscStauts.None)
            {

                return true;
            }
            else
            {
                return false;
            }
            //Console.WriteLine("usbportqueryprinter:" + TSCLIB_DLL.usbportqueryprinter());
        }
        public TscStauts CheckTscStatus() {
            //return TscStauts.准备就绪;
            TscStauts s = TscStauts.None;
            var t = Task.Run(() => {
                Console.WriteLine("TID:"+ GetCurrentThreadId().ToString("X"));
                for (int i = 0; i < 3; i++)
                {
                    try
                    {
                        s = (TscStauts)TSCLIB_DLL.usbportqueryprinter();
                        break;
                    }
                    catch
                    {                        
                        s = TscStauts.其它错误;
                    }
                }
            });
            if (!t.Wait(3000))
                Console.WriteLine("usbportqueryprinter time out");
            return s;
        }
        [DllImport("kernel32.dll")]
        static extern int GetCurrentThreadId();
        
    }
    public enum TscStauts
    {
        准备就绪 = 0x0,
        打印头开启 = 0x1,
        纸张卡纸 = 0x02,
        打印头开启并且纸张卡纸 = 0x03,
        纸张缺纸 = 0x04,
        打印头开启并且纸张缺纸 = 0x05,
        无碳带 = 0x08,
        打印头开启并且无碳带 = 0x09,
        纸张卡纸并且无碳带 = 0x0A,
        打印头开启_纸张卡纸并且无碳带 = 0x0B,
        纸张缺纸并且无碳带 = 0x0C,
        打印头开启_纸张缺纸并且无碳带 = 0x0D,
        暂停 = 0x10,
        Error = 0x14,
        打印中 = 0x20,
        其它错误 = 0x80,
        None = 0xFD,
        Offline = 0xFF,
    }
    enum TscStautsaa { 
     a = 1,
     b = 1<<1,
     c = 1<<2,
    }
    public class TscConfig
    {
        /// <summary>
        /// 打印机名称
        /// </summary>
        public string PrinterName = "TSC TTP-342 Pro";
        /// <summary>
        /// 纸张间隙mm,默认2mm
        /// </summary>
        public double Gap = 2;
        /// <summary>
        /// 纸张间隙偏移量mm,默认0.3mm
        /// </summary>
        public double GapOffset = 0;
        /// <summary>
        /// 打印方向 1横向,0纵向,默认1
        /// </summary>
        public int Direction = 1;
        public int Directions = 0;
        /// <summary>
        /// 出纸偏移量mm,默认-10mm
        /// </summary>
        public double Offset = -10;
        /// <summary>
        /// 打印速度1-15,默认9
        /// </summary>
        public int Speed = 9;
        /// <summary>
        /// 打印浓度 1-15,默认12
        /// </summary>
        public int Density = 12;
        /// <summary>
        /// 打印x轴偏移量
        /// </summary>
        public int x = 0;
        /// <summary>
        /// 打印y轴偏移量
        /// </summary>
        public int y = 0;
        
    }
}