Exemple #1
0
// Encode returns a EAN 8 or EAN 13 barcode for the given code
func Encode(code string) (barcode.Barcode, error) {
	var checkSum int
	if len(code) == 7 || len(code) == 12 {
		code += string(calcCheckNum(code))
		checkSum = utils.RuneToInt(calcCheckNum(code))
	} else if len(code) == 8 || len(code) == 13 {
		check := code[0 : len(code)-1]
		check += string(calcCheckNum(check))
		if check != code {
			return nil, errors.New("checksum missmatch")
		}
		checkSum = utils.RuneToInt(rune(code[len(code)-1]))
	}

	if len(code) == 8 {
		result := encodeEAN8(code)
		if result != nil {
			return utils.New1DCode("EAN 8", code, result, checkSum), nil
		}
	} else if len(code) == 13 {
		result := encodeEAN13(code)
		if result != nil {
			return utils.New1DCode("EAN 13", code, result, checkSum), nil
		}
	}
	return nil, errors.New("invalid ean code data")
}
Exemple #2
0
func calcCheckNum(code string) rune {
	x3 := len(code) == 7
	sum := 0
	for _, r := range code {
		curNum := utils.RuneToInt(r)
		if curNum < 0 || curNum > 9 {
			return 'B'
		}
		if x3 {
			curNum = curNum * 3
		}
		x3 = !x3
		sum += curNum
	}

	return utils.IntToRune((10 - (sum % 10)) % 10)
}
Exemple #3
0
// AddCheckSum calculates the correct check-digit and appends it to the given content.
func AddCheckSum(content string) (string, error) {
	if content == "" {
		return "", errors.New("content is empty")
	}

	even := len(content)%2 == 1
	sum := 0
	for _, r := range content {
		if _, ok := encodingTable[r]; ok {
			value := utils.RuneToInt(r)
			if even {
				sum += value * 3
			} else {
				sum += value
			}
			even = !even
		} else {
			return "", fmt.Errorf("can not encode \"%s\"", content)
		}
	}

	return content + string(utils.IntToRune(sum%10)), nil
}