Search code examples
c#winformsbarcodezen

Zen Barcode with characters. Winforms


enter image description here

Hi does anyone know how to include the numbers/strings too at the bottom when it draw the barcode?

Here is my code

     private void btnGenerate_Click_1(object sender, EventArgs e)
    {
        Zen.Barcode.Code128BarcodeDraw barcode = Zen.Barcode.BarcodeDrawFactory.Code128WithChecksum;
        pictureBox1.Image = barcode.Draw(textBox1.Text, 50);
    }

PS should i save it in a database column and call it there too? Thank you

UPDATE base from sir VVatashi answer. here is the new output.

enter image description here

But its overlapping the barcode i want it to look something like this: enter image description here

Thank you


Solution

  • You can print text on image with System.Drawing, according to your code:

    Zen.Barcode.Code128BarcodeDraw barcode = Zen.Barcode.BarcodeDrawFactory.Code128WithChecksum;
    var image = barcode.Draw(textBox1.Text, 50);
    
    using (var graphics = Graphics.FromImage(image))
    using (var font = new Font("Consolas", 12)) // Any font you want
    using (var brush = new SolidBrush(Color.White))
    using (var format = new StringFormat() { LineAlignment = StringAlignment.Far }) // To align text above the specified point
    {
        // Print a string at the left bottom corner of image
        graphics.DrawString(textBox1.Text, font, brush, 0, image.Height, format);
    }
    
    pictureBox1.Image = image;
    

    It's a bit unclear how database related to the first part of your question.

    Update. Oh, I did not notice that the generated barcode graph is the entire image. In this case, you can draw barcode and text on a larger image:

    Zen.Barcode.Code128BarcodeDraw barcode = Zen.Barcode.BarcodeDrawFactory.Code128WithChecksum;
    var barcodeImage = barcode.Draw(textBox1.Text, 50);
    
    var resultImage = new Bitmap(barcodeImage.Width, barcodeImage.Height + 20); // 20 is bottom padding, adjust to your text
    
    using (var graphics = Graphics.FromImage(resultImage))
    using (var font = new Font("Consolas", 12))
    using (var brush = new SolidBrush(Color.Black))
    using (var format = new StringFormat()
    {
        Alignment = StringAlignment.Center, // Also, horizontally centered text, as in your example of the expected output
        LineAlignment = StringAlignment.Far
    })
    {
        graphics.Clear(Color.White);
        graphics.DrawImage(barcodeImage, 0, 0);
        graphics.DrawString(textBox1.Text, font, brush, resultImage.Width / 2, resultImage.Height, format);
    }
    
    pictureBox1.Image = resultImage;