C# 打印Label

一.调用CodeSoft打印:
利用第三方软件codesofe进行label设计,然后在程序中调用打印。这种方式维护起来比较方便,手动调整label各参数指标即可。 
准备工作:1.安装打印机驱动 2.安装codeSoft 3.设计label,设置label参数
程序实现:注意首先添加引用:Lppx2.tlb (codesoft安装后文件中)
二.机器码打印:
这种方式直接使用打印机机器指令进行打印,调用系统串口或并口实现。
针对上述两中情况,我用C#写了一个打印类.在实际工作中,觉得通过执行SQL得到相关Label信息的纪录集,然后根据纪录集控制label打印.用起来特方便,灵活.
可以很自由地控制Label打印内容,数量,模板文档等等一些信息,下面代码供大家学习参考.
PrintLabel类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

using System.IO;
using System.IO.Ports;
using System.Data;
using System.Windows.Forms;

namespace PrintLabel
{
    public class PrintLabel
    {
        //读取文件内容#region //读取文件内容
        //获取需要打印的文本!
        public bool GetContent(DataTable dt, out string fileContent)
        {
            string strFileName = "";

            if (dt.Rows.Count == 0)
            {
                fileContent = "Has no label information !";
                return false;
            }

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (dt.Columns[i].ColumnName.ToUpper().IndexOf("LABELFILE") > -1)
                {
                    strFileName = dt.Rows[0]["LabelFile"].ToString();
                    break;
                }
            }

            if (strFileName == "")
            {
                fileContent = "Can not find label file name !";
                return false;
            }

            string strFilePath = Application.StartupPath + @"\" + strFileName;

            if (!File.Exists(strFilePath))
            {
                fileContent = "Can not find label file template" + strFilePath + " !";
                return false;
            }

            StreamReader sr = new StreamReader(strFilePath, System.Text.Encoding.GetEncoding("gb2312"));
            string strFileContent = sr.ReadToEnd();
            sr.Close();

            try
            {
                int iRow = 0;
                int iCol = 0;
                int iRows = 0;
                iRows = dt.Rows.Count;
                for (; iRow < iRows; iRow++)
                {
                    if (iRow == 0)
                    {
                        for (; iCol < dt.Columns.Count; iCol++)
                        {
                            strFileContent = strFileContent.Replace("<" + dt.Columns[iCol].ColumnName.ToUpper() + ">", dt.Rows[iRow][iCol].ToString());
                        }
                    }
                    else
                    {
                        for (iCol = 0; iCol < dt.Columns.Count; iCol++)
                        {
                            strFileContent = strFileContent.Replace("<" + dt.Columns[iCol].ColumnName.ToUpper() + iRow.ToString() + ">", dt.Rows[iRow][iCol].ToString());
                        }
                    }
                }

                for (int iDelRow = iRows; iDelRow < 100; iDelRow++)
                {
                    for (int iDelCol = 0; iDelCol < dt.Columns.Count; iDelCol++)
                    {
                        if (strFileContent.IndexOf("<" + dt.Columns[iDelCol].ColumnName.ToUpper() + iDelRow.ToString() + ">") > -1)
                        {
                            strFileContent = strFileContent.Replace("<" + dt.Columns[iDelCol].ColumnName.ToUpper() + iDelRow.ToString() + ">", "<DELETELINE>");
                        }
                    }
                }

                string[] strLineArray = System.Text.RegularExpressions.Regex.Split(strFileContent, "\r\n");  //利用正则表达式来分解
                strFileContent = "";
                int j = 1;
                foreach (string strLine in strLineArray)
                {
                    if (strLine.IndexOf("<DELETELINE>") > -1)
                    {
                        continue;
                    }
                    if (j == 1)
                    {
                        strFileContent = strLine;
                        j = j + 1;
                    }
                    else
                    {
                        strFileContent = strFileContent + "\r\n" + strLine;
                        j = j + 1;
                    }
                }
                fileContent = strFileContent;
                return true;
            }
            catch (Exception ex)
            {
                fileContent = ex.Message;
                return false;
            }
        }
        #endregion

        //调用CodeSoft打印,首先添加引用:Lppx2.tlb(codesoft安装后文件中)#region //调用CodeSoft打印,首先添加引用:Lppx2.tlb(codesoft安装后文件中)
        //打印函数,参数为打印机的命令或者其他文本!
        public bool CSWrite(DataTable dt, out string Msg)
        {
            string strFileName = "";

            if (dt.Rows.Count == 0)
            {
                Msg = "Has no label information !";
                return false;
            }

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (dt.Columns[i].ColumnName.ToUpper().IndexOf("LABELFILE") > -1)
                {
                    strFileName = dt.Rows[0]["LabelFile"].ToString();
                    break;
                }
            }

            if (strFileName == "")
            {
                Msg = "Can not find label file name !";
                return false;
            }

            string strFilePath = Application.StartupPath + @"\" + strFileName.Replace(".txt", ".lab").Replace(".TXT", ".lab");

            if (!File.Exists(strFilePath))
            {
                Msg = "Can not find label file template" + strFilePath + " !";
                return false;
            }

            LabelManager2.ApplicationClass lbl = new LabelManager2.ApplicationClass();

