Sunday, February 6, 2011

Create Barcode Image with asp.net

To create and save barcode image in database with asp.net :




private Bitmap createbarcode(string data)
    {
        Bitmap barcode = new Bitmap(1, 1);
        PrivateFontCollection pfc = new PrivateFontCollection();
        string pth = Server.MapPath("../Fonts/idautomationhc39m.ttf");
        pfc.AddFontFile(pth);
        FontFamily ff = pfc.Families[0];
        FontFamily family = new FontFamily("IDAutomationHC39M", pfc);
        System.Drawing.Font threeofnine = new System.Drawing.Font(family, 12, FontStyle.Regular, GraphicsUnit.Point);
        Graphics graphic = Graphics.FromImage(barcode);
        SizeF datasize = graphic.MeasureString(data, threeofnine);
        barcode = new Bitmap(barcode, datasize.ToSize());
        graphic = Graphics.FromImage(barcode);
        graphic.Clear(System.Drawing.Color.White);
        graphic.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
        graphic.DrawString(data, threeofnine, new SolidBrush(System.Drawing.Color.Black), 0, 0);
        graphic.Flush();
        threeofnine.Dispose();
        graphic.Dispose();
        return barcode;
    }
    private void GenerateAndGetBarCode()
    {
        data = GenerateRandomCode();
        Bitmap barCode = createbarcode("*" + data + "*");
        imgPath = ConfigurationManager.AppSettings["site_url"] + "/Barcode/" + data + ".Gif";
        String filepath = Server.MapPath("../BarCode/") + data + ".Gif";
        barCode.Save( filepath, ImageFormat.Gif);
    }

No comments:

Post a Comment