預設情況下條碼印表機是不能列印漢字的, 不過條碼印表機是支援上傳自訂字型的, 但是這個字型庫跟windows裡面的字型庫肯定不是一回事, 起初我覺得最好能通過上傳字型來實現列印漢字, 但是大概研究了一下, 發現這個太複雜, 而且字型庫檔案也無從搞到, 所以換了方向, 考慮將漢字畫成圖片, 通過列印圖片的方式來實現列印漢字.
所以總的過程為: 將需要列印的漢字在伺服器上通過GDI畫成圖片, 然後將圖片按照條碼印表機的要求序列化成字串上傳到印表機, 最後通過列印圖片命令將其列印出來.
具體的實現方式為:
1. 繪圖.
protected Bitmap CreateImage(string data, Font f) { if (string.IsNullOrEmpty(data)) return null; var txt = new TextBox(); txt.Text = data; txt.Font = f; //txt.PreferredSize.Height只能取到一行的高度(連邊距) //所以需要乘以行數, 但是必須先減掉邊距, 乘了以後,再把邊距加上. //5是目測的邊距 var image = new Bitmap(txt.PreferredSize.Width, (txt.PreferredSize.Height - 5) * txt.Lines.Length + 5); var g = Graphics.FromImage(image); var b = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Black, Color.Black, 1.2f, true); g.Clear(System.Drawing.Color.White); g.DrawString(data, f, b, 1, 1); return image; }
將需要列印的漢字和字型作為參數傳入, 即可得到一副圖片.
2. 轉換並序列化圖片.
protected string ConvertImageToCode(Bitmap img) { var sb = new StringBuilder(); long clr = 0, n = 0; int b = 0; for (int i = 0; i < img.Size.Height; i++) { for (int j = 0; j < img.Size.Width; j++) { b = b * 2; clr = img.GetPixel(j, i).ToArgb(); string s = clr.ToString("X"); if (s.Substring(s.Length - 6, 6).CompareTo("BBBBBB") < 0) { b++; } n++; if (j == (img.Size.Width - 1)) { if (n < 8) { b = b * (2 ^ (8 - (int)n)); sb.Append(b.ToString("X").PadLeft(2, '0')); b = 0; n = 0; } } if (n >= 8) { sb.Append(b.ToString("X").PadLeft(2, '0')); b = 0; n = 0; } } sb.Append(System.Environment.NewLine); } return sb.ToString();}
這是將圖片轉換為條碼印表機能夠支援的點陣圖.
3. 通過ZPL將圖片上傳:
var t = ((img.Size.Width / 8 + ((img.Size.Width % 8 == 0) ? 0 : 1)) * img.Size.Height).ToString(); var w = (img.Size.Width / 8 + ((img.Size.Width % 8 == 0) ? 0 : 1)).ToString(); string zpl = string.Format("~DGR:imgName.GRF,{0},{1},{2}", t, w, imgCode);
其中, img是上述CreateImage函數的返回結果. imgCode是ConvertImageToCode函數的返回結果. imgName是隨便起的圖片名字.
這樣, 就可以通過繼續向zpl添加繪圖命令來列印漢字了.
例如, 以下一段範例程式碼:
^XA
^FO10,10
^XGR:imgName.GRF,1,1^FS
^XZ
具體如何將zpl指令發送到印表機, 請參考我以前的一篇文章:
http://www.cnblogs.com/Moosdau/archive/2009/10/16/1584627.html