C#生成条码图片,并用条码打印机打印

来源:互联网 发布:奎屯大数据 编辑:程序博客网 时间:2024/05/01 10:10

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.Text.RegularExpressions;
using System.Windows.Forms;

/// <summary>
/// code39 的摘要说明
/// </summary>
public class code39
{
    private Hashtable Decode;
    private Hashtable CheckCode;
    //每個字元間的間隔符
    private string SPARATOR = "0";
    public int WidthCU = 3;  //粗線和寬間隙寬度
    public int WidthXI = 1;  //細線和窄間隙寬度
    public int xCoordinate = 10;//75;  //條碼起始座標
    public int LineHeight = 60;
    private int Height = 0;
    private int Width = 0;
    private string _barcode = "";

 public code39()
 {
  //
  // TODO: 在此处添加构造函数逻辑
  //
        Decode = new Hashtable();
        Decode.Add("0", "000110100");
        Decode.Add("1", "100100001");
        Decode.Add("2", "001100001");
        Decode.Add("3", "101100000");
        Decode.Add("4", "000110001");
        Decode.Add("5", "100110000");
        Decode.Add("6", "001110000");
        Decode.Add("7", "000100101");
        Decode.Add("8", "100100100");
        Decode.Add("9", "001100100");
        Decode.Add("A", "100001001");
        Decode.Add("B", "001001001");
        Decode.Add("C", "101001000");
        Decode.Add("D", "000011001");
        Decode.Add("E", "100011000");
        Decode.Add("F", "001011000");
        Decode.Add("G", "000001101");
        Decode.Add("H", "100001100");
        Decode.Add("I", "001001101");
        Decode.Add("J", "000011100");
        Decode.Add("K", "100000011");
        Decode.Add("L", "001000011");
        Decode.Add("M", "101000010");
        Decode.Add("N", "000010011");
        Decode.Add("O", "100010010");
        Decode.Add("P", "001010010");
        Decode.Add("Q", "000000111");
        Decode.Add("R", "100000110");
        Decode.Add("S", "001000110");
        Decode.Add("T", "000010110");
        Decode.Add("U", "110000001");
        Decode.Add("V", "011000001");
        Decode.Add("W", "111000000");
        Decode.Add("X", "010010001");
        Decode.Add("Y", "110010000");
        Decode.Add("Z", "011010000");
        Decode.Add("-", "010000101");
        Decode.Add("%", "000101010");
        Decode.Add("$", "010101000");
        Decode.Add("*", "010010100");

        CheckCode = new Hashtable();
        CheckCode.Add("0", "0");
        CheckCode.Add("1", "1");
        CheckCode.Add("2", "2");
        CheckCode.Add("3", "3");
        CheckCode.Add("4", "4");
        CheckCode.Add("5", "5");
        CheckCode.Add("6", "6");
        CheckCode.Add("7", "7");
        CheckCode.Add("8", "8");
        CheckCode.Add("9", "9");
        CheckCode.Add("A", "10");
        CheckCode.Add("B", "11");
        CheckCode.Add("C", "12");
        CheckCode.Add("D", "13");
        CheckCode.Add("E", "14");
        CheckCode.Add("F", "15");
        CheckCode.Add("G", "16");
        CheckCode.Add("H", "17");
        CheckCode.Add("I", "18");
        CheckCode.Add("J", "19");
        CheckCode.Add("K", "20");
        CheckCode.Add("L", "21");
        CheckCode.Add("M", "22");
        CheckCode.Add("N", "23");
        CheckCode.Add("O", "24");
        CheckCode.Add("P", "25");
        CheckCode.Add("Q", "26");
        CheckCode.Add("R", "27");
        CheckCode.Add("S", "28");
        CheckCode.Add("T", "29");
        CheckCode.Add("U", "30");
        CheckCode.Add("V", "31");
        CheckCode.Add("W", "32");
        CheckCode.Add("X", "33");
        CheckCode.Add("Y", "34");
        CheckCode.Add("Z", "35");
        CheckCode.Add("-", "36");
        CheckCode.Add(".", "37");
        CheckCode.Add(",", "38");
        CheckCode.Add("$", "39");
        CheckCode.Add("/", "40");
        CheckCode.Add("+", "41");
        CheckCode.Add("%", "42");

 }
    //保存檔
        public Boolean saveFile(string Code, string Title, int UseCheck, int ValidateCode)
        {
            string code39 = Encode39(Code, UseCheck, ValidateCode);
            if (code39 != null)
            {
                Bitmap saved = new Bitmap(this.Width, this.Height);
                Graphics g = Graphics.FromImage(saved);
                g.FillRectangle(new SolidBrush(Color.White), 0, 0, this.Width, this.Height);
                this.DrawBarCode39(code39, Title, g);
                //string path = ConfigurationSettings.AppSettings["ImagePath"];
                string path = string.Empty;
                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.Filter = "*.JPEG|*.JPEG|*.JPG|*.JPG";
                saveFile.ShowDialog();
                if (!saveFile.FileName.Equals(""))
                {
                    path = saveFile.FileName;
                }
                else
                {
                    return false;
                }
                string filename = path + Code + ".jpg";
                saved.Save(filename, ImageFormat.Jpeg);
                saved.Dispose();
                return true;
            }
            return false;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Code">要生成條碼的內容</param>
        /// <param name="Title">要顯示的標題</param>
        /// <param name="UseCheck">計算檢查碼</param>
        /// <returns></returns>
        public Bitmap CreateBarCode(string Code, string Title, int UseCheck,int ValidateCode)
        {
            this._barcode = Code;

            string code39 = Encode39(Code, UseCheck,ValidateCode);
            if (code39 != null)
            {
                Bitmap saved = new Bitmap(this.Width, this.Height);
                Graphics g = Graphics.FromImage(saved);
                g.FillRectangle(new SolidBrush(Color.White), 0, 0, this.Width, this.Height);
                this.DrawBarCode39(code39, Title, g);
                return saved;
            }
            return null;
        }
        /***
        * Code:未經編碼的字串
        *
        * **/
        private string Encode39(string Code, int UseCheck, int ValidateCode)
        {
            int UseStand = 1;  //檢查輸入待編碼字元是否為標準格式(是否以*開始結束)

            //保存備份資料
            string originalCode = Code;

            //為空不進行編碼
            if (null == Code || Code.Trim().Equals(""))
            {
                return null;
            }
            //檢查錯誤字元
            Code = Code.ToUpper();  //轉為大寫
            Regex rule = new Regex(@"[^0-9A-Z%$/-*]");
            if (rule.IsMatch(Code))
            {
                MessageBox.Show("編碼中包含非法字元,目前僅支援字母,數位及%$-*符號!!");
                return null;
            }
            //計算檢查碼
            if (UseCheck == 1)
            {
                int Check = 0;
                //累計求和
                for (int i = 0; i < Code.Length; i++)
                {
                    Check += int.Parse((string)CheckCode[Code.Substring(i, 1)]);
                }
                //取模
                Check = Check % 43;
                //附加檢測碼
                if (ValidateCode == 1)
                {
                    foreach (DictionaryEntry de in CheckCode)
                    {
                        if ((string)de.Value == Check.ToString())
                        {
                            Code = Code + (string)de.Key;
                            break;
                        }
                    }
                }
            }
            //標準化輸入字元,增加起始標記
            if (UseStand == 1)
            {
                if (Code.Substring(0, 1) != "*")
                {
                    Code = "*" + Code;
                }
                if (Code.Substring(Code.Length - 1, 1) != "*")
                {
                    Code = Code + "*";
                }
            }
            //轉換成39編碼
            string Code39 = string.Empty;
            for (int i = 0; i < Code.Length; i++)
            {
                Code39 = Code39 + (string)Decode[Code.Substring(i, 1)] +SPARATOR;
            }

            int height = 30 + LineHeight;//定義圖片高度     
            int width = xCoordinate;
            for (int i = 0; i < Code39.Length; i++)
            {
                if ("0".Equals(Code39.Substring(i, 1)))
                {
                    width += WidthXI;
                }
                else
                {
                    width += WidthCU;
                }
            }
            this.Width = width + xCoordinate;
            this.Height = height;

            return Code39;
        }

        private void DrawBarCode39(string Code39, string Title, Graphics g)
        {
            int UseTitle = 1;  //條碼上端顯示標題
            //int UseTTF = 1;  //使用TTF字體,方便顯示中文,需要$UseTitle=1時才能生效
            if (Title.Trim().Equals(""))
            {
                UseTitle = 0;
            }
            Pen pWhite = new Pen(Color.White, 1);
            Pen pBlack = new Pen(Color.Black, 1);
            int position = xCoordinate;
            //顯示標題
            if (UseTitle == 1)
            {
                Font TitleFont = new Font("宋體", 9, FontStyle.Bold);
                SizeF sf = g.MeasureString(Title, TitleFont);
                g.DrawString(Title, TitleFont, Brushes.Black, (Width - sf.Width) / 2, 5);
            }
            for (int i = 0; i < Code39.Length; i++)
            {
                //繪製條線
                if ("0".Equals(Code39.Substring(i, 1)))
                {
                    for (int j = 0; j < WidthXI; j++)
                    {
                        g.DrawLine(pBlack, position + j, 30, position + j, 30 + LineHeight);
                    }
                    position += WidthXI;
                }
                else
                {
                    for (int j = 0; j < WidthCU; j++)
                    {
                        g.DrawLine(pBlack, position + j, 30, position + j, 30 + LineHeight);
                    }
                    position += WidthCU;
                }
                i++;
                //繪製間隔線
                if ("0".Equals(Code39.Substring(i, 1)))
                {
                    position += WidthXI;
                }
                else
                {
                    position += WidthCU;
                }
            }
            Font lableFont = new Font("宋體", 9, FontStyle.Bold);
            SizeF lb = g.MeasureString(this._barcode, lableFont);
            g.DrawString(this._barcode, lableFont, Brushes.Black, (Width - lb.Width) / 2, 5);

            return;
        }

    }

*********************************************************************************************

********************************************************************************************

using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Text;


public class Handler : IHttpHandler {

