简体   繁体   中英

Barcode4j - Generate check digit in an EAN13 barcode

When yo generate a barcode with Barcode4j as an image, you could obtain the human readable text, too, for instance:

EAN13 barcode example

In this picture we can see that the human readable text is: 1000000012026

In this example the barcode has been generated with the code 100000001202 and the number 6 is the check digit added by Barcode4j generator.

So, my question is: Is possible obtain the check digit of an EAN13 generated barcode with Barcode4j? Because I know how to render this as a image, but I don't know how to obtain the human readable text, as a plain text.

Regards,

Miguel.

Thanks to Barcode4j plugin, you can calculate the checksum with the barcode format you need. In Java 7, you can calculate the checkSum as this way:

private String calculateCodeWithcheckSum(String codigo){
   EAN13Bean generator = new EAN13Bean();
   UPCEANLogicImpl impl = generator.createLogicImpl();
   codigo += impl.calcChecksum(codigo);
   return codigo;
}

First, you need the EAN13 barcode format, so you can get the class that the plugin provides you, and call its only method: createLogicImpl() .

This method is used to give you a class of type UPCEANLogicImpl . This is the class you need, because you can find in it the method to calculate the checkSum. So, you only have to call the method calcChecksum giving your code ( 100000001202 ), and will give you the checkSum value ( 6 ).

You can check it in the next web: http://www.gs1.org/check-digit-calculator

Adding your code and the checkSum value will give you the value you need ( 1000000012026 )

In case you what to compute the check digit without importing a java library here's the code:

public static String ean13CheckDigit(String barcode) {
    int s = 0;
    for (int i = 0; i < 12; i++) {
        int c = Character.getNumericValue(barcode.charAt(i));
        s += c * ( i%2 == 0? 1: 3);
    }
    s = (10 - s % 10) % 10;
    barcode += s;
    return barcode;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM