Search code examples
itextbarcodeean-13

iText for .NET barcode


I try to create a PDF with a EAN13 Bar-code using the iTextSharp library. I try to generate a barcode with the value "023942432852".

iTextSharp.text.Image imageEAN = codeEan.CreateImageWithBarcode(cb, null, null);

throws System.IndexOutOfRangeException.

There is the code:

Document pdfdoc = new Document(pageSize, _margSx, _margDx, _margUp, _margBo);
            PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(_path + @"\Barcode.pdf", FileMode.Create));


            pdfdoc.Open();

            PdfContentByte cb = writer.DirectContent;

            pdfdoc.PageSize.BackgroundColor = BaseColor.GRAY;


            BarcodeEAN codeEan = new BarcodeEAN();
            if (CreaChecksum)
                codeEan.GenerateChecksum = true;
            codeEan.ChecksumText = true;
            codeEan.CodeType = Barcode.EAN13;
            codeEan.Code = barcode;

            iTextSharp.text.Image imageEAN = codeEan.CreateImageWithBarcode(cb, null, null);
            imageEAN.ScaleAbsolute(100, 40);
            imageEAN.SetAbsolutePosition(pdfdoc.PageSize.Right - 150f, pdfdoc.PageSize.Bottom + 30f);   
            pdfdoc.Add(imageEAN);

Solution

  • As the name indicates an EAN13 bar code requires 13 digits, just like an EAN8 bar code requires 8 digits. You are trying to create a bar code for this string:

    "023942432852"
    

    When I count the number of digits in this string, I only find 12. One digit is missing. Please complete the string so that its length is 13.