Question

I have made a Windows Form application and I want to generate a delivery note with a barcode. I have embed the barcode font, but I get an error. See this question: Embed Barcode in C# PDF Library

Now, I want to make an image from the barcode and embed this image on my delivery note. I have searched on Google for doing this, and I found the following code:

    private Image DrawBarcodeAfleverbonImage(String text)
    {
        Font barcodeFont = new Font("Bar-Code 39", 31, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
        //Font barcodeFont = new Font("Arial", 31, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);

        //first, create a dummy bitmap just to get a graphics object
        Image img = new Bitmap(1, 1);
        Graphics drawing = Graphics.FromImage(img);

        //measure the string to see how big the image needs to be
        SizeF textSize = drawing.MeasureString(text, barcodeFont);

        //free up the dummy image and old graphics object
        img.Dispose();
        drawing.Dispose();

        //create a new image of the right size
        img = new Bitmap((int)textSize.Width, (int)textSize.Height);

        drawing = Graphics.FromImage(img);

        //create a brush for the text
        Brush textBrush = new SolidBrush(Color.Black);
        drawing.DrawString(text, barcodeFont, textBrush, 0, 0);

        drawing.Save();
        img.Save(@"C:\Users\Marten\Documents\test.png");

        textBrush.Dispose();
        drawing.Dispose();

        return img;

If I run my program an image will be created. There is just one problem: the barcode font is too thick, so I can not scan:

enter image description here

What is wrong?

Was it helpful?

Solution

You need to set a background color before drawing your text:

drawing.Clear(Color.White);
drawing.DrawString(text, barcodeFont, textBrush, 0, 0);

Or if you want a transparent background you need to turn off font smoothing.

drawing.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
drawing.DrawString(text, barcodeFont, textBrush, 0, 0);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top