    protected int _height = 30;
    protected string _code = "0002bfft6280824";
    protected string code = "";
   
    public void ProcessRequest (HttpContext context) {
        if (context.Request.QueryString["height"] != null)
        {
            _height = Convert.ToInt32(context.Request.QueryString["height"].ToString());
        }
        if (context.Request.QueryString["code"] != null)
        {
            _code = context.Request.QueryString["code"].ToString();
        }
        code = getCodeText(_code);
        int p_w = code.Length;
        int p_h = _height + 20;
        context.Response.ContentType = "image/gif";
        Bitmap myBitmap = new Bitmap(p_w, p_h);

        Graphics myGrap = Graphics.FromImage(myBitmap);
        myGrap.Clear(Color.White);

        for (int i = 0; i < p_w; i++)
        {
            Pen myPen = new Pen(Color.White, 1);
            if (code.Substring(i, 1) == "|")
            {
                myPen.Color = Color.Black;
            }
            // myGrap.DrawString(_code.Substring(i, 1), new Font("宋体", 12), new SolidBrush(Color.Black), i*13, 20);
            myGrap.DrawLine(myPen, i, 0, i, _height);
        }

        myGrap.DrawString(_code, new Font("Courier New", 10), new SolidBrush(Color.Black), -4, _height);
        myBitmap.Save(context.Response.OutputStream, ImageFormat.Gif);
        context.Response.End();

    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    private string getCodeText(string n)
    {
        string zf = n.ToLower();
        zf = zf.Replace("0", "_|_|__||_||_|");
        zf = zf.Replace("1", "_||_|__|_|_||");
        zf = zf.Replace("2", "_|_||__|_|_||");
        zf = zf.Replace("3", "_||_||__|_|_|");
        zf = zf.Replace("4", "_|_|__||_|_||");
        zf = zf.Replace("5", "_||_|__||_|_|");
        zf = zf.Replace("7", "_|_|__|_||_||");
        zf = zf.Replace("6", "_|_||__||_|_|");
        zf = zf.Replace("8", "_||_|__|_||_|");
        zf = zf.Replace("9", "_|_||__|_||_|");
        zf = zf.Replace("a", "_||_|_|__|_||");
        zf = zf.Replace("b", "_|_||_|__|_||");
        zf = zf.Replace("c", "_||_||_|__|_|");
        zf = zf.Replace("d", "_|_|_||__|_||");
        zf = zf.Replace("e", "_||_|_||__|_|");
        zf = zf.Replace("f", "_|_||_||__|_|");
        zf = zf.Replace("g", "_|_|_|__||_||");
        zf = zf.Replace("h", "_||_|_|__||_|");
        zf = zf.Replace("i", "_|_||_|__||_|");
        zf = zf.Replace("j", "_|_|_||__||_|");
        zf = zf.Replace("k", "_||_|_|_|__||");
        zf = zf.Replace("l", "_|_||_|_|__||");
        zf = zf.Replace("m", "_||_||_|_|__|");
        zf = zf.Replace("n", "_|_|_||_|__||");
        zf = zf.Replace("o", "_||_|_||_|__|");
        zf = zf.Replace("p", "_|_||_||_|__|");
        zf = zf.Replace("r", "_||_|_|_||__|");
        zf = zf.Replace("q", "_|_|_|_||__||");
        zf = zf.Replace("s", "_|_||_|_||__|");
        zf = zf.Replace("t", "_|_|_||_||__|");
        zf = zf.Replace("u", "_||__|_|_|_||");
        zf = zf.Replace("v", "_|__||_|_|_||");
        zf = zf.Replace("w", "_||__||_|_|_|");
        zf = zf.Replace("x", "_|__|_||_|_||");
        zf = zf.Replace("y", "_||__|_||_|_|");
        zf = zf.Replace("z", "_|__||_||_|_|");
        zf = zf.Replace("-", "_|__|_|_||_||");
        zf = zf.Replace("*", "_|__|_||_||_|");
        zf = zf.Replace("/", "_|__|__|_|__|");
        zf = zf.Replace("%", "_|_|__|__|__|");
        zf = zf.Replace("+", "_|__|_|__|__|");
        zf = zf.Replace(".", "_||__|_|_||_|");
        return zf;
    }

 

 

********************************************************************************************

打印条码 

 

<script type="text/javascript" src="../../../js/jquery.js"></script>
<style media=print>
.Noprint {
 display: none;
}
.PageNext {
 page-break-after: always;
}
</style>
<style>
.tdp {
 border-bottom: 1 solid #000000;
 border-left: 1 solid #000000;
 border-right: 0 solid #ffffff;
 border-top: 0 solid #ffffff;
}
.tabp {
 border-color: #000;
 border-style: solid;
 border-top-width: 2px;
 border-right-width: 2px;
 border-bottom-width: 1px;
 border-left-width: 1px;
}
.NOPRINT {
 font-family: "宋体";
 font-size: 9pt;
}
</style>
<center class="Noprint">
 <div>
  <OBJECT id=WebBrowser
   classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 height=0 width=0>
  </OBJECT>
  <input type=button value=打印
   onclick=document.all.WebBrowser.ExecWB(6,1)>
  <!-- <input type=button value=直接打印
   onclick=document.all.WebBrowser.ExecWB(6,6)>
  <input type=button value=页面设置
   onclick=document.all.WebBrowser.ExecWB(8,1)>
  <input type="button" value="清空页码" onclick="PageSetup_Null()">
  <input type="button" value="恢复页码" onclick="PageSetup_Default()">
  <input type=button value=打印预览
   onclick=document.all.WebBrowser.ExecWB(7,1)> -->
 </div>
</center>
<hr align="center" width="90%" size="1" noshade class="NOPRINT">
<div id="pageWidth" style="width: 1cm; display: none;">
 &nbsp;
</div>
<div class="layout" style="text_align:center;" id="codeIn">
 <div id="modle" style="display:none; padding: 0px; "><div style="float:left;" style="margin-top:30px" ></div><div style="float:right; padding-bottom: 0px; padding: 0px;"><div name="custname" style="text-align:left;width:100%; height: 0.7cm; margin-left:1cm;" ></div><img src="" name="imgCode"  style=" margin: 0px; "></div><div style="clear:both;"></div></div>
 <div id="dbList" style="padding: 0px; "></div>
</div>
<script type="text/javascript">
   $(document).ready(function(){
      var scale = parseFloat($("#pageWidth").width())-1;
      var box_code=$.getParam("box_code");
      var cust_name=$.getParam("cust_name");
      setPageSize("codeIn");
      var boxCode=box_code.split(",");
      var custName=cust_name.split(",");
    for(i=0;i<boxCode.length;i++)
    {
     var temp=$("#modle").clone();
      temp.show();
      //temp.width(scale*9.08);
      //temp.height(scale*3.56);
      temp.get(0).style.width=9.08+"cm";
      temp.get(0).style.height=3.56 - 0.2*2+"cm";
         temp.find("img[@name=imgCode]").attr("src","/arch_1.0/barcode?msg=" +boxCode[i]+"")
         temp.find("img[@name=imgCode]")[0].style.width=9.08-3-1*2+"cm";
         temp.find("img[@name=imgCode]")[0].style.height=3.56 - 0.2*2-0.7+"cm";
         temp.find("div[@name=custname]").text(custName[i]);
         temp.appendTo($("#dbList"));
    }
   })
      function setPageSize(Id){
    var scale = parseFloat($("#pageWidth").width())-1;
             $("#"+Id).width(scale*(9-0.1905*2));
      }
</script>
 
 
 window.open("/arch/business/arch_in/print_block.html?bag_code="+ids+"&cust_names="+cust_names+"",null,"status=no,toolbar=no,menubar=yes,location=no")

 

 

原创粉丝点击