C# 标签(条码)的打印与设计(一)

      相信目前稍有规模的公司已进入或正在进入信息化之中,尤其在制造企业中,少不了一个条码的打印功能,而这类应用大多是使用斑马打印机,所以就会遇到了怎么打印的问题了。本人也已经从事ERP,MES等系统多年,也有去了解过一些公司的做法。知道条码的打印的一些做法,下面我们来谈一谈,如有错误之处,请大家不吝指出。

  1.一些规模小的企业是用标签设计软件做好模板,在标签设计软件中打印,这种办法不用写代码,但对大多数公司来说并不适合,因为企业的数据动态的比较多,如果纯手工修改打印肯定不能接受,于是唯一的出路只能是代码解决问题。

      2.首先做好模板,然后替换其中动态变化的内容为变量名,在代码中动态替换变量,再把指令输出至打印机而在一开这个博客的时候我就写了一篇ZPL如何打印中文信息的随笔(大家可以去参考一下)。

  3.还有就是用绘图方式打印至打印机的,也叫GDI打印,这种可以用报表工具画好标签,运行报表时,把结果输出位图,再发送至打印机。(这种需要较新的打印机)

上面的这些做法都有其缺点。第1是手动,工作量大;第二是需要了解斑马打印指令(新人不便接手);第三是较新的做法,大多公司不是采取这种方式;而我要介绍的是另一种做法,而这种做法比较接近第二类,但又不需要开发者了解斑马指令(EPL/ZPL),而且就算再老的斑马打印机也能用,在速度和质量上都有其优越性。最最主要的是:1.代码相当的少(实际是封了主要一些方法);2.支持ZPL,EPL两种语言;3.支持中文/日文打印;4.无须理会打印机的连接类型;5.支持WINFORM和WEBFORM的打印。在项目之中只需要简单的引用和书写代码即可达到你想要的结果。 下面我们首先谈一下如何打印这个条码,而设计这一块将会放到下一篇随笔,有兴趣的后续可以留意一下。

 

由于是一个DEMO,做得非常的简单。

 

 

打印出来的结果。

下面我们来分析一下代码。

代码是相当的简单。

namespace FormExample
{
    public partial class Form2 : Form
    {
//Created by zhuhl on 2014-11-16
        private int nPrintIdTmp;
        private int LabelType;
        private string LabelFile = string.Empty;
        