            try
            {
                lbl.Documents.Open(strFilePath, false);// 调用设计好的label文件
                LabelManager2.Document doc = lbl.ActiveDocument;


                int iRow = 0;
                int iCol = 0;
                int iRows = 0;
                iRows = dt.Rows.Count;
                for (; iRow < iRows; iRow++)
                {
                    if (iRow == 0)
                    {
                        for (; iCol < dt.Columns.Count; iCol++)
                        {
                            try
                            {
                                doc.Variables.FormVariables.Item(dt.Columns[iCol].ColumnName.ToUpper()).Value = dt.Rows[iRow][iCol].ToString(); //给参数传值
                            }
                            catch (Exception ex1)
                            {
                                continue; //Codesoft文档中如没有该变量则跳出本次循环
                            }
                        }
                    }
                    else
                    {
                        for (iCol = 0; iCol < dt.Columns.Count; iCol++)
                        {
                            try
                            {
                                doc.Variables.FormVariables.Item(dt.Columns[iCol].ColumnName.ToUpper() + iRow.ToString()).Value = dt.Rows[iRow][iCol].ToString(); //给参数传值
                            }
                            catch (Exception ex2)
                            {
                                continue; //Codesoft文档中如没有该变量则跳出本次循环
                            }
                        }
                    }
                }


                int Num = 1;    //打印数量
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (dt.Columns[j].ColumnName.ToUpper().IndexOf("LABELNUM") > -1)
                    {
                        Num = Convert.ToInt32((dt.Rows[0]["LabelNum"].ToString()));
                        break;
                    }
                }

                doc.PrintDocument(Num); //打印
                Msg = "Pass";
                return true;
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
                return false;
            }
            finally
            {
                lbl.Quit();  //退出
            }
        }
        #endregion

        //串口打印#region //串口打印
        //打印函数,参数为打印机的命令或者其他文本!
        public bool COMWrite(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, string myString)
        {
            try
            {
                SerialPort ComPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
                if (ComPort.IsOpen)
                {
                    ComPort.Close();
                }
                ComPort.Open();
                ComPort.WriteLine(myString);
                ComPort.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        //并口打印#region //并口打印

        [StructLayout(LayoutKind.Sequential)]
        private struct OVERLAPPED
        {
            int Internal;
            int InternalHigh;
            int Offset;
            int OffSetHigh;
            int hEvent;
        }
        [DllImport("kernel32.dll")]
        private static extern int CreateFile(string lpFileName, uint dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile);

        [DllImport("kernel32.dll")]
        private static extern bool WriteFile(int hFile, byte[] lpBuffer, int nNumberOfBytesToWriter, out int lpNumberOfBytesWriten, out OVERLAPPED lpOverLapped);

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(int hObject);

        private int iHandle;

        //打开LPT 端口
        public bool LPTOpen()
        {
            iHandle = CreateFile("lpt1", 0x40000000, 0, 0, 3, 0, 0);
            if (iHandle != -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        //打印函数,参数为打印机的命令或者其他文本!
        public bool LPTWrite(string myString)
        {
            if (!LPTOpen()) { return false; }
            if (iHandle != 1)
            {
                int i;
                OVERLAPPED x;
                byte[] mybyte = System.Text.Encoding.Default.GetBytes(myString);
                //return WriteFile(iHandle, mybyte, mybyte.Length, out i, out x);
                if (WriteFile(iHandle, mybyte, mybyte.Length, out i, out x))
                {
                    LPTClose();
                    return true;
                }
                else
                {
                    return false;
                }

            }
            else
            {
                throw new Exception("端口未打开~!");
                return false;
            }
        }
        //关闭打印端口
        public bool LPTClose()
        {
            return CloseHandle(iHandle);
        }
        #endregion
    }
}
private bool PrintModuleLabel(DataTable dt)
{
    string fileMsg;
    if (PrintLabel.GetContent(dt,out fileMsg)==false)
    {
        MessageBox.Show(fileMsg, "Module Buffer", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return false;
    }

    if (rdoCOMPort.Checked==true)
    {
        string portName=cboPortName.Text.ToString().Trim();
        int baudRate=Convert.ToInt32(cboBaudRate.Text.ToString().Trim());
        Parity parity=Parity.None;
        int dataBits=Convert.ToInt32(cboDataBits.Text.ToString().Trim());
        StopBits stopBits;
        switch (cboStopBits.Text.ToString().Trim())
        {
            case "1":
                stopBits = StopBits.One;
                break;
            case "2":
                stopBits = StopBits.Two;
                break;
            case "None":
                stopBits = StopBits.None;
                break;
            default:
                stopBits = StopBits.One;
                break;

        }
        if (PrintLabel.COMWrite(portName,baudRate,parity,dataBits,stopBits,fileMsg)==false)
        {
            MessageBox.Show("COM Port Error !", "Module Buffer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
        else
        {
            return true;
        }
    }
    else if(rdoLPTPort.Checked==true)
    {
        if (PrintLabel.LPTWrite(fileMsg)==false)
        {
            MessageBox.Show("LPT Port Error !", "Module Buffer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
        else
        {
            return true;
        }
    }
    else
    {
        string Msg;
        if (PrintLabel.CSWrite(dt,out Msg)==false)
        {
            MessageBox.Show(Msg, "Module Buffer", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
        else
        {
            return true;
        }
    }
}
转载自 http://www.cnblogs.com/zgm2006/archive/2008/09/18/1293413.html

你可能感兴趣的:(C# 打印Label)