using System; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Printing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using ZXing; using System.Collections; using System.Collections.Generic; using System.Data.SqlClient; using Procurement.ViewModel; using Procurement.EntityFrameworkCore.SqlRepositories; namespace Procurement.Helpers { public class BarCodeHelper { private int TcpPrinterDPI = 200; private int TcpLabelLongMM = 80, TcpLabelHeightMM = 42; private int gap = 2; private LabelViewModel _label=null; private DataTable _formatMasters = null; public void getPrintItems(dynamic items, SqlParameter[] parameters, ISqlRepository _repository) { if (((Dictionary)items).ContainsKey("labelData")) { var labelData = ((ArrayList)items["labelData"]); if (labelData.Count > 0) { string domain = ""; bool isCommandPrint = false, isMovePrinter = false; foreach (var param in parameters) { if (param.ParameterName == "@Domain") { domain = param.Value.ToString(); } if (param.ParameterName == "@IsCommandPrint") { isCommandPrint = Convert.ToBoolean(param.Value); } if (param.ParameterName == "@IsMovePrinter") { isMovePrinter = Convert.ToBoolean(param.Value); } } foreach (var labelItem in labelData) { var item = (Dictionary)labelItem; string label = item["Label"].ToString(); string labelFormat = label.Substring(0, label.IndexOf("@&@")); DataTable dt = _repository.SelectDataBaseBySql("exec pr_SFM_GetCustomLabel @Domain='" + domain + "',@LabelFormat='" + labelFormat + "',@IsCommandPrint=" + isCommandPrint.ToString() + ",@IsMovePrinter=" + isMovePrinter.ToString()); if (dt.Rows.Count > 0) { var printResult = SendNetBarCode(label, dt, isCommandPrint); item["IsAutoStock"] = printResult.isLocalPrint; item["PrinterCommand"] = printResult.printercommand; item["Label"] = printResult.data; item["ErrorMsg"] = ""; } else { item["IsAutoStock"] = true; item["PrinterCommand"] = ""; item["Label"] = ""; item["ErrorMsg"] = labelFormat + "标签格式不存在"; } } } } } #region 打印模式 public (bool isLocalPrint,string data,string printercommand) SendNetBarCode(string labelStr, DataTable formatMasters, bool isCommandPrint = false) { LabelViewModel label = GetLabel(labelStr); _label = label; _formatMasters = formatMasters; string serverName = System.Environment.MachineName; bool isLocalPrint = false; string result = ""; string printercommand = formatMasters.Rows[0]["PrinterCommand"].ToString(); bool isMovePrinter = Convert.ToBoolean(formatMasters.Rows[0]["IsMovePrinter"]); //便携式打印机 if (label.Computer == serverName) { //result=SendPrint(); } else { isLocalPrint = true; if (isCommandPrint) { result = GetPrintDataByCommand(printercommand, isMovePrinter); } else { result = GetPrintData(printercommand); } } return (isLocalPrint, result, printercommand); } private LabelViewModel GetLabel(string labelStr) { var arrStr = labelStr.Split(new string[] { "@&@" }, StringSplitOptions.None); LabelViewModel label = new LabelViewModel(); label.TypeID = arrStr[0];//类型 label.Computer = arrStr[1];//打印机PC label.Printer = arrStr[2];//打印机名称 label.Customer = arrStr[3];//公司名称 if (arrStr.Length >= 5) label.Name = arrStr[4];//描述1 if (arrStr.Length >= 6) label.Descr = arrStr[5];//描述2 if (arrStr.Length >= 7) label.Lable = arrStr[6];//条码 if (arrStr.Length >= 8) label.ItemNum = arrStr[7];//零件号 if (arrStr.Length >= 9) label.BatchNum = arrStr[8];// if (arrStr.Length >= 10) label.Qty = arrStr[9];//回报数量 if (arrStr.Length >= 11) label.Date = arrStr[10];//日期 if (arrStr.Length >= 12) label.Checker = arrStr[11];//检验员编号 if (arrStr.Length >= 13) label.Position = arrStr[12];//方位 if (arrStr.Length >= 14) label.Factory = arrStr[13];//工程 if (arrStr.Length >= 15) label.LineName = arrStr[14];//产线描述 if (arrStr.Length >= 16) label.Other = arrStr[15];//供应商代码 if (arrStr.Length >= 17) label.ALCCode = arrStr[16];//供应商代码 if (arrStr.Length >= 18) label.Model = arrStr[17];//车型 if (arrStr.Length >= 19) label.Location = arrStr[18];//下工序库位 if (arrStr.Length >= 20) label.Line = arrStr[19];//产线编号 if (arrStr.Length >= 21) label.Remark = arrStr[20];//备注 if (arrStr.Length >= 22) label.CustItem = arrStr[21];//客户件号 if (arrStr.Length >= 23) label.Time = arrStr[22];//时间秒 hh:mm;ss if (arrStr.Length >= 24) label.PackQty = arrStr[23];//包装数量 if (arrStr.Length >= 25) label.CkName = arrStr[24];//检验员名称 或单位UM if (arrStr.Length >= 26) label.LuoSite = arrStr[25];//落脚点 if (arrStr.Length >= 27) label.Domain = arrStr[26];//域 if (arrStr.Length >= 28) label.LoNoDesc = arrStr[27];//下工序库位不带描述 if (arrStr.Length >= 29) label.LabColor = arrStr[28];//颜色 if (arrStr.Length > 30) label.LotSerial = arrStr[29];//批号 if (arrStr.Length > 31) label.Period = arrStr[30];//生产周期 if (arrStr.Length >= 32) label.Carton = arrStr[31];//流水号 if (arrStr.Length >= 33) label.OrdNbr = arrStr[32];//单号 if (arrStr.Length >= 34) label.CustItemDescr = arrStr[33];//客户件号名称 if (arrStr.Length >= 35) label.EngineeringNo = arrStr[34];//工程变更号 if (arrStr.Length >= 36) label.CartonQty = arrStr[35];//箱数 if (arrStr.Length >= 37) label.WorkOrd = arrStr[36];//工单号 if (arrStr.Length >= 38) label.CustBarcode = arrStr[37];//客户标签 if (arrStr.Length >= 39) label.MoldNum = arrStr[38];//模具号 if (arrStr.Length >= 40) label.FurnaceLot = arrStr[39];//熔炉号 if (arrStr.Length >= 41) label.Refs = arrStr[40];//腔号 if (arrStr.Length >= 42) label.Shelf = arrStr[41];//货架 if (arrStr.Length >= 43) label.NetWeight = arrStr[42];//净重 if (arrStr.Length >= 44) label.NetWeightUM = arrStr[43];//净重单位 if (arrStr.Length >= 45) label.UM = arrStr[44];//单位 if (arrStr.Length >= 46) label.Desc3 = arrStr[45];//库位名称 if (arrStr.Length >= 47) label.Remarks1 = arrStr[46];//备注1 if (arrStr.Length >= 48) label.Remarks2 = arrStr[47];//备注2 if (arrStr.Length >= 49) label.Remarks3 = arrStr[48];//备注3 if (arrStr.Length >= 50) label.Remarks4 = arrStr[49];//备注4 if (arrStr.Length >= 51) label.Remarks5 = arrStr[50];//备注5 if (arrStr.Length >= 52) label.Remarks6 = arrStr[51];//备注6 if (arrStr.Length >= 53) label.Remarks7 = arrStr[52];//备注7 if (arrStr.Length >= 54) label.Remarks8 = arrStr[53];//备注8 if (arrStr.Length >= 55) label.Factor = arrStr[54];//dell件号 if (arrStr.Length >= 56) label.ShelfLife = arrStr[55]; if (arrStr.Length >= 57) label.GuaranteeDate = arrStr[56]; if (arrStr.Length >= 58) label.Hazard = arrStr[57];//防火危险等级 return label; } #endregion #region 打印指令 private string GetPrintData(string command) { bool isTSC = command == "TSC"; LabelViewModel label = _label; DataTable formatMasters = _formatMasters; DataRow labelSize = formatMasters.Select("Property='0'")[0]; if (labelSize == null) { return ""; } if (labelSize["Long"] == null || Convert.ToInt32(labelSize["Long"].ToString()) == 0) { labelSize["Long"] = 400; } if (labelSize["Wide"] == null || Convert.ToInt32(labelSize["Wide"].ToString()) == 0) { labelSize["Wide"] = 300; } if (!(labelSize["ReMark"] == null || labelSize["ReMark"].ToString()=="")) { int.TryParse(labelSize["ReMark"].ToString(), out TcpLabelHeightMM); if (TcpLabelHeightMM == 0) { TcpLabelHeightMM = 42; } } if (isTSC) { TcpLabelLongMM = Convert.ToInt32(Convert.ToDecimal(labelSize["Long"]) / (Convert.ToDecimal(labelSize["Wide"]) / (TcpLabelHeightMM + 3))); if (!(labelSize["ReMark2"] == null || labelSize["ReMark2"].ToString() == "")) { int.TryParse(labelSize["ReMark2"].ToString(), out gap); if (gap == 0) { gap = 2; } } } var writer = new BarcodeWriterPixelData(); double dpiScale = (TcpPrinterDPI / 25.4 * TcpLabelHeightMM) / Convert.ToInt32(labelSize["Wide"].ToString()); Bitmap bitmap = new Bitmap(Convert.ToInt32(Convert.ToInt32(labelSize["Long"].ToString())*dpiScale), Convert.ToInt32(Convert.ToInt32(labelSize["Wide"].ToString())*dpiScale), PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(bitmap); g.Clear(Color.White); int penWidth = Convert.ToInt32(Math.Ceiling(1 * dpiScale)); var propertys = label.GetType().GetProperties(); foreach (DataRow item in formatMasters.Rows) { item["Long"] = Convert.ToInt32(Convert.ToInt32(item["Long"].ToString()) * dpiScale); item["Wide"] = Convert.ToInt32(Convert.ToInt32(item["Wide"].ToString()) * dpiScale); item["VerticalDistance"] = Convert.ToInt32(Convert.ToInt32(item["VerticalDistance"].ToString()) * dpiScale); item["HorizontalDistance"] = Convert.ToInt32(Convert.ToInt32(item["HorizontalDistance"].ToString()) * dpiScale); item["FontSize"] = Convert.ToInt32(Convert.ToInt32(item["FontSize"].ToString()) * dpiScale); var property = (from p in propertys where p.Name == item["LabelName"].ToString() select p).FirstOrDefault(); string itemVal = ""; if (property!=null) { object obj = property.GetValue(label); if (obj != null) { itemVal = obj.ToString(); } } if (string.IsNullOrEmpty(item["FontStyle"].ToString())) { item["FontStyle"] = "微软雅黑"; } if (item["Property"].ToString() == "5") { writer.Format = BarcodeFormat.CODE_128; float V = Convert.ToInt32(item["VerticalDistance"].ToString()); float H = Convert.ToInt32(item["HorizontalDistance"].ToString()); float L = Convert.ToInt32(item["Long"].ToString()); float W = Convert.ToInt32(item["Wide"].ToString()); var pixdata = writer.Write(itemVal); Bitmap barcode = PixToBitmap(pixdata.Pixels, pixdata.Width, pixdata.Height); g.DrawImage(barcode, (int)H, (int)V, (int)L, (int)W); barcode.Dispose(); barcode = null; } else if (item["Property"].ToString() == "6") { float V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) { V = 1; item["VerticalDistance"] = 1; } float H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) { H = 1; item["HorizontalDistance"] = 1; } float L = Convert.ToInt32(item["Long"].ToString()); if (L == 0) { L = 1; item["Long"] = 10; } float W = Convert.ToInt32(item["Wide"].ToString()); if (W == 0) { W = 1; item["Wide"] = 10; } Bitmap barcode; //DM码Core没有,暂时全用QR writer = new BarcodeWriterPixelData(); writer.Options.PureBarcode = true; if (string.IsNullOrEmpty(item["BarcodeFormat"].ToString())) { writer.Format = BarcodeFormat.QR_CODE; } else { writer.Format = (BarcodeFormat)Enum.Parse(typeof(BarcodeFormat), item["BarcodeFormat"].ToString().ToUpper()); } var pixdata = writer.Write(itemVal); barcode = PixToBitmap(pixdata.Pixels, pixdata.Width, pixdata.Height); g.DrawImage(barcode, (int)H, (int)V, (int)L, (int)W); barcode.Dispose(); barcode = null; } else if (item["Property"].ToString() == "7") { int V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) { V = 1; item["VerticalDistance"] = 1; } int H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) { H = 1; item["HorizontalDistance"] = 1; } int L = Convert.ToInt32(item["Long"].ToString()); if (L == 0) { L = 1; item["Long"] = 10; } int W = Convert.ToInt32(item["Wide"].ToString()); if (W == 0) { W = 1; item["Wide"] = 10; } g.DrawImage(BytesToBitmap((byte[])item["Photo"]), H, V, L, W); } else if (item["Property"].ToString() == "1") { int V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) { V = 1; item["VerticalDistance"] = 1; } int H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) { H = 1; item["HorizontalDistance"] = 1; } int L = Convert.ToInt32(item["Long"].ToString()); if (L == 0) { L = 1; item["Long"] = 10; } int W = Convert.ToInt32(item["Wide"].ToString()); if (W == 0) { W = 1; item["Wide"] = 10; } Pen pen = new Pen(Color.Black, penWidth); g.DrawRectangle(pen, new Rectangle(H, V, L, W)); } else if (item["Property"].ToString() == "0") { continue; } else if (item["Property"].ToString() == "2") { int V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) { V = 1; item["VerticalDistance"] = 1; } int H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) { H = 1; item["HorizontalDistance"] = 1; } int L = Convert.ToInt32(item["Long"].ToString()); int W = Convert.ToInt32(item["Wide"].ToString()); Pen pen = new Pen(Color.Black, penWidth); g.DrawLine(pen, new Point(H, V), new Point(H + L, V + W)); } else { float V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) V = 1; float H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) H = 1; float size = Convert.ToInt32(item["FontSize"].ToString()); if (size == 0) size = 1; string content = ""; if (item["Property"].ToString() == "3") { content = item["LabelContent"].ToString(); } else { if (string.IsNullOrEmpty(itemVal)) { content = " "; } else { content = itemVal; if (!string.IsNullOrEmpty(item["LabelContent"].ToString())) { if (item["LabelName"].ToString() == "Date" && item["LabelContent"].ToString().ToUpper().IndexOf("MM") >= 0) { content = Convert.ToDateTime(itemVal).ToString(item["LabelContent"].ToString()); } else if (item["LabelName"].ToString() == "Period") { int length = item["LabelContent"].ToString().Length - itemVal.Length; string tempContent = ""; for (int i = 1; i <= length; i++) { tempContent += "0"; } content = tempContent + itemVal; } } } } if (Convert.ToBoolean(item["IsCrude"].ToString())) g.DrawString(content, new Font(item["FontStyle"].ToString(), size, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, H, V); else g.DrawString(content, new Font(item["FontStyle"].ToString(), size, System.Drawing.FontStyle.Regular), System.Drawing.Brushes.Black, H, V); } } g.Dispose(); GC.Collect(); if(isTSC) { MemoryStream ms = new MemoryStream(); string result = ""; try { bitmap.Save(ms, ImageFormat.Png); byte[] arrBmp = new byte[ms.Length]; ms.Position = 0; ms.Read(arrBmp, 0, (int)ms.Length); result = Convert.ToBase64String(arrBmp); result = $"{TcpLabelLongMM},{TcpLabelHeightMM+3},{gap}|" + result; } catch (Exception ex) { throw new Exception(ex.Message, ex); } finally { if (ms != null) { ms.Dispose(); ms = null; } } return result; } else { return GetCPCLBytes(bitmap); } } private string GetPrintDataByCommand(string command, bool isMovePrinter) { bool isTSC = command == "TSC"; if (isTSC && !isMovePrinter) TcpPrinterDPI = 300; string txtCommands = ""; LabelViewModel label = _label; DataTable formatMasters = _formatMasters; DataRow labelSize = formatMasters.Select("Property='0'")[0]; if (labelSize == null) { return ""; } if (labelSize["Long"] == null || Convert.ToInt32(labelSize["Long"].ToString()) == 0) { labelSize["Long"] = 400; } if (labelSize["Wide"] == null || Convert.ToInt32(labelSize["Wide"].ToString()) == 0) { labelSize["Wide"] = 300; } if (!(labelSize["ReMark"] == null || labelSize["ReMark"].ToString() == "")) { int.TryParse(labelSize["ReMark"].ToString(), out TcpLabelHeightMM); if (TcpLabelHeightMM == 0) { TcpLabelHeightMM = 42; } } if (isTSC) { TcpLabelLongMM = Convert.ToInt32(Convert.ToDecimal(labelSize["Long"]) / (Convert.ToDecimal(labelSize["Wide"]) / (TcpLabelHeightMM + 3))); if (!(labelSize["ReMark2"] == null || labelSize["ReMark2"].ToString() == "")) { int.TryParse(labelSize["ReMark2"].ToString(), out gap); if (gap == 0) { gap = 2; } } } double dpiScale = (TcpPrinterDPI / 25.4 * TcpLabelHeightMM) / Convert.ToInt32(labelSize["Wide"].ToString()); var propertys = label.GetType().GetProperties(); foreach (DataRow item in formatMasters.Rows) { item["Long"] = Convert.ToInt32(Convert.ToInt32(item["Long"].ToString()) * dpiScale); item["Wide"] = Convert.ToInt32(Convert.ToInt32(item["Wide"].ToString()) * dpiScale); item["VerticalDistance"] = Convert.ToInt32(Convert.ToInt32(item["VerticalDistance"].ToString()) * dpiScale); item["HorizontalDistance"] = Convert.ToInt32(Convert.ToInt32(item["HorizontalDistance"].ToString()) * dpiScale); item["FontSize"] = Convert.ToInt32(Convert.ToInt32(item["FontSize"].ToString()) * dpiScale); var property = (from p in propertys where p.Name == item["LabelName"].ToString() select p).FirstOrDefault(); string itemVal = ""; if (property != null) { object obj = property.GetValue(label); if (obj != null) { itemVal = obj.ToString(); } } if (string.IsNullOrEmpty(item["FontStyle"].ToString())) { item["FontStyle"] = "微软雅黑"; } if (item["Property"].ToString() == "5") { if (string.IsNullOrEmpty(itemVal)) { continue; } float V = Convert.ToInt32(item["VerticalDistance"].ToString()); float H = Convert.ToInt32(item["HorizontalDistance"].ToString()); float L = Convert.ToInt32(item["Long"].ToString()); float W = Convert.ToInt32(item["Wide"].ToString()); if(isTSC) { txtCommands += $"BARCODE {H},{V},\"128\",{(int)W},1,0,3,1,\"{itemVal}\"\r\n"; } else { txtCommands += $"BARCODE 128 1 1 {(int)W} {H} {V} {itemVal}\r\n"; } } else if (item["Property"].ToString() == "6") { if (string.IsNullOrEmpty(itemVal)) { continue; } float V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) { V = 1; item["VerticalDistance"] = 1; } float H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) { H = 1; item["HorizontalDistance"] = 1; } float L = Convert.ToInt32(item["Long"].ToString()); if (L == 0) { L = 1; item["Long"] = 10; } float W = Convert.ToInt32(item["Wide"].ToString()); if (W == 0) { W = 1; item["Wide"] = 10; } int qrSize = (int)(Math.Round(L / 8 / 10 + 3)); H = H + Convert.ToInt32(12 * dpiScale); if (isTSC) { txtCommands += $"QRCODE {H},{V},L,{qrSize+1},A,0,\"{itemVal}\"\r\n"; } else { txtCommands += $"B QR {H} {V} M 2 U {qrSize}\r\n"; txtCommands += $"MA,{itemVal}\r\n"; txtCommands += $"ENDQR\r\n"; } } else if (item["Property"].ToString() == "7") { //int V = Convert.ToInt32(item["VerticalDistance"].ToString()); //if (V == 0) //{ // V = 1; // item["VerticalDistance"] = 1; //} //int H = Convert.ToInt32(item["HorizontalDistance"].ToString()); //if (H == 0) //{ // H = 1; // item["HorizontalDistance"] = 1; //} //int L = Convert.ToInt32(item["Long"].ToString()); //if (L == 0) //{ // L = 1; // item["Long"] = 10; //} //int W = Convert.ToInt32(item["Wide"].ToString()); //if (W == 0) //{ // W = 1; // item["Wide"] = 10; //} //if (item["Photo"] != DBNull.Value) //{ // Bitmap logbitmap = new Bitmap(L, W, PixelFormat.Format24bppRgb); // Graphics g = Graphics.FromImage(logbitmap); // g.Clear(Color.White); // g.DrawImage(BytesToBitmap((byte[])item["Photo"]), 0, 0, L, W); // txtCommands += GetCPCLBytes(logbitmap, true,H,V); // g.Dispose(); // logbitmap.Dispose(); //} } else if (item["Property"].ToString() == "1") { int V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) { V = 1; item["VerticalDistance"] = 1; } int H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) { H = 1; item["HorizontalDistance"] = 1; } int L = Convert.ToInt32(item["Long"].ToString()); if (L == 0) { L = 1; item["Long"] = 10; } int W = Convert.ToInt32(item["Wide"].ToString()); if (W == 0) { W = 1; item["Wide"] = 10; } if (isTSC) { txtCommands += $"BOX {H},{V},{H + L},{V + W},3\r\n"; } else { txtCommands += $"BOX {H} {V} {H + L} {V + W} 1\r\n"; } } else if (item["Property"].ToString() == "0") { continue; } else if (item["Property"].ToString() == "2") { int V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) { V = 1; item["VerticalDistance"] = 1; } int H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) { H = 1; item["HorizontalDistance"] = 1; } int L = Convert.ToInt32(item["Long"].ToString()); int W = Convert.ToInt32(item["Wide"].ToString()); if (isTSC) { L = L == 0 ? 3 : L; W = W == 0 ? 3 : W; txtCommands += $"BAR {H},{V},{L},{W}\r\n"; } else { txtCommands += $"LINE {H} {V} {H + L} {V + W} 1\r\n"; } } else { float V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) V = 1; float H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) H = 1; float size = Convert.ToInt32(item["FontSize"].ToString()); if (size == 0) size = 1; string content = ""; bool isCrude = (bool)item["IsCrude"]; if (item["Property"].ToString() == "3") { content = item["LabelContent"].ToString().Trim(); } else { if (string.IsNullOrEmpty(itemVal)) { content = ""; } else { content = itemVal; if (!string.IsNullOrEmpty(item["LabelContent"].ToString())) { if (item["LabelName"].ToString() == "Date" && item["LabelContent"].ToString().ToUpper().IndexOf("MM") >= 0) { content = Convert.ToDateTime(itemVal).ToString(item["LabelContent"].ToString()); } else if (item["LabelName"].ToString() == "Period") { int length = item["LabelContent"].ToString().Length - itemVal.Length; string tempContent = ""; for (int i = 1; i <= length; i++) { tempContent += "0"; } content = tempContent + itemVal; } } } } if (!string.IsNullOrEmpty(content)) { if (isTSC) { string font = "4"; int multiplication = 1; //if (item["Property"].ToString() == "3" || item["ReMark"].ToString().ToUpper() == "ZH-CN") if (item["ReMark"].ToString().ToUpper() == "ZH-CN") { font = "TSS24.BF2"; multiplication = 2; int.TryParse(item["ReMark2"].ToString(), out multiplication); if (multiplication == 0) { multiplication = 2; } } else { int font2 = 4; int.TryParse(item["ReMark2"].ToString(), out font2); if (font2 == 0) { font2 = 4; } font = font2.ToString(); } txtCommands += $"TEXT {H},{V},\"{font}\",0,{multiplication},{multiplication},\"{content}\"\r\n"; } else { if (isCrude) { txtCommands += "SETBOLD 2\r\n"; } txtCommands += $"TEXT GBUNSG24.CPF 0 {H} {V} {content}\r\n"; if (isCrude) { txtCommands += "SETBOLD 0\r\n"; } } } } } string commands = ""; if (isTSC) { commands = $"SIZE {TcpLabelLongMM} mm,{TcpLabelHeightMM+3} mm\r\n"; commands += $"GAP {gap} mm,0 mm\r\n"; commands += "CLS\r\n"; commands += "REFERENCE 3 mm,3 mm\r\n"; commands += "DIRECTION 1,0\r\n"; commands += "DENSITY 13\r\n"; commands += txtCommands; commands += "PRINT 1\r\n"; commands += "SOUND 2,100\r\n"; } else { commands = $"! {0} {TcpPrinterDPI} {TcpPrinterDPI} {(int)(TcpPrinterDPI / 25.4f * TcpLabelHeightMM)} 1\r\n"; //commands += "PREFEED -24\r\n"; //commands += "TONE 30\r\n"; commands += "ENCODING GB18030\r\n"; commands += "SETMAG 1 1\r\n"; commands += txtCommands; commands += "FORM\r\nPRINT\r\n"; } return commands; } #endregion #region 生成CPCL图像打印指令 private string GetCPCLBytes(Bitmap bitmap) { int RowRealBytesCount = 0; int GraphHeight = 0; byte[] bmpData = GetBitmapData(bitmap, ref RowRealBytesCount, ref GraphHeight); int bmpDataLength = bmpData.Length; for (int i = 0; i < bmpDataLength; i++) { bmpData[i] ^= 0xFF; } int Copies = 1; string textHex = BitConverter.ToString(bmpData).Replace("-", string.Empty); string text = string.Format("! {0} {1} {2} {3} {4}\r\nPREFEED {5}\r\nTONE {6}\r\nCENTER\r\nEG {7} {8} {9} {10} {11}\r\nFORM\r\nPRINT\r\n", 0, TcpPrinterDPI, TcpPrinterDPI, (int)(TcpPrinterDPI / 25.4f * TcpLabelHeightMM), Copies, -24, 30, RowRealBytesCount, GraphHeight, 0, 0, textHex ); return text; } #endregion #region 获取单色位图数据 private byte[] GetBitmapData(Bitmap srcBmp, ref int RowRealBytesCount, ref int GraphHeight) { MemoryStream dstStream = new MemoryStream(); Bitmap dstBmp = null; byte[] dstBuffer = null; byte[] result = null; try { dstBmp = ConvertToGrayscale(srcBmp); dstBmp.Save(dstStream, ImageFormat.Bmp); dstBuffer = dstStream.ToArray(); int bfOffBits = BitConverter.ToInt32(dstBuffer, 10); int GraphWidth = srcBmp.Width; GraphHeight = srcBmp.Height; RowRealBytesCount = 0; if ((GraphWidth % 8) > 0) { RowRealBytesCount = GraphWidth / 8 - 1; } else { RowRealBytesCount = GraphWidth / 8; } int RowSize = (((GraphWidth) + 31) >> 5) << 2; result = new byte[GraphHeight * RowRealBytesCount]; for (int i = 0; i < GraphHeight; i++) { Array.Copy(dstBuffer, bfOffBits + (GraphHeight - 1 - i) * RowSize, result, i * RowRealBytesCount, RowRealBytesCount); } } catch (Exception ex) { throw new Exception(ex.Message, ex); } finally { if (dstStream != null) { dstStream.Dispose(); dstStream = null; } if (srcBmp != null) { srcBmp.Dispose(); srcBmp = null; } if (dstBmp != null) { dstBmp.Dispose(); dstBmp = null; } } return result; } private Bitmap ConvertToGrayscale(Bitmap pimage) { Bitmap source = null; // If original bitmap is not already in 32 BPP, ARGB format, then convert if (pimage.PixelFormat != PixelFormat.Format32bppArgb) { source = new Bitmap(pimage.Width, pimage.Height, PixelFormat.Format32bppArgb); source.SetResolution(pimage.HorizontalResolution, pimage.VerticalResolution); using (Graphics g = Graphics.FromImage(source)) { g.DrawImageUnscaled(pimage, 0, 0); } } else { source = pimage; } // Lock source bitmap in memory BitmapData sourceData = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); // Copy image data to binary array int imageSize = sourceData.Stride * sourceData.Height; byte[] sourceBuffer = new byte[imageSize]; Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize); // Unlock source bitmap source.UnlockBits(sourceData); // Create destination bitmap Bitmap destination = new Bitmap(source.Width, source.Height, PixelFormat.Format1bppIndexed); // Lock destination bitmap in memory BitmapData destinationData = destination.LockBits(new Rectangle(0, 0, destination.Width, destination.Height), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed); // Create destination buffer imageSize = destinationData.Stride * destinationData.Height; byte[] destinationBuffer = new byte[imageSize]; int sourceIndex = 0; int destinationIndex = 0; int pixelTotal = 0; byte destinationValue = 0; int pixelValue = 128; int height = source.Height; int width = source.Width; int threshold = 500; // Iterate lines for (int y = 0; y < height; y++) { sourceIndex = y * sourceData.Stride; destinationIndex = y * destinationData.Stride; destinationValue = 0; pixelValue = 128; // Iterate pixels for (int x = 0; x < width; x++) { // Compute pixel brightness (i.e. total of Red, Green, and Blue values) pixelTotal = sourceBuffer[sourceIndex + 1] + sourceBuffer[sourceIndex + 2] + sourceBuffer[sourceIndex + 3]; if (pixelTotal > threshold) { destinationValue += (byte)pixelValue; } if (pixelValue == 1) { destinationBuffer[destinationIndex] = destinationValue; destinationIndex++; destinationValue = 0; pixelValue = 128; } else { pixelValue >>= 1; } sourceIndex += 4; } if (pixelValue != 128) { destinationBuffer[destinationIndex] = destinationValue; } } // Copy binary image data to destination bitmap Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, imageSize); // Unlock destination bitmap destination.UnlockBits(destinationData); // Dispose of source if not originally supplied bitmap if (source != pimage) { source.Dispose(); } // Return return destination; } #endregion #region 字节数组转换为位图 /// /// 将一个字节数组转换为位图 /// /// 显示字节数组 /// 图像宽度 /// 图像高度 /// 位图 private Bitmap PixToBitmap(byte[] pixValue, int width, int height) { //// 申请目标位图的变量,并将其内存区域锁定 var m_currBitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); var m_rect = new Rectangle(0, 0, width, height); var m_bitmapData = m_currBitmap.LockBits(m_rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb); IntPtr iptr = m_bitmapData.Scan0; // 获取bmpData的内存起始位置 //// 用Marshal的Copy方法,将刚才得到的内存字节数组复制到BitmapData中 System.Runtime.InteropServices.Marshal.Copy(pixValue, 0, iptr, pixValue.Length); m_currBitmap.UnlockBits(m_bitmapData); //// 算法到此结束,返回结果 return m_currBitmap; } //byte[] 转换 Bitmap private Bitmap BytesToBitmap(byte[] Bytes) { MemoryStream stream = null; try { stream = new MemoryStream(Bytes); return new Bitmap((Image)new Bitmap(stream)); } catch (ArgumentNullException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } finally { stream.Close(); } } #endregion } }