Chitrakant Sahu
Chitrakant Sahu

Reputation: 31

how to generate readable Barcode

I want to generate Barcode, for this I use following code

protected void Button3_Click(object sender, EventArgs e)
    {
        string barCode = TextBox1.Text;
        System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
        using (Bitmap bitMap = new Bitmap(barCode.Length * 40, 80))
        {
            using (Graphics graphics = Graphics.FromImage(bitMap))
            {
                Font oFont = new Font("IDAutomationHC39M", 16);
                //Font oFont = new Font(Server.MapPath("~\\Fonts\\IDAutomationHC39M.ttf"), 16);
                PointF point = new PointF(2f, 2f);
                SolidBrush blackBrush = new SolidBrush(Color.Black);
                SolidBrush whiteBrush = new SolidBrush(Color.White);
                graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
                graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point);
            }
            using (MemoryStream ms = new MemoryStream())
            {
                bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] byteImage = ms.ToArray();

                Convert.ToBase64String(byteImage);
                imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
            }
            plBarCode.Controls.Add(imgBarCode);
        }
}

This code work fine if I install the font "IDAutomationHC39M" in system and trying to generate Barcode. But it is not working if I am keeping this font in particular folder and pass the font path to Font object in code. i.e. Font oFont = new Font(Server.MapPath("~\\Fonts\\IDAutomationHC39M.ttf"), 16); in this case Barcode is not generated and whatever the text I passed in Textbox is print as it is.

So I want to know that it is necessary to install the font in the system and is it possible to keep a Barcode font in a particular folder and can generate Barcode from this.

Please any one give me solution for this.

I am working in Asp.net, C#.

Upvotes: 0

Views: 1093

Answers (1)

BugFinder
BugFinder

Reputation: 17858

Have you read this Read a font from a file

It explains about creating a private font collection and adding the file font to it.

private FontFamily LoadFontFamily(string fileName, out PrivateFontCollection _myFonts)
        {
            //IN MEMORY _myFonts point to the myFonts created in the load event 11 lines up.
            _myFonts = new PrivateFontCollection();//here is where we assing memory space to myFonts
            _myFonts.AddFontFile(fileName);//we add the full path of the ttf file
            return _myFonts.Families[0];//returns the family object as usual.
        }

and then you can use it such as

    Font theFont = new Font(family, 20.0f);

    //HERE WE SET THE LABEL FONT PROPERTY TO THE ONE WE JUST LOADED
    label1.Font = theFont;

Upvotes: 1

Related Questions