        public Form2()
        {
            InitializeComponent();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (this.txtProlot.Text.Trim().Length > 15)
            {
                MessageBox.Show("批号长度不能超过15位","系统提示",MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
            if (this.ChkProlot())
            {
                string strPath = Application.StartupPath.ToString();
                string str2 = "";
                str2 = strPath + @"\Label\FontLib.xml"; //设置字体
                // string barFontlist = ;
                PrintersAndPrintType type = new PrintersAndPrintType();
                if (type.ShowDialog() != DialogResult.Cancel) // 取消选打印机及语言,直接取默认,即EPLII 和 默认打印机
                {

                    string strSql = "PRODUCT_GETBARCODEDATA '" + this.nPrintIdTmp + "','" + this.LabelType + "'";
                    ITPrintClass class2 = new ITPrintClass();
                    // class2.ChineseFontName = "宋体";
                    // class2.BeginPrint(); // 直接发送到默认打印机
                    class2.BeginPrintAt(type.ITPrinterName); //指定打印机                

                    if (string.Compare(type.ITPrinterType, "ZPLII") == 0)
                    {
                        class2.PrinterType = tagITPrinterType.ZPLII;
                    }
                    if ((str2 != null) && (str2.Length > 0))
                    {
                        //获取定义标签的文件的内容
                        class2.LoadFontLibIndexFromText(this.GetDefineLabelXmlText(str2));
                    }
                    string strFile = strPath + @"\Label\" + LabelFile;//添加路径信息
                    class2.SetBarcodeDefineXmlText(this.GetDefineLabelXmlText(strFile)); //标贴定义档

                    if (strSql.Length > 0)
                    {
                        class2.PrintDefinedBarcodeLabel(this.GetSqlDataXmlText(strSql));//从数据库取的

                    }
                    else
                    {
                        class2.PrintDefinedBarcodeLabel(null);
                    }
                    class2.EndPrint();
                    class2 = null;
                }
            }
                       
        }


        private string GetDefineLabelXmlText(string filepath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            StringWriter w = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(w);
            writer.Formatting = Formatting.Indented;
            xmlDoc.Save(writer);
            writer.Close();
            return w.ToString();
        }

        private string GetSqlDataXmlText(string strSql)
        {
            XmlDocument document = new XmlDocument();
           
            document.LoadXml("<BarcodeSqlData/>");
            SqlConnection connection = new SqlConnection(this.ConnectionString);
            SqlCommand command = new SqlCommand(strSql, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                XmlElement newChild = document.CreateElement("FieldData");
                int num2 = reader.FieldCount - 1;
                for (int i = 0; i <= num2; i++)
                {
                    newChild.SetAttribute(reader.GetName(i), Convert.ToString(RuntimeHelpers.GetObjectValue(reader.GetValue(i))).Trim());
                }
                document.DocumentElement.AppendChild(newChild);
            }
            reader.Close();
            connection.Close();
            StringWriter w = new StringWriter();
            XmlTextWriter writer = new XmlTextWriter(w);
            writer.Formatting = Formatting.Indented;
            document.Save(writer);
            writer.Close();
            return w.ToString();
        }

        protected string ConnectionString
        {
            get
            {
                string str = "SERVER";
                string str2 = "USER";
                string str3 = "PASSWORD";
                string str4 = "DATABASE";
                string str5 = string.Empty;
                // str5 = "Persist Security Info=True;Password=" + str3 + ";User ID=" + str2;
                str5 = "Persist Security Info=True;Password=" + str3 + ";User ID=" + str2;
                return (str5 + ";Initial Catalog=" + str4 + ";Data Source=" + str + ";Connect Timeout=60");
            }
        }

        private bool ChkProlot()
        {
            string str2 = "";
            SqlConnection connection = new SqlConnection(this.ConnectionString);
            SqlCommand command = new SqlCommand("ZZLABEL_TEST '" + this.txtProlot.Text + "'", connection); //检测生产批号的有效性
            bool flag = true;
            connection.Open();
            try
            {
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    flag = false;
                    str2 = reader.GetString(1).Trim();
                    this.nPrintIdTmp = reader.GetInt32(2);
                }
                reader.Close();
                reader = new SqlCommand("PRODUCT_GETLABELFILE '" + str2 + "','" + this.nPrintIdTmp.ToString() + "'", connection).ExecuteReader();//这个批号对应的标签定义文件名
                while (reader.Read())
                {
                    LabelFile = reader.GetString(0).Trim();
                    LabelType = reader.GetInt32(1);
                }
                reader.Close();
                connection.Close();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

     
    }
}
View Code

 

大家看一下代码,是否非常的简单呢? 这里主要是提供几个打印信息便可(打印语言,打印机。还有就是标签定义文档/字库路径),根本不太需要了解斑马的语言就可以轻易打印出来想要的条码。那么问题来了,到底如何设计这个模板呢? 敬请留意下一篇文章,也是相当的容易的。做为程序开发人员,肯定要想办法减轻工作量,以获得足够多的业余时间做自己喜欢做的事。

转载于:https://www.cnblogs.com/Geton/p/4102650.html

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您可以使用以下代码来打印一个50x60的标签并包含CODE128条码: ```c# using System; using System.Drawing.Printing; using System.Text; class Program { static void Main(string[] args) { // 设置打印机名称 string printerName = "Your Printer Name"; // 创建打印对象 PrintDocument pd = new PrintDocument(); pd.PrinterSettings.PrinterName = printerName; // 设置打印事件 pd.PrintPage += (sender, e) => { // 设置打印区域 int x = 0, y = 0; int width = 500, height = 600; // 画边框 e.Graphics.DrawRectangle(Pens.Black, x, y, width, height); // 打印条码 string barcodeData = "1234567890"; Code128BarcodeDraw barcodeDraw = BarcodeDrawFactory.Code128WithChecksum; Image barcodeImage = barcodeDraw.Draw(barcodeData, 60); // 计算条码位置 int barcodeX = x + (width - barcodeImage.Width) / 2; int barcodeY = y + (height - barcodeImage.Height) / 2 - 50; // 绘制条码 e.Graphics.DrawImage(barcodeImage, barcodeX, barcodeY); // 打印文字 Font font = new Font("Arial", 12); string text = "Label Text"; SizeF textSize = e.Graphics.MeasureString(text, font); int textX = x + (width - (int)textSize.Width) / 2; int textY = y + height - (int)textSize.Height - 10; e.Graphics.DrawString(text, font, Brushes.Black, textX, textY); }; // 开始打印 pd.Print(); } } public static class BarcodeDrawFactory { private static Lazy<BarcodeDraw> lazy = new Lazy<BarcodeDraw>(() => BarcodeDrawFactory.SVGDrawer); public static BarcodeDraw Default { get { return lazy.Value; } } public static BarcodeDraw Code128WithChecksum { get { return new BarcodeDrawCode128Checksum(); } } public static BarcodeDraw SVGDrawer { get { return new BarcodeDrawSVG(); } } } ``` 这段代码使用了一个名为 `BarcodeDraw` 的库,它可以帮助我们创建条码。在这个例子中,我们创建了一个 CODE128 条码,并将其放置在标签的中央。同时,我们还打印了一些文本,以及一个边框。 请注意将 `Your Printer Name` 替换为您的打印机名称。另外,您需要在项目中导入 `BarcodeLib` 库。您可以通过 NuGet 安装它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值