BarCodeHelper.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. using System;
  2. using System.Data;
  3. using System.Drawing;
  4. using System.Drawing.Drawing2D;
  5. using System.Drawing.Imaging;
  6. using System.Drawing.Printing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Runtime.InteropServices;
  10. using ZXing;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.Data.SqlClient;
  14. using Procurement.ViewModel;
  15. using Procurement.EntityFrameworkCore.SqlRepositories;
  16. namespace Procurement.Helpers
  17. {
  18. public class BarCodeHelper
  19. {
  20. private int TcpPrinterDPI = 200;
  21. private int TcpLabelLongMM = 80, TcpLabelHeightMM = 42;
  22. private int gap = 2;
  23. private LabelViewModel _label=null;
  24. private DataTable _formatMasters = null;
  25. public void getPrintItems(dynamic items, SqlParameter[] parameters, ISqlRepository _repository)
  26. {
  27. if (((Dictionary<string, object>)items).ContainsKey("labelData"))
  28. {
  29. var labelData = ((ArrayList)items["labelData"]);
  30. if (labelData.Count > 0)
  31. {
  32. string domain = "";
  33. bool isCommandPrint = false, isMovePrinter = false;
  34. foreach (var param in parameters)
  35. {
  36. if (param.ParameterName == "@Domain")
  37. {
  38. domain = param.Value.ToString();
  39. }
  40. if (param.ParameterName == "@IsCommandPrint")
  41. {
  42. isCommandPrint = Convert.ToBoolean(param.Value);
  43. }
  44. if (param.ParameterName == "@IsMovePrinter")
  45. {
  46. isMovePrinter = Convert.ToBoolean(param.Value);
  47. }
  48. }
  49. foreach (var labelItem in labelData)
  50. {
  51. var item = (Dictionary<string, object>)labelItem;
  52. string label = item["Label"].ToString();
  53. string labelFormat = label.Substring(0, label.IndexOf("@&@"));
  54. DataTable dt = _repository.SelectDataBaseBySql("exec pr_SFM_GetCustomLabel @Domain='" + domain + "',@LabelFormat='" + labelFormat + "',@IsCommandPrint=" + isCommandPrint.ToString() + ",@IsMovePrinter=" + isMovePrinter.ToString());
  55. if (dt.Rows.Count > 0)
  56. {
  57. var printResult = SendNetBarCode(label, dt, isCommandPrint);
  58. item["IsAutoStock"] = printResult.isLocalPrint;
  59. item["PrinterCommand"] = printResult.printercommand;
  60. item["Label"] = printResult.data;
  61. item["ErrorMsg"] = "";
  62. }
  63. else
  64. {
  65. item["IsAutoStock"] = true;
  66. item["PrinterCommand"] = "";
  67. item["Label"] = "";
  68. item["ErrorMsg"] = labelFormat + "标签格式不存在";
  69. }
  70. }
  71. }
  72. }
  73. }
  74. #region 打印模式
  75. public (bool isLocalPrint,string data,string printercommand) SendNetBarCode(string labelStr, DataTable formatMasters, bool isCommandPrint = false)
  76. {
  77. LabelViewModel label = GetLabel(labelStr);
  78. _label = label;
  79. _formatMasters = formatMasters;
  80. string serverName = System.Environment.MachineName;
  81. bool isLocalPrint = false;
  82. string result = "";
  83. string printercommand = formatMasters.Rows[0]["PrinterCommand"].ToString();
  84. bool isMovePrinter = Convert.ToBoolean(formatMasters.Rows[0]["IsMovePrinter"]); //便携式打印机
  85. if (label.Computer == serverName)
  86. {
  87. //result=SendPrint();
  88. }
  89. else
  90. {
  91. isLocalPrint = true;
  92. if (isCommandPrint)
  93. {
  94. result = GetPrintDataByCommand(printercommand, isMovePrinter);
  95. }
  96. else
  97. {
  98. result = GetPrintData(printercommand);
  99. }
  100. }
  101. return (isLocalPrint, result, printercommand);
  102. }
  103. private LabelViewModel GetLabel(string labelStr)
  104. {
  105. var arrStr = labelStr.Split(new string[] { "@&@" }, StringSplitOptions.None);
  106. LabelViewModel label = new LabelViewModel();
  107. label.TypeID = arrStr[0];//类型
  108. label.Computer = arrStr[1];//打印机PC
  109. label.Printer = arrStr[2];//打印机名称
  110. label.Customer = arrStr[3];//公司名称
  111. if (arrStr.Length >= 5)
  112. label.Name = arrStr[4];//描述1
  113. if (arrStr.Length >= 6)
  114. label.Descr = arrStr[5];//描述2
  115. if (arrStr.Length >= 7)
  116. label.Lable = arrStr[6];//条码
  117. if (arrStr.Length >= 8)
  118. label.ItemNum = arrStr[7];//零件号
  119. if (arrStr.Length >= 9)
  120. label.BatchNum = arrStr[8];//
  121. if (arrStr.Length >= 10)
  122. label.Qty = arrStr[9];//回报数量
  123. if (arrStr.Length >= 11)
  124. label.Date = arrStr[10];//日期
  125. if (arrStr.Length >= 12)
  126. label.Checker = arrStr[11];//检验员编号
  127. if (arrStr.Length >= 13)
  128. label.Position = arrStr[12];//方位
  129. if (arrStr.Length >= 14)
  130. label.Factory = arrStr[13];//工程
  131. if (arrStr.Length >= 15)
  132. label.LineName = arrStr[14];//产线描述
  133. if (arrStr.Length >= 16)
  134. label.Other = arrStr[15];//供应商代码
  135. if (arrStr.Length >= 17)
  136. label.ALCCode = arrStr[16];//供应商代码
  137. if (arrStr.Length >= 18)
  138. label.Model = arrStr[17];//车型
  139. if (arrStr.Length >= 19)
  140. label.Location = arrStr[18];//下工序库位
  141. if (arrStr.Length >= 20)
  142. label.Line = arrStr[19];//产线编号
  143. if (arrStr.Length >= 21)
  144. label.Remark = arrStr[20];//备注
  145. if (arrStr.Length >= 22)
  146. label.CustItem = arrStr[21];//客户件号
  147. if (arrStr.Length >= 23)
  148. label.Time = arrStr[22];//时间秒 hh:mm;ss
  149. if (arrStr.Length >= 24)
  150. label.PackQty = arrStr[23];//包装数量
  151. if (arrStr.Length >= 25)
  152. label.CkName = arrStr[24];//检验员名称 或单位UM
  153. if (arrStr.Length >= 26)
  154. label.LuoSite = arrStr[25];//落脚点
  155. if (arrStr.Length >= 27)
  156. label.Domain = arrStr[26];//域
  157. if (arrStr.Length >= 28)
  158. label.LoNoDesc = arrStr[27];//下工序库位不带描述
  159. if (arrStr.Length >= 29)
  160. label.LabColor = arrStr[28];//颜色
  161. if (arrStr.Length > 30)
  162. label.LotSerial = arrStr[29];//批号
  163. if (arrStr.Length > 31)
  164. label.Period = arrStr[30];//生产周期
  165. if (arrStr.Length >= 32)
  166. label.Carton = arrStr[31];//流水号
  167. if (arrStr.Length >= 33)
  168. label.OrdNbr = arrStr[32];//单号
  169. if (arrStr.Length >= 34)
  170. label.CustItemDescr = arrStr[33];//客户件号名称
  171. if (arrStr.Length >= 35)
  172. label.EngineeringNo = arrStr[34];//工程变更号
  173. if (arrStr.Length >= 36)
  174. label.CartonQty = arrStr[35];//箱数
  175. if (arrStr.Length >= 37)
  176. label.WorkOrd = arrStr[36];//工单号
  177. if (arrStr.Length >= 38)
  178. label.CustBarcode = arrStr[37];//客户标签
  179. if (arrStr.Length >= 39)
  180. label.MoldNum = arrStr[38];//模具号
  181. if (arrStr.Length >= 40)
  182. label.FurnaceLot = arrStr[39];//熔炉号
  183. if (arrStr.Length >= 41)
  184. label.Refs = arrStr[40];//腔号
  185. if (arrStr.Length >= 42)
  186. label.Shelf = arrStr[41];//货架
  187. if (arrStr.Length >= 43)
  188. label.NetWeight = arrStr[42];//净重
  189. if (arrStr.Length >= 44)
  190. label.NetWeightUM = arrStr[43];//净重单位
  191. if (arrStr.Length >= 45)
  192. label.UM = arrStr[44];//单位
  193. if (arrStr.Length >= 46)
  194. label.Desc3 = arrStr[45];//库位名称
  195. if (arrStr.Length >= 47)
  196. label.Remarks1 = arrStr[46];//备注1
  197. if (arrStr.Length >= 48)
  198. label.Remarks2 = arrStr[47];//备注2
  199. if (arrStr.Length >= 49)
  200. label.Remarks3 = arrStr[48];//备注3
  201. if (arrStr.Length >= 50)
  202. label.Remarks4 = arrStr[49];//备注4
  203. if (arrStr.Length >= 51)
  204. label.Remarks5 = arrStr[50];//备注5
  205. if (arrStr.Length >= 52)
  206. label.Remarks6 = arrStr[51];//备注6
  207. if (arrStr.Length >= 53)
  208. label.Remarks7 = arrStr[52];//备注7
  209. if (arrStr.Length >= 54)
  210. label.Remarks8 = arrStr[53];//备注8
  211. if (arrStr.Length >= 55)
  212. label.Factor = arrStr[54];//dell件号
  213. if (arrStr.Length >= 56)
  214. label.ShelfLife = arrStr[55];
  215. if (arrStr.Length >= 57)
  216. label.GuaranteeDate = arrStr[56];
  217. if (arrStr.Length >= 58)
  218. label.Hazard = arrStr[57];//防火危险等级
  219. return label;
  220. }
  221. #endregion
  222. #region 打印指令
  223. private string GetPrintData(string command)
  224. {
  225. bool isTSC = command == "TSC";
  226. LabelViewModel label = _label;
  227. DataTable formatMasters = _formatMasters;
  228. DataRow labelSize = formatMasters.Select("Property='0'")[0];
  229. if (labelSize == null)
  230. {
  231. return "";
  232. }
  233. if (labelSize["Long"] == null || Convert.ToInt32(labelSize["Long"].ToString()) == 0)
  234. {
  235. labelSize["Long"] = 400;
  236. }
  237. if (labelSize["Wide"] == null || Convert.ToInt32(labelSize["Wide"].ToString()) == 0)
  238. {
  239. labelSize["Wide"] = 300;
  240. }
  241. if (!(labelSize["ReMark"] == null || labelSize["ReMark"].ToString()==""))
  242. {
  243. int.TryParse(labelSize["ReMark"].ToString(), out TcpLabelHeightMM);
  244. if (TcpLabelHeightMM == 0)
  245. {
  246. TcpLabelHeightMM = 42;
  247. }
  248. }
  249. if (isTSC)
  250. {
  251. TcpLabelLongMM = Convert.ToInt32(Convert.ToDecimal(labelSize["Long"]) / (Convert.ToDecimal(labelSize["Wide"]) / (TcpLabelHeightMM + 3)));
  252. if (!(labelSize["ReMark2"] == null || labelSize["ReMark2"].ToString() == ""))
  253. {
  254. int.TryParse(labelSize["ReMark2"].ToString(), out gap);
  255. if (gap == 0)
  256. {
  257. gap = 2;
  258. }
  259. }
  260. }
  261. var writer = new BarcodeWriterPixelData();
  262. double dpiScale = (TcpPrinterDPI / 25.4 * TcpLabelHeightMM) / Convert.ToInt32(labelSize["Wide"].ToString());
  263. Bitmap bitmap = new Bitmap(Convert.ToInt32(Convert.ToInt32(labelSize["Long"].ToString())*dpiScale), Convert.ToInt32(Convert.ToInt32(labelSize["Wide"].ToString())*dpiScale), PixelFormat.Format24bppRgb);
  264. Graphics g = Graphics.FromImage(bitmap);
  265. g.Clear(Color.White);
  266. int penWidth = Convert.ToInt32(Math.Ceiling(1 * dpiScale));
  267. var propertys = label.GetType().GetProperties();
  268. foreach (DataRow item in formatMasters.Rows)
  269. {
  270. item["Long"] = Convert.ToInt32(Convert.ToInt32(item["Long"].ToString()) * dpiScale);
  271. item["Wide"] = Convert.ToInt32(Convert.ToInt32(item["Wide"].ToString()) * dpiScale);
  272. item["VerticalDistance"] = Convert.ToInt32(Convert.ToInt32(item["VerticalDistance"].ToString()) * dpiScale);
  273. item["HorizontalDistance"] = Convert.ToInt32(Convert.ToInt32(item["HorizontalDistance"].ToString()) * dpiScale);
  274. item["FontSize"] = Convert.ToInt32(Convert.ToInt32(item["FontSize"].ToString()) * dpiScale);
  275. var property = (from p in propertys where p.Name == item["LabelName"].ToString() select p).FirstOrDefault();
  276. string itemVal = "";
  277. if (property!=null)
  278. {
  279. object obj = property.GetValue(label);
  280. if (obj != null)
  281. {
  282. itemVal = obj.ToString();
  283. }
  284. }
  285. if (string.IsNullOrEmpty(item["FontStyle"].ToString()))
  286. {
  287. item["FontStyle"] = "微软雅黑";
  288. }
  289. if (item["Property"].ToString() == "5")
  290. {
  291. writer.Format = BarcodeFormat.CODE_128;
  292. float V = Convert.ToInt32(item["VerticalDistance"].ToString());
  293. float H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  294. float L = Convert.ToInt32(item["Long"].ToString());
  295. float W = Convert.ToInt32(item["Wide"].ToString());
  296. var pixdata = writer.Write(itemVal);
  297. Bitmap barcode = PixToBitmap(pixdata.Pixels, pixdata.Width, pixdata.Height);
  298. g.DrawImage(barcode, (int)H, (int)V, (int)L, (int)W);
  299. barcode.Dispose();
  300. barcode = null;
  301. }
  302. else if (item["Property"].ToString() == "6")
  303. {
  304. float V = Convert.ToInt32(item["VerticalDistance"].ToString());
  305. if (V == 0)
  306. {
  307. V = 1;
  308. item["VerticalDistance"] = 1;
  309. }
  310. float H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  311. if (H == 0)
  312. {
  313. H = 1;
  314. item["HorizontalDistance"] = 1;
  315. }
  316. float L = Convert.ToInt32(item["Long"].ToString());
  317. if (L == 0)
  318. {
  319. L = 1;
  320. item["Long"] = 10;
  321. }
  322. float W = Convert.ToInt32(item["Wide"].ToString());
  323. if (W == 0)
  324. {
  325. W = 1;
  326. item["Wide"] = 10;
  327. }
  328. Bitmap barcode;
  329. //DM码Core没有,暂时全用QR
  330. writer = new BarcodeWriterPixelData();
  331. writer.Options.PureBarcode = true;
  332. if (string.IsNullOrEmpty(item["BarcodeFormat"].ToString()))
  333. {
  334. writer.Format = BarcodeFormat.QR_CODE;
  335. }
  336. else
  337. {
  338. writer.Format = (BarcodeFormat)Enum.Parse(typeof(BarcodeFormat), item["BarcodeFormat"].ToString().ToUpper());
  339. }
  340. var pixdata = writer.Write(itemVal);
  341. barcode = PixToBitmap(pixdata.Pixels, pixdata.Width, pixdata.Height);
  342. g.DrawImage(barcode, (int)H, (int)V, (int)L, (int)W);
  343. barcode.Dispose();
  344. barcode = null;
  345. }
  346. else if (item["Property"].ToString() == "7")
  347. {
  348. int V = Convert.ToInt32(item["VerticalDistance"].ToString());
  349. if (V == 0)
  350. {
  351. V = 1;
  352. item["VerticalDistance"] = 1;
  353. }
  354. int H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  355. if (H == 0)
  356. {
  357. H = 1;
  358. item["HorizontalDistance"] = 1;
  359. }
  360. int L = Convert.ToInt32(item["Long"].ToString());
  361. if (L == 0)
  362. {
  363. L = 1;
  364. item["Long"] = 10;
  365. }
  366. int W = Convert.ToInt32(item["Wide"].ToString());
  367. if (W == 0)
  368. {
  369. W = 1;
  370. item["Wide"] = 10;
  371. }
  372. g.DrawImage(BytesToBitmap((byte[])item["Photo"]), H, V, L, W);
  373. }
  374. else if (item["Property"].ToString() == "1")
  375. {
  376. int V = Convert.ToInt32(item["VerticalDistance"].ToString());
  377. if (V == 0)
  378. {
  379. V = 1;
  380. item["VerticalDistance"] = 1;
  381. }
  382. int H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  383. if (H == 0)
  384. {
  385. H = 1;
  386. item["HorizontalDistance"] = 1;
  387. }
  388. int L = Convert.ToInt32(item["Long"].ToString());
  389. if (L == 0)
  390. {
  391. L = 1;
  392. item["Long"] = 10;
  393. }
  394. int W = Convert.ToInt32(item["Wide"].ToString());
  395. if (W == 0)
  396. {
  397. W = 1;
  398. item["Wide"] = 10;
  399. }
  400. Pen pen = new Pen(Color.Black, penWidth);
  401. g.DrawRectangle(pen, new Rectangle(H, V, L, W));
  402. }
  403. else if (item["Property"].ToString() == "0")
  404. {
  405. continue;
  406. }
  407. else if (item["Property"].ToString() == "2")
  408. {
  409. int V = Convert.ToInt32(item["VerticalDistance"].ToString());
  410. if (V == 0)
  411. {
  412. V = 1;
  413. item["VerticalDistance"] = 1;
  414. }
  415. int H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  416. if (H == 0)
  417. {
  418. H = 1;
  419. item["HorizontalDistance"] = 1;
  420. }
  421. int L = Convert.ToInt32(item["Long"].ToString());
  422. int W = Convert.ToInt32(item["Wide"].ToString());
  423. Pen pen = new Pen(Color.Black, penWidth);
  424. g.DrawLine(pen, new Point(H, V), new Point(H + L, V + W));
  425. }
  426. else
  427. {
  428. float V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) V = 1;
  429. float H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) H = 1;
  430. float size = Convert.ToInt32(item["FontSize"].ToString()); if (size == 0) size = 1;
  431. string content = "";
  432. if (item["Property"].ToString() == "3")
  433. {
  434. content = item["LabelContent"].ToString();
  435. }
  436. else
  437. {
  438. if (string.IsNullOrEmpty(itemVal))
  439. {
  440. content = " ";
  441. }
  442. else
  443. {
  444. content = itemVal;
  445. if (!string.IsNullOrEmpty(item["LabelContent"].ToString()))
  446. {
  447. if (item["LabelName"].ToString() == "Date" && item["LabelContent"].ToString().ToUpper().IndexOf("MM") >= 0)
  448. {
  449. content = Convert.ToDateTime(itemVal).ToString(item["LabelContent"].ToString());
  450. }
  451. else if (item["LabelName"].ToString() == "Period")
  452. {
  453. int length = item["LabelContent"].ToString().Length - itemVal.Length;
  454. string tempContent = "";
  455. for (int i = 1; i <= length; i++)
  456. {
  457. tempContent += "0";
  458. }
  459. content = tempContent + itemVal;
  460. }
  461. }
  462. }
  463. }
  464. if (Convert.ToBoolean(item["IsCrude"].ToString()))
  465. g.DrawString(content, new Font(item["FontStyle"].ToString(), size, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, H, V);
  466. else
  467. g.DrawString(content, new Font(item["FontStyle"].ToString(), size, System.Drawing.FontStyle.Regular), System.Drawing.Brushes.Black, H, V);
  468. }
  469. }
  470. g.Dispose();
  471. GC.Collect();
  472. if(isTSC)
  473. {
  474. MemoryStream ms = new MemoryStream();
  475. string result = "";
  476. try
  477. {
  478. bitmap.Save(ms, ImageFormat.Png);
  479. byte[] arrBmp = new byte[ms.Length];
  480. ms.Position = 0;
  481. ms.Read(arrBmp, 0, (int)ms.Length);
  482. result = Convert.ToBase64String(arrBmp);
  483. result = $"{TcpLabelLongMM},{TcpLabelHeightMM+3},{gap}|" + result;
  484. }
  485. catch (Exception ex)
  486. {
  487. throw new Exception(ex.Message, ex);
  488. }
  489. finally
  490. {
  491. if (ms != null)
  492. {
  493. ms.Dispose();
  494. ms = null;
  495. }
  496. }
  497. return result;
  498. }
  499. else
  500. {
  501. return GetCPCLBytes(bitmap);
  502. }
  503. }
  504. private string GetPrintDataByCommand(string command, bool isMovePrinter)
  505. {
  506. bool isTSC = command == "TSC";
  507. if (isTSC && !isMovePrinter) TcpPrinterDPI = 300;
  508. string txtCommands = "";
  509. LabelViewModel label = _label;
  510. DataTable formatMasters = _formatMasters;
  511. DataRow labelSize = formatMasters.Select("Property='0'")[0];
  512. if (labelSize == null)
  513. {
  514. return "";
  515. }
  516. if (labelSize["Long"] == null || Convert.ToInt32(labelSize["Long"].ToString()) == 0)
  517. {
  518. labelSize["Long"] = 400;
  519. }
  520. if (labelSize["Wide"] == null || Convert.ToInt32(labelSize["Wide"].ToString()) == 0)
  521. {
  522. labelSize["Wide"] = 300;
  523. }
  524. if (!(labelSize["ReMark"] == null || labelSize["ReMark"].ToString() == ""))
  525. {
  526. int.TryParse(labelSize["ReMark"].ToString(), out TcpLabelHeightMM);
  527. if (TcpLabelHeightMM == 0)
  528. {
  529. TcpLabelHeightMM = 42;
  530. }
  531. }
  532. if (isTSC)
  533. {
  534. TcpLabelLongMM = Convert.ToInt32(Convert.ToDecimal(labelSize["Long"]) / (Convert.ToDecimal(labelSize["Wide"]) / (TcpLabelHeightMM + 3)));
  535. if (!(labelSize["ReMark2"] == null || labelSize["ReMark2"].ToString() == ""))
  536. {
  537. int.TryParse(labelSize["ReMark2"].ToString(), out gap);
  538. if (gap == 0)
  539. {
  540. gap = 2;
  541. }
  542. }
  543. }
  544. double dpiScale = (TcpPrinterDPI / 25.4 * TcpLabelHeightMM) / Convert.ToInt32(labelSize["Wide"].ToString());
  545. var propertys = label.GetType().GetProperties();
  546. foreach (DataRow item in formatMasters.Rows)
  547. {
  548. item["Long"] = Convert.ToInt32(Convert.ToInt32(item["Long"].ToString()) * dpiScale);
  549. item["Wide"] = Convert.ToInt32(Convert.ToInt32(item["Wide"].ToString()) * dpiScale);
  550. item["VerticalDistance"] = Convert.ToInt32(Convert.ToInt32(item["VerticalDistance"].ToString()) * dpiScale);
  551. item["HorizontalDistance"] = Convert.ToInt32(Convert.ToInt32(item["HorizontalDistance"].ToString()) * dpiScale);
  552. item["FontSize"] = Convert.ToInt32(Convert.ToInt32(item["FontSize"].ToString()) * dpiScale);
  553. var property = (from p in propertys where p.Name == item["LabelName"].ToString() select p).FirstOrDefault();
  554. string itemVal = "";
  555. if (property != null)
  556. {
  557. object obj = property.GetValue(label);
  558. if (obj != null)
  559. {
  560. itemVal = obj.ToString();
  561. }
  562. }
  563. if (string.IsNullOrEmpty(item["FontStyle"].ToString()))
  564. {
  565. item["FontStyle"] = "微软雅黑";
  566. }
  567. if (item["Property"].ToString() == "5")
  568. {
  569. if (string.IsNullOrEmpty(itemVal))
  570. {
  571. continue;
  572. }
  573. float V = Convert.ToInt32(item["VerticalDistance"].ToString());
  574. float H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  575. float L = Convert.ToInt32(item["Long"].ToString());
  576. float W = Convert.ToInt32(item["Wide"].ToString());
  577. if(isTSC)
  578. {
  579. txtCommands += $"BARCODE {H},{V},\"128\",{(int)W},1,0,3,1,\"{itemVal}\"\r\n";
  580. }
  581. else
  582. {
  583. txtCommands += $"BARCODE 128 1 1 {(int)W} {H} {V} {itemVal}\r\n";
  584. }
  585. }
  586. else if (item["Property"].ToString() == "6")
  587. {
  588. if (string.IsNullOrEmpty(itemVal))
  589. {
  590. continue;
  591. }
  592. float V = Convert.ToInt32(item["VerticalDistance"].ToString());
  593. if (V == 0)
  594. {
  595. V = 1;
  596. item["VerticalDistance"] = 1;
  597. }
  598. float H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  599. if (H == 0)
  600. {
  601. H = 1;
  602. item["HorizontalDistance"] = 1;
  603. }
  604. float L = Convert.ToInt32(item["Long"].ToString());
  605. if (L == 0)
  606. {
  607. L = 1;
  608. item["Long"] = 10;
  609. }
  610. float W = Convert.ToInt32(item["Wide"].ToString());
  611. if (W == 0)
  612. {
  613. W = 1;
  614. item["Wide"] = 10;
  615. }
  616. int qrSize = (int)(Math.Round(L / 8 / 10 + 3));
  617. H = H + Convert.ToInt32(12 * dpiScale);
  618. if (isTSC)
  619. {
  620. txtCommands += $"QRCODE {H},{V},L,{qrSize+1},A,0,\"{itemVal}\"\r\n";
  621. }
  622. else
  623. {
  624. txtCommands += $"B QR {H} {V} M 2 U {qrSize}\r\n";
  625. txtCommands += $"MA,{itemVal}\r\n";
  626. txtCommands += $"ENDQR\r\n";
  627. }
  628. }
  629. else if (item["Property"].ToString() == "7")
  630. {
  631. //int V = Convert.ToInt32(item["VerticalDistance"].ToString());
  632. //if (V == 0)
  633. //{
  634. // V = 1;
  635. // item["VerticalDistance"] = 1;
  636. //}
  637. //int H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  638. //if (H == 0)
  639. //{
  640. // H = 1;
  641. // item["HorizontalDistance"] = 1;
  642. //}
  643. //int L = Convert.ToInt32(item["Long"].ToString());
  644. //if (L == 0)
  645. //{
  646. // L = 1;
  647. // item["Long"] = 10;
  648. //}
  649. //int W = Convert.ToInt32(item["Wide"].ToString());
  650. //if (W == 0)
  651. //{
  652. // W = 1;
  653. // item["Wide"] = 10;
  654. //}
  655. //if (item["Photo"] != DBNull.Value)
  656. //{
  657. // Bitmap logbitmap = new Bitmap(L, W, PixelFormat.Format24bppRgb);
  658. // Graphics g = Graphics.FromImage(logbitmap);
  659. // g.Clear(Color.White);
  660. // g.DrawImage(BytesToBitmap((byte[])item["Photo"]), 0, 0, L, W);
  661. // txtCommands += GetCPCLBytes(logbitmap, true,H,V);
  662. // g.Dispose();
  663. // logbitmap.Dispose();
  664. //}
  665. }
  666. else if (item["Property"].ToString() == "1")
  667. {
  668. int V = Convert.ToInt32(item["VerticalDistance"].ToString());
  669. if (V == 0)
  670. {
  671. V = 1;
  672. item["VerticalDistance"] = 1;
  673. }
  674. int H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  675. if (H == 0)
  676. {
  677. H = 1;
  678. item["HorizontalDistance"] = 1;
  679. }
  680. int L = Convert.ToInt32(item["Long"].ToString());
  681. if (L == 0)
  682. {
  683. L = 1;
  684. item["Long"] = 10;
  685. }
  686. int W = Convert.ToInt32(item["Wide"].ToString());
  687. if (W == 0)
  688. {
  689. W = 1;
  690. item["Wide"] = 10;
  691. }
  692. if (isTSC)
  693. {
  694. txtCommands += $"BOX {H},{V},{H + L},{V + W},3\r\n";
  695. }
  696. else
  697. {
  698. txtCommands += $"BOX {H} {V} {H + L} {V + W} 1\r\n";
  699. }
  700. }
  701. else if (item["Property"].ToString() == "0")
  702. {
  703. continue;
  704. }
  705. else if (item["Property"].ToString() == "2")
  706. {
  707. int V = Convert.ToInt32(item["VerticalDistance"].ToString());
  708. if (V == 0)
  709. {
  710. V = 1;
  711. item["VerticalDistance"] = 1;
  712. }
  713. int H = Convert.ToInt32(item["HorizontalDistance"].ToString());
  714. if (H == 0)
  715. {
  716. H = 1;
  717. item["HorizontalDistance"] = 1;
  718. }
  719. int L = Convert.ToInt32(item["Long"].ToString());
  720. int W = Convert.ToInt32(item["Wide"].ToString());
  721. if (isTSC)
  722. {
  723. L = L == 0 ? 3 : L;
  724. W = W == 0 ? 3 : W;
  725. txtCommands += $"BAR {H},{V},{L},{W}\r\n";
  726. }
  727. else
  728. {
  729. txtCommands += $"LINE {H} {V} {H + L} {V + W} 1\r\n";
  730. }
  731. }
  732. else
  733. {
  734. float V = Convert.ToInt32(item["VerticalDistance"].ToString()); if (V == 0) V = 1;
  735. float H = Convert.ToInt32(item["HorizontalDistance"].ToString()); if (H == 0) H = 1;
  736. float size = Convert.ToInt32(item["FontSize"].ToString()); if (size == 0) size = 1;
  737. string content = "";
  738. bool isCrude = (bool)item["IsCrude"];
  739. if (item["Property"].ToString() == "3")
  740. {
  741. content = item["LabelContent"].ToString().Trim();
  742. }
  743. else
  744. {
  745. if (string.IsNullOrEmpty(itemVal))
  746. {
  747. content = "";
  748. }
  749. else
  750. {
  751. content = itemVal;
  752. if (!string.IsNullOrEmpty(item["LabelContent"].ToString()))
  753. {
  754. if (item["LabelName"].ToString() == "Date" && item["LabelContent"].ToString().ToUpper().IndexOf("MM") >= 0)
  755. {
  756. content = Convert.ToDateTime(itemVal).ToString(item["LabelContent"].ToString());
  757. }
  758. else if (item["LabelName"].ToString() == "Period")
  759. {
  760. int length = item["LabelContent"].ToString().Length - itemVal.Length;
  761. string tempContent = "";
  762. for (int i = 1; i <= length; i++)
  763. {
  764. tempContent += "0";
  765. }
  766. content = tempContent + itemVal;
  767. }
  768. }
  769. }
  770. }
  771. if (!string.IsNullOrEmpty(content))
  772. {
  773. if (isTSC)
  774. {
  775. string font = "4";
  776. int multiplication = 1;
  777. //if (item["Property"].ToString() == "3" || item["ReMark"].ToString().ToUpper() == "ZH-CN")
  778. if (item["ReMark"].ToString().ToUpper() == "ZH-CN")
  779. {
  780. font = "TSS24.BF2";
  781. multiplication = 2;
  782. int.TryParse(item["ReMark2"].ToString(), out multiplication);
  783. if (multiplication == 0)
  784. {
  785. multiplication = 2;
  786. }
  787. }
  788. else
  789. {
  790. int font2 = 4;
  791. int.TryParse(item["ReMark2"].ToString(), out font2);
  792. if (font2 == 0)
  793. {
  794. font2 = 4;
  795. }
  796. font = font2.ToString();
  797. }
  798. txtCommands += $"TEXT {H},{V},\"{font}\",0,{multiplication},{multiplication},\"{content}\"\r\n";
  799. }
  800. else
  801. {
  802. if (isCrude)
  803. {
  804. txtCommands += "SETBOLD 2\r\n";
  805. }
  806. txtCommands += $"TEXT GBUNSG24.CPF 0 {H} {V} {content}\r\n";
  807. if (isCrude)
  808. {
  809. txtCommands += "SETBOLD 0\r\n";
  810. }
  811. }
  812. }
  813. }
  814. }
  815. string commands = "";
  816. if (isTSC)
  817. {
  818. commands = $"SIZE {TcpLabelLongMM} mm,{TcpLabelHeightMM+3} mm\r\n";
  819. commands += $"GAP {gap} mm,0 mm\r\n";
  820. commands += "CLS\r\n";
  821. commands += "REFERENCE 3 mm,3 mm\r\n";
  822. commands += "DIRECTION 1,0\r\n";
  823. commands += "DENSITY 13\r\n";
  824. commands += txtCommands;
  825. commands += "PRINT 1\r\n";
  826. commands += "SOUND 2,100\r\n";
  827. }
  828. else
  829. {
  830. commands = $"! {0} {TcpPrinterDPI} {TcpPrinterDPI} {(int)(TcpPrinterDPI / 25.4f * TcpLabelHeightMM)} 1\r\n";
  831. //commands += "PREFEED -24\r\n";
  832. //commands += "TONE 30\r\n";
  833. commands += "ENCODING GB18030\r\n";
  834. commands += "SETMAG 1 1\r\n";
  835. commands += txtCommands;
  836. commands += "FORM\r\nPRINT\r\n";
  837. }
  838. return commands;
  839. }
  840. #endregion
  841. #region 生成CPCL图像打印指令
  842. private string GetCPCLBytes(Bitmap bitmap)
  843. {
  844. int RowRealBytesCount = 0;
  845. int GraphHeight = 0;
  846. byte[] bmpData = GetBitmapData(bitmap, ref RowRealBytesCount, ref GraphHeight);
  847. int bmpDataLength = bmpData.Length;
  848. for (int i = 0; i < bmpDataLength; i++)
  849. {
  850. bmpData[i] ^= 0xFF;
  851. }
  852. int Copies = 1;
  853. string textHex = BitConverter.ToString(bmpData).Replace("-", string.Empty);
  854. 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",
  855. 0,
  856. TcpPrinterDPI,
  857. TcpPrinterDPI,
  858. (int)(TcpPrinterDPI / 25.4f * TcpLabelHeightMM),
  859. Copies,
  860. -24,
  861. 30,
  862. RowRealBytesCount,
  863. GraphHeight,
  864. 0,
  865. 0,
  866. textHex
  867. );
  868. return text;
  869. }
  870. #endregion
  871. #region 获取单色位图数据
  872. private byte[] GetBitmapData(Bitmap srcBmp, ref int RowRealBytesCount, ref int GraphHeight)
  873. {
  874. MemoryStream dstStream = new MemoryStream();
  875. Bitmap dstBmp = null;
  876. byte[] dstBuffer = null;
  877. byte[] result = null;
  878. try
  879. {
  880. dstBmp = ConvertToGrayscale(srcBmp);
  881. dstBmp.Save(dstStream, ImageFormat.Bmp);
  882. dstBuffer = dstStream.ToArray();
  883. int bfOffBits = BitConverter.ToInt32(dstBuffer, 10);
  884. int GraphWidth = srcBmp.Width;
  885. GraphHeight = srcBmp.Height;
  886. RowRealBytesCount = 0;
  887. if ((GraphWidth % 8) > 0)
  888. {
  889. RowRealBytesCount = GraphWidth / 8 - 1;
  890. }
  891. else
  892. {
  893. RowRealBytesCount = GraphWidth / 8;
  894. }
  895. int RowSize = (((GraphWidth) + 31) >> 5) << 2;
  896. result = new byte[GraphHeight * RowRealBytesCount];
  897. for (int i = 0; i < GraphHeight; i++)
  898. {
  899. Array.Copy(dstBuffer, bfOffBits + (GraphHeight - 1 - i) * RowSize, result, i * RowRealBytesCount, RowRealBytesCount);
  900. }
  901. }
  902. catch (Exception ex)
  903. {
  904. throw new Exception(ex.Message, ex);
  905. }
  906. finally
  907. {
  908. if (dstStream != null)
  909. {
  910. dstStream.Dispose();
  911. dstStream = null;
  912. }
  913. if (srcBmp != null)
  914. {
  915. srcBmp.Dispose();
  916. srcBmp = null;
  917. }
  918. if (dstBmp != null)
  919. {
  920. dstBmp.Dispose();
  921. dstBmp = null;
  922. }
  923. }
  924. return result;
  925. }
  926. private Bitmap ConvertToGrayscale(Bitmap pimage)
  927. {
  928. Bitmap source = null;
  929. // If original bitmap is not already in 32 BPP, ARGB format, then convert
  930. if (pimage.PixelFormat != PixelFormat.Format32bppArgb)
  931. {
  932. source = new Bitmap(pimage.Width, pimage.Height, PixelFormat.Format32bppArgb);
  933. source.SetResolution(pimage.HorizontalResolution, pimage.VerticalResolution);
  934. using (Graphics g = Graphics.FromImage(source))
  935. {
  936. g.DrawImageUnscaled(pimage, 0, 0);
  937. }
  938. }
  939. else
  940. {
  941. source = pimage;
  942. }
  943. // Lock source bitmap in memory
  944. BitmapData sourceData = source.LockBits(new Rectangle(0, 0, source.Width, source.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
  945. // Copy image data to binary array
  946. int imageSize = sourceData.Stride * sourceData.Height;
  947. byte[] sourceBuffer = new byte[imageSize];
  948. Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize);
  949. // Unlock source bitmap
  950. source.UnlockBits(sourceData);
  951. // Create destination bitmap
  952. Bitmap destination = new Bitmap(source.Width, source.Height, PixelFormat.Format1bppIndexed);
  953. // Lock destination bitmap in memory
  954. BitmapData destinationData = destination.LockBits(new Rectangle(0, 0, destination.Width, destination.Height), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);
  955. // Create destination buffer
  956. imageSize = destinationData.Stride * destinationData.Height;
  957. byte[] destinationBuffer = new byte[imageSize];
  958. int sourceIndex = 0;
  959. int destinationIndex = 0;
  960. int pixelTotal = 0;
  961. byte destinationValue = 0;
  962. int pixelValue = 128;
  963. int height = source.Height;
  964. int width = source.Width;
  965. int threshold = 500;
  966. // Iterate lines
  967. for (int y = 0; y < height; y++)
  968. {
  969. sourceIndex = y * sourceData.Stride;
  970. destinationIndex = y * destinationData.Stride;
  971. destinationValue = 0;
  972. pixelValue = 128;
  973. // Iterate pixels
  974. for (int x = 0; x < width; x++)
  975. {
  976. // Compute pixel brightness (i.e. total of Red, Green, and Blue values)
  977. pixelTotal = sourceBuffer[sourceIndex + 1] + sourceBuffer[sourceIndex + 2] + sourceBuffer[sourceIndex + 3];
  978. if (pixelTotal > threshold)
  979. {
  980. destinationValue += (byte)pixelValue;
  981. }
  982. if (pixelValue == 1)
  983. {
  984. destinationBuffer[destinationIndex] = destinationValue;
  985. destinationIndex++;
  986. destinationValue = 0;
  987. pixelValue = 128;
  988. }
  989. else
  990. {
  991. pixelValue >>= 1;
  992. }
  993. sourceIndex += 4;
  994. }
  995. if (pixelValue != 128)
  996. {
  997. destinationBuffer[destinationIndex] = destinationValue;
  998. }
  999. }
  1000. // Copy binary image data to destination bitmap
  1001. Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, imageSize);
  1002. // Unlock destination bitmap
  1003. destination.UnlockBits(destinationData);
  1004. // Dispose of source if not originally supplied bitmap
  1005. if (source != pimage)
  1006. {
  1007. source.Dispose();
  1008. }
  1009. // Return
  1010. return destination;
  1011. }
  1012. #endregion
  1013. #region 字节数组转换为位图
  1014. /// <summary>
  1015. /// 将一个字节数组转换为位图
  1016. /// </summary>
  1017. /// <param name="pixValue">显示字节数组</param>
  1018. /// <param name="width">图像宽度</param>
  1019. /// <param name="height">图像高度</param>
  1020. /// <returns>位图</returns>
  1021. private Bitmap PixToBitmap(byte[] pixValue, int width, int height)
  1022. {
  1023. //// 申请目标位图的变量,并将其内存区域锁定
  1024. var m_currBitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
  1025. var m_rect = new Rectangle(0, 0, width, height);
  1026. var m_bitmapData = m_currBitmap.LockBits(m_rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
  1027. IntPtr iptr = m_bitmapData.Scan0; // 获取bmpData的内存起始位置
  1028. //// 用Marshal的Copy方法,将刚才得到的内存字节数组复制到BitmapData中
  1029. System.Runtime.InteropServices.Marshal.Copy(pixValue, 0, iptr, pixValue.Length);
  1030. m_currBitmap.UnlockBits(m_bitmapData);
  1031. //// 算法到此结束,返回结果
  1032. return m_currBitmap;
  1033. }
  1034. //byte[] 转换 Bitmap
  1035. private Bitmap BytesToBitmap(byte[] Bytes)
  1036. {
  1037. MemoryStream stream = null;
  1038. try
  1039. {
  1040. stream = new MemoryStream(Bytes);
  1041. return new Bitmap((Image)new Bitmap(stream));
  1042. }
  1043. catch (ArgumentNullException ex)
  1044. {
  1045. throw ex;
  1046. }
  1047. catch (ArgumentException ex)
  1048. {
  1049. throw ex;
  1050. }
  1051. finally
  1052. {
  1053. stream.Close();
  1054. }
  1055. }
  1056. #endregion
  1057. }
  1058. }