Search code examples
.netbarcodeean-13

generating .NET EAN-13 string


Can someone recommend a (free for commercial use) library to generate EAN-13 barcode?

I do not need an image, only a string.

I would like to pass product code, manufacturer code and country/region (not number system) as a parameters.

It could translate country/region to number system, concat it all together and calculate checksum.


Solution

  • Basically: Ean13 is a checksum calculation based on a model:

    So you have a number of 12 digits without the checksum and then add the checksum

    CheckSum Function:

       public static string CalculateEan13(string country, string manufacturer, string product)
        {
            string temp = $"{country}{manufacturer}{product}";
            int sum = 0;
            int digit = 0;
    
            // Calculate the checksum digit here.
            for (int i = temp.Length; i >= 1; i--)
            {
                digit = Convert.ToInt32(temp.Substring(i - 1, 1));
                // This appears to be backwards but the 
                // EAN-13 checksum must be calculated
                // this way to be compatible with UPC-A.
                if (i % 2 == 0)
                { // odd  
                    sum += digit * 3;
                }
                else
                { // even
                    sum += digit * 1;
                }
            }
            int checkSum = (10 - (sum % 10)) % 10;
            return $"{temp}{checkSum}";
        }
    

    How to calculate your check digit yourself

    Example barcode number: 501234576421

    Step 1: add together all alternate numbers starting from the right

    5 0 1 2 3 4 5 7 6 4 2 1

    0 + 2 + 4 + 7 + 4 + 1 = 18

    Step 2: multiply the answer by 3

    18 x 3 = 54

    Step 3: now add together the remaining numbers

    5 0 1 2 3 4 5 7 6 4 2 1

    5 + 1 + 3 + 5 + 6 + 2 = 22

    Step 4: add step 2 and 3 together

    54 + 22 = 76

    Step 5: the difference between step 4 and the next 10th number:

    76 + 4 = 80

    Check digit = 4