周广明的博客

.Net & MS SQL Tech
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# 打印Label的两种方式及实现

Posted on 2008-09-18 16:03  Zhougm  阅读(7142)  评论(6)    收藏  举报
一.调用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
    
{
        
//读取文件内容

        
//调用CodeSoft打印,首先添加引用:Lppx2.tlb(codesoft安装后文件中)

        
//串口打印

        
//并口打印
    }

}

 
程序实现
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;
        }

    }

}

 注:以上内容,如需转载请注明出处.