Open Source Repository

Home /itextpdf/itextpdf-5.1.2 | Repository Home



com/itextpdf/text/pdf/BarcodeDatamatrix.java
/*
 * $Id: BarcodeDatamatrix.java 4784 2011-03-15 08:33:00Z blowagie $
 *
 * This file is part of the iText (R) project.
 * Copyright (c) 1998-2011 1T3XT BVBA
 * Authors: Bruno Lowagie, Paulo Soares, et al.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License version 3
 * as published by the Free Software Foundation with the addition of the
 * following permission added to Section 15 as permitted in Section 7(a):
 * FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY 1T3XT,
 * 1T3XT DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA, 02110-1301 USA, or download the license from the following URL:
 * http://itextpdf.com/terms-of-use/
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License,
 * a covered work must retain the producer line in every PDF that is created
 * or manipulated using iText.
 *
 * You can be released from the requirements of the license by purchasing
 * a commercial license. Buying such a license is mandatory as soon as you
 * develop commercial activities involving the iText software without
 * disclosing the source code of your own applications.
 * These activities include: offering paid services to customers as an ASP,
 * serving PDFs on the fly in a web application, shipping iText with a closed
 * source product.
 *
 * For more information, please contact iText Software Corp. at this
 * address: [email protected]
 */
package com.itextpdf.text.pdf;

import java.awt.Canvas;
import java.awt.image.MemoryImageSource;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Hashtable;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.codec.CCITTG4Encoder;

/**
 * A DataMatrix 2D barcode generator.
 */
public class BarcodeDatamatrix {
    /**
     * No error.
     */
    public static final int DM_NO_ERROR = 0;
    /**
     * The text is too big for the symbology capabilities.
     */
    public static final int DM_ERROR_TEXT_TOO_BIG = 1;
    /**
     * The dimensions given for the symbol are illegal.
     */
    public static final int DM_ERROR_INVALID_SQUARE = 3;
    /**
     * An error while parsing an extension.
     */
    public static final int DM_ERROR_EXTENSION = 5;

    /**
     * The best encodation will be used.
     */
    public static final int DM_AUTO = 0;
    /**
     * ASCII encodation.
     */
    public static final int DM_ASCII = 1;
    /**
     * C40 encodation.
     */
    public static final int DM_C40 = 2;
    /**
     * TEXT encodation.
     */
    public static final int DM_TEXT = 3;
    /**
     * Binary encodation.
     */
    public static final int DM_B256 = 4;
    /**
     * X21 encodation.
     */
    public static final int DM_X21 = 5;
    /**
     * EDIFACT encodation.
     */
    public static final int DM_EDIFACT = 6;
    /**
     * No encodation needed. The bytes provided are already encoded.
     */
    public static final int DM_RAW = 7;

    /**
     * Allows extensions to be embedded at the start of the text.
     */
    public static final int DM_EXTENSION = 32;
    /**
     * Doesn't generate the image but returns all the other information.
     */
    public static final int DM_TEST = 64;

    private final static DmParams[] dmSizes = {
        new DmParams(10101010335),
        new DmParams(12121212557),
        new DmParams(818818557),
        new DmParams(141414148810),
        new DmParams(832816101011),
        new DmParams(16161616121212),
        new DmParams(12261226161614),
        new DmParams(18181818181814),
        new DmParams(20202020222218),
        new DmParams(12361218222218),
        new DmParams(22222222303020),
        new DmParams(16361618323224),
        new DmParams(24242424363624),
        new DmParams(26262626444428),
        new DmParams(16481624494928),
        new DmParams(32321616626236),
        new DmParams(36361818868642),
        new DmParams(4040202011411448),
        new DmParams(4444222214414456),
        new DmParams(4848242417417468),
        new DmParams(5252262620410242),
        new DmParams(6464161628014056),
        new DmParams(727218183689236),
        new DmParams(8080202045611448),
        new DmParams(8888222257614456),
        new DmParams(9696242469617468),
        new DmParams(104104262681613656),
        new DmParams(1201202020105017568),
        new DmParams(1321322222130416362),
        new DmParams(1441442424155815662)};

    private static final String x12 = "\r*> 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private int extOut;
    private short[] place;
    private byte[] image;
    private int height;
    private int width;
    private int ws;
    private int options;

    /**
     * Creates an instance of this class.
     */
    public BarcodeDatamatrix() {
    }

    private void setBit(int x, int y, int xByte) {
        image[y * xByte + x / 8|= (byte)(128 >> (x & 7));
    }

    private void draw(byte[] data, int dataSize, DmParams dm) {
        int i, j, p, x, y, xs, ys, z;
        int xByte = (dm.width + ws * 78;
        Arrays.fill(image, (byte)0);
        //alignment patterns
        //dotted horizontal line
        for (i = ws; i < dm.height + ws; i += dm.heightSection) {
            for (j = ws; j < dm.width + ws; j += 2) {
                setBit(j, i, xByte);
            }
        }
        //solid horizontal line
        for (i = dm.heightSection - + ws; i < dm.height + ws; i += dm.heightSection) {
            for (j = ws; j < dm.width + ws; ++j) {
                setBit(j, i, xByte);
            }
        }
        //solid vertical line
        for (i = ws; i < dm.width + ws; i += dm.widthSection) {
            for (j = ws; j < dm.height + ws; ++j) {
                setBit(i, j, xByte);
            }
        }
        //dotted vertical line
        for (i = dm.widthSection - + ws; i < dm.width + ws; i += dm.widthSection) {
            for (j = + ws; j < dm.height + ws; j += 2) {
                setBit(i, j, xByte);
            }
        }
        p = 0;
        for (ys = 0; ys < dm.height; ys += dm.heightSection) {
            for (y = 1; y < dm.heightSection - 1; ++y) {
                for (xs = 0; xs < dm.width; xs += dm.widthSection) {
                    for (x = 1; x < dm.widthSection - 1; ++x) {
                        z = place[p++];
                        if (z == || z > && (data[z/8-10xff 128 >> z%8!= 0)
                            setBit(x + xs + ws, y + ys + ws, xByte);
                    }
                }
            }
        }
    }

    private static void makePadding(byte[] data, int position, int count) {
        //already in ascii mode
        if (count <= 0)
            return;
        data[position++(byte)129;
        while (--count > 0) {
            int t = 129 (position + 1149 253 1;
            if (t > 254)
                t -= 254;
            data[position++(byte)t;
        }
    }

    private static boolean isDigit(int c) {
        return c >= '0' && c <= '9';
    }

    private static int asciiEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength) {
        int ptrIn, ptrOut, c;
        ptrIn = textOffset;
        ptrOut = dataOffset;
        textLength += textOffset;
        dataLength += dataOffset;
        while (ptrIn < textLength) {
            if (ptrOut >= dataLength)
                return -1;
            c = text[ptrIn++0xff;
            if (isDigit(c&& ptrIn < textLength && isDigit(text[ptrIn0xff)) {
                data[ptrOut++(byte)((c - '0'10 (text[ptrIn++0xff'0' 130);
            }
            else if (c > 127) {
                if (ptrOut + >= dataLength)
                    return -1;
                data[ptrOut++(byte)235;
                data[ptrOut++(byte)(c - 128 1);
            }
            else {
                data[ptrOut++(byte)(c + 1);
            }
        }
        return ptrOut - dataOffset;
    }

    private static int b256Encodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength) {
        int k, j, prn, tv, c;
        if (textLength == 0)
            return 0;
        if (textLength < 250 && textLength + > dataLength)
            return -1;
        if (textLength >= 250 && textLength + > dataLength)
            return -1;
        data[dataOffset(byte)231;
        if (textLength < 250) {
            data[dataOffset + 1(byte)textLength;
            k = 2;
        }
        else {
            data[dataOffset + 1(byte)(textLength / 250 249);
            data[dataOffset + 2(byte)(textLength % 250);
            k = 3;
        }
        System.arraycopy(text, textOffset, data, k + dataOffset, textLength);
        k += textLength + dataOffset;
        for (j = dataOffset + 1; j < k; ++j) {
            c = data[j0xff;
            prn = 149 (j + 1255 1;
            tv = c + prn;
            if (tv > 255)
                tv -= 256;
            data[j(byte)tv;

        }
        return k - dataOffset;
    }

    private static int X12Encodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength) {
        int ptrIn, ptrOut, count, k, n, ci;
        byte c;
        if (textLength == 0)
            return 0;
        ptrIn = 0;
        ptrOut = 0;
        byte[] x = new byte[textLength];
        count = 0;
        for (; ptrIn < textLength; ++ptrIn) {
            int i = x12.indexOf((char)text[ptrIn + textOffset]);
            if (i >= 0) {
                x[ptrIn(byte)i;
                ++count;
            }
            else {
                x[ptrIn100;
                if (count >= 6)
                    count -= count / 3;
                for (k = 0; k < count; ++k)
                    x[ptrIn - k - 1100;
                count = 0;
            }
        }
        if (count >= 6)
            count -= count / 3;
        for (k = 0; k < count; ++k)
            x[ptrIn - k - 1100;
        ptrIn = 0;
        c = 0;
        for (; ptrIn < textLength; ++ptrIn) {
            c = x[ptrIn];
            if (ptrOut >= dataLength)
                break;
            if (c < 40) {
                if (ptrIn == || ptrIn > && x[ptrIn - 140)
                    data[dataOffset + ptrOut++(byte)238;
                if (ptrOut + > dataLength)
                    break;
                n = 1600 * x[ptrIn40 * x[ptrIn + 1+ x[ptrIn + 21;
                data[dataOffset + ptrOut++(byte)(n / 256);
                data[dataOffset + ptrOut++(byte)n;
                ptrIn += 2;
            }
            else {
                if (ptrIn > && x[ptrIn - 140)
                    data[dataOffset + ptrOut++(byte)254;
                ci = text[ptrIn + textOffset0xff;
                if (ci > 127) {
                    data[dataOffset + ptrOut++(byte)235;
                    ci -= 128;
                }
                if (ptrOut >= dataLength)
                    break;
                data[dataOffset + ptrOut++(byte)(ci + 1);
            }
        }
        c = 100;
        if (textLength > 0)
            c = x[textLength - 1];
        if (ptrIn != textLength || c < 40 && ptrOut >= dataLength)
            return -1;
        if (c < 40)
            data[dataOffset + ptrOut++(byte)254;
        return ptrOut;
    }

    private static int EdifactEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength) {
        int ptrIn, ptrOut, edi, pedi, c;
        if (textLength == 0)
            return 0;
        ptrIn = 0;
        ptrOut = 0;
        edi = 0;
        pedi = 18;
        boolean ascii = true;
        for (; ptrIn < textLength; ++ptrIn) {
            c = text[ptrIn + textOffset0xff;
            if (((c & 0xe0== 0x40 || (c & 0xe0== 0x20&& c != '_') {
                if (ascii) {
                    if (ptrOut + > dataLength)
                        break;
                    data[dataOffset + ptrOut++(byte)240;
                    ascii = false;
                }
                c &= 0x3f;
                edi |= c << pedi;
                if (pedi == 0) {
                    if (ptrOut + > dataLength)
                        break;
                    data[dataOffset + ptrOut++(byte)(edi >> 16);
                    data[dataOffset + ptrOut++(byte)(edi >> 8);
                    data[dataOffset + ptrOut++(byte)edi;
                    edi = 0;
                    pedi = 18;
                }
                else
                    pedi -= 6;
            }
            else {
                if (!ascii) {
                    edi |= ('_' 0x3f<< pedi;
                    if (ptrOut + - pedi / > dataLength)
                        break;
                    data[dataOffset + ptrOut++(byte)(edi >> 16);
                    if (pedi <= 12)
                        data[dataOffset + ptrOut++(byte)(edi >> 8);
                    if (pedi <= 6)
                        data[dataOffset + ptrOut++(byte)edi;
                    ascii = true;
                    pedi = 18;
                    edi = 0;
                }
                if (c > 127) {
                    if (ptrOut >= dataLength)
                        break;
                    data[dataOffset + ptrOut++(byte)235;
                    c -= 128;
                }
                if (ptrOut >= dataLength)
                    break;
                data[dataOffset + ptrOut++(byte)(c + 1);
            }
        }
        if (ptrIn != textLength)
            return -1;
        if (!ascii) {
            edi |= ('_' 0x3f<< pedi;
            if (ptrOut + - pedi / > dataLength)
                return -1;
            data[dataOffset + ptrOut++(byte)(edi >> 16);
            if (pedi <= 12)
                data[dataOffset + ptrOut++(byte)(edi >> 8);
            if (pedi <= 6)
                data[dataOffset + ptrOut++(byte)edi;
        }
        return ptrOut;
    }

    private static int C40OrTextEncodation(byte[] text, int textOffset, int textLength, byte[] data, int dataOffset, int dataLength, boolean c40) {
        int ptrIn, ptrOut, encPtr, last0, last1, i, a, c;
        String basic, shift2, shift3;
        if (textLength == 0)
            return 0;
        ptrIn = 0;
        ptrOut = 0;
        if (c40)
            data[dataOffset + ptrOut++(byte)230;
        else
            data[dataOffset + ptrOut++(byte)239;
        shift2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_";
        if (c40) {
            basic = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            shift3 = "`abcdefghijklmnopqrstuvwxyz{|}~\177";
        }
        else {
            basic = " 0123456789abcdefghijklmnopqrstuvwxyz";
            shift3 = "`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\177";
        }
        int[] enc = new int[textLength * 10];
        encPtr = 0;
        last0 = 0;
        last1 = 0;
        while (ptrIn < textLength) {
            if (encPtr % == 0) {
                last0 = ptrIn;
                last1 = encPtr;
            }
            c = text[textOffset + ptrIn++0xff;
            if (c > 127) {
                c -= 128;
                enc[encPtr++1;
                enc[encPtr++30;
            }
            int idx = basic.indexOf((char)c);
            if (idx >= 0) {
                enc[encPtr++= idx + 3;
            }
            else if (c < 32) {
                enc[encPtr++0;
                enc[encPtr++= c;
            }
            else if ((idx = shift2.indexOf((char)c)) >= 0) {
                enc[encPtr++1;
                enc[encPtr++= idx;
            }
            else if ((idx = shift3.indexOf((char)c)) >= 0) {
                enc[encPtr++2;
                enc[encPtr++= idx;
            }
        }
        if (encPtr % != 0) {
            ptrIn = last0;
            encPtr = last1;
        }
        if (encPtr / > dataLength - 2) {
            return -1;
        }
        i = 0;
        for (; i < encPtr; i += 3) {
            a = 1600 * enc[i40 * enc[i + 1+ enc[i + 21;
            data[dataOffset + ptrOut++(byte)(a / 256);
            data[dataOffset + ptrOut++(byte)a;
        }
        data[ptrOut++(byte)254;
        i = asciiEncodation(text, ptrIn, textLength - ptrIn, data, ptrOut, dataLength - ptrOut);
        if (i < 0)
            return i;
        return ptrOut + i;
    }

    private static int getEncodation(byte[] text, int textOffset, int textSize, byte[] data, int dataOffset, int dataSize, int options, boolean firstMatch) {
        int e, j, k;
        int[] e1 = new int[6];
        if (dataSize < 0)
            return -1;
        e = -1;
        options &= 7;
        if (options == 0) {
            e1[0= asciiEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
            if (firstMatch && e1[0>= 0)
                return e1[0];
            e1[1= C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false);
            if (firstMatch && e1[1>= 0)
                return e1[1];
            e1[2= C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true);
            if (firstMatch && e1[2>= 0)
                return e1[2];
            e1[3= b256Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
            if (firstMatch && e1[3>= 0)
                return e1[3];
            e1[4= X12Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
            if (firstMatch && e1[4>= 0)
                return e1[4];
            e1[5= EdifactEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
            if (firstMatch && e1[5>= 0)
                return e1[5];
            if (e1[0&& e1[1&& e1[2&& e1[3&& e1[4&& e1[50) {
                return -1;
            }
            j = 0;
            e = 99999;
            for (k = 0; k < 6; ++k) {
                if (e1[k>= && e1[k< e) {
                    e = e1[k];
                    j = k;
                }
            }
            if (j == 0)
                e = asciiEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
            else if (j == 1)
                e = C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false);
            else if (j == 2)
                e = C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true);
            else if (j == 3)
                e = b256Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
            else if (j == 4)
                e = X12Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
            return e;
        }
        switch (options) {
        case DM_ASCII:
            return asciiEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
        case DM_C40:
            return C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, true);
        case DM_TEXT:
            return C40OrTextEncodation(text, textOffset, textSize, data, dataOffset, dataSize, false);
        case DM_B256:
            return b256Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
        case DM_X21:
            return X12Encodation(text, textOffset, textSize, data, dataOffset, dataSize);
        case DM_EDIFACT:
            return EdifactEncodation(text, textOffset, textSize, data, dataOffset, dataSize);
        case DM_RAW:
            if (textSize > dataSize)
                return -1;
            System.arraycopy(text, textOffset, data, dataOffset, textSize);
            return textSize;
        }
        return -1;
    }

    private static int getNumber(byte[] text, int ptrIn, int n) {
        int v, j, c;
        v = 0;
        for (j = 0; j < n; ++j) {
            c = text[ptrIn++&0xff;
            if (c < '0' || c > '9')
                return -1;
            v = v * 10 + c - '0';
        }
        return v;
    }

    private int processExtensions(byte[] text, int textOffset, int textSize, byte[] data) {
        int order, ptrIn, ptrOut, eci, fn, ft, fi, c;
        if ((options & DM_EXTENSION== 0)
            return 0;
        order = 0;
        ptrIn = 0;
        ptrOut = 0;
        while (ptrIn < textSize) {
            if (order > 20)
                return -1;
            c = text[textOffset + ptrIn++&0xff;
            ++order;
            switch (c) {
            case '.':
                extOut = ptrIn;
                return ptrOut;
            case 'e':
                if (ptrIn + > textSize)
                    return -1;
                eci = getNumber(text, textOffset + ptrIn, 6);
                if (eci < 0)
                    return -1;
                ptrIn += 6;
                data[ptrOut++(byte)241;
                if (eci < 127)
                    data[ptrOut++(byte)(eci + 1);
                else if (eci < 16383) {
                    data[ptrOut++(byte)((eci - 127254 128);
                    data[ptrOut++(byte)((eci - 127254 1);
                }
                else {
                    data[ptrOut++(byte)((eci - 1638364516 192);
                    data[ptrOut++(byte)((eci - 16383254 254 1);
                    data[ptrOut++(byte)((eci - 16383254 1);
                }
                break;
            case 's':
                if (order != 1)
                    return -1;
                if (ptrIn + > textSize)
                    return -1;
                fn = getNumber(text, textOffset + ptrIn, 2);
                if (fn <= || fn > 16)
                    return -1;
                ptrIn += 2;
                ft = getNumber(text, textOffset + ptrIn, 2);
                if (ft <= || ft > 16)
                    return -1;
                ptrIn += 2;
                fi = getNumber(text, textOffset + ptrIn, 5);
                if (fi < || fn >= 64516)
                    return -1;
                ptrIn += 5;
                data[ptrOut++(byte)233;
                data[ptrOut++(byte)(fn - << 17 - ft);
                data[ptrOut++(byte)(fi / 254 1);
                data[ptrOut++(byte)(fi % 254 1);
                break;
            case 'p':
                if (order != 1)
                    return -1;
                data[ptrOut++(byte)234;
                break;
            case 'm':
                if (order != 1)
                    return -1;
                if (ptrIn + > textSize)
                    return -1;
                c = text[textOffset + ptrIn++&0xff;
                if (c != '5' && c != '5')
                    return -1;
                data[ptrOut++(byte)234;
                data[ptrOut++(byte)(c == '5' 236 237);
                break;
            case 'f':
                if (order != && (order != || text[textOffset!= 's' && text[textOffset!= 'm'))
                    return -1;
                data[ptrOut++(byte)232;
            }
        }
        return -1;
    }

    /**
     * Creates a barcode. The <CODE>String</CODE> is interpreted with the ISO-8859-1 encoding
     @param text the text
     @return the status of the generation. It can be one of this values:
     <p>
     <CODE>DM_NO_ERROR</CODE> - no error.<br>
     <CODE>DM_ERROR_TEXT_TOO_BIG</CODE> - the text is too big for the symbology capabilities.<br>
     <CODE>DM_ERROR_INVALID_SQUARE</CODE> - the dimensions given for the symbol are illegal.<br>
     <CODE>DM_ERROR_EXTENSION</CODE> - an error was while parsing an extension.
     @throws java.io.UnsupportedEncodingException on error
     */
    public int generate(String textthrows UnsupportedEncodingException {
        byte[] t = text.getBytes("iso-8859-1");
        return generate(t, 0, t.length);
    }

    /**
     * Creates a barcode.
     @param text the text
     @param textOffset the offset to the start of the text
     @param textSize the text size
     @return the status of the generation. It can be one of this values:
     <p>
     <CODE>DM_NO_ERROR</CODE> - no error.<br>
     <CODE>DM_ERROR_TEXT_TOO_BIG</CODE> - the text is too big for the symbology capabilities.<br>
     <CODE>DM_ERROR_INVALID_SQUARE</CODE> - the dimensions given for the symbol are illegal.<br>
     <CODE>DM_ERROR_EXTENSION</CODE> - an error was while parsing an extension.
     */
    public int generate(byte[] text, int textOffset, int textSize) {
        int extCount, e, k, full;
        DmParams dm, last;
        byte[] data = new byte[2500];
        extOut = 0;
        extCount = processExtensions(text, textOffset, textSize, data);
        if (extCount < 0) {
            return DM_ERROR_EXTENSION;
        }
        e = -1;
        if (height == || width == 0) {
            last = dmSizes[dmSizes.length - 1];
            e = getEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, last.dataSize - extCount, options, false);
            if (e < 0) {
                return DM_ERROR_TEXT_TOO_BIG;
            }
            e += extCount;
            for (k = 0; k < dmSizes.length; ++k) {
                if (dmSizes[k].dataSize >= e)
                    break;
            }
            dm = dmSizes[k];
            height = dm.height;
            width = dm.width;
        }
        else {
            for (k = 0; k < dmSizes.length; ++k) {
                if (height == dmSizes[k].height && width == dmSizes[k].width)
                    break;
            }
            if (k == dmSizes.length) {
                return DM_ERROR_INVALID_SQUARE;
            }
            dm = dmSizes[k];
            e = getEncodation(text, textOffset + extOut, textSize - extOut, data, extCount, dm.dataSize - extCount, options, true);
            if (e < 0) {
                return DM_ERROR_TEXT_TOO_BIG;
            }
            e += extCount;
        }
        if ((options & DM_TEST!= 0) {
            return DM_NO_ERROR;
        }
        image = new byte[(dm.width + * ws + 7(dm.height + * ws)];
        makePadding(data, e, dm.dataSize - e);
        place = Placement.doPlacement(dm.height - dm.height / dm.heightSection * 2, dm.width - dm.width / dm.widthSection * 2);
        full = dm.dataSize + (dm.dataSize + 2/ dm.dataBlock * dm.errorBlock;
        ReedSolomon.generateECC(data, dm.dataSize, dm.dataBlock, dm.errorBlock);
        draw(data, full, dm);
        return DM_NO_ERROR;
    }

    /** Gets an <CODE>Image</CODE> with the barcode. A successful call to the method <CODE>generate()</CODE>
     * before calling this method is required.
     @return the barcode <CODE>Image</CODE>
     @throws BadElementException on error
     */
    public Image createImage() throws BadElementException {
        if (image == null)
            return null;
        byte g4[] = CCITTG4Encoder.compress(image, width + * ws, height + * ws);
        return Image.getInstance(width + * ws, height + * ws, false, Image.CCITTG4, 0, g4, null);
    }

    /**
     * Creates a <CODE>java.awt.Image</CODE>. A successful call to the method <CODE>generate()</CODE>
     * before calling this method is required.
     @param foreground the color of the bars
     @param background the color of the background
     @return the image
     */
    public java.awt.Image createAwtImage(java.awt.Color foreground, java.awt.Color background) {
        if (image == null)
            return null;
        int f = foreground.getRGB();
        int g = background.getRGB();
        Canvas canvas = new Canvas();

        int w = width + * ws;
        int h = height + * ws;
        int pix[] new int[w * h];
        int stride = (w + 78;
        int ptr = 0;
        for (int k = 0; k < h; ++k) {
            int p = k * stride;
            for (int j = 0; j < w; ++j) {
                int b = image[p + j / 80xff;
                b <<= j % 8;
                pix[ptr++(b & 0x80== ? g : f;
            }
        }
        java.awt.Image img = canvas.createImage(new MemoryImageSource(w, h, pix, 0, w));
        return img;
    }

    private static class DmParams {
        DmParams(int height, int width, int heightSection, int widthSection, int dataSize, int dataBlock, int errorBlock) {
            this.height = height;
            this.width = width;
            this.heightSection = heightSection;
            this.widthSection = widthSection;
            this.dataSize = dataSize;
            this.dataBlock = dataBlock;
            this.errorBlock = errorBlock;
        }

        int height;
        int width;
        int heightSection;
        int widthSection;
        int dataSize;
        int dataBlock;
        int errorBlock;
    };

    /**
     * Gets the generated image. The image is represented as a stream of bytes, each byte representing
     * 8 pixels, 0 for white and 1 for black, with the high-order bit of each byte first. Each row
     * is aligned at byte boundaries. The dimensions of the image are defined by height and width
     * plus 2 * ws.
     @return the generated image
     */
    public byte[] getImage() {
        return image;
    }

    /**
     * Gets the height of the barcode. Will contain the real height used after a successful call
     * to <CODE>generate()</CODE>. This height doesn't include the whitespace border, if any.
     @return the height of the barcode
     */
    public int getHeight() {
        return height;
    }

    /**
     * Sets the height of the barcode. If the height is zero it will be calculated. This height doesn't include the whitespace border, if any.
     <p>
     * The allowed dimensions are (height, width):<p>
     * 10, 10<br>
     * 12, 12<br>
     * 8, 18<br>
     * 14, 14<br>
     * 8, 32<br>
     * 16, 16<br>
     * 12, 26<br>
     * 18, 18<br>
     * 20, 20<br>
     * 12, 36<br>
     * 22, 22<br>
     * 16, 36<br>
     * 24, 24<br>
     * 26, 26<br>
     * 16, 48<br>
     * 32, 32<br>
     * 36, 36<br>
     * 40, 40<br>
     * 44, 44<br>
     * 48, 48<br>
     * 52, 52<br>
     * 64, 64<br>
     * 72, 72<br>
     * 80, 80<br>
     * 88, 88<br>
     * 96, 96<br>
     * 104, 104<br>
     * 120, 120<br>
     * 132, 132<br>
     * 144, 144<br>
     @param height the height of the barcode
     */
    public void setHeight(int height) {
        this.height = height;
    }

    /**
     * Gets the width of the barcode. Will contain the real width used after a successful call
     * to <CODE>generate()</CODE>. This width doesn't include the whitespace border, if any.
     @return the width of the barcode
     */
    public int getWidth() {
        return width;
    }

    /**
     * Sets the width of the barcode. If the width is zero it will be calculated. This width doesn't include the whitespace border, if any.
     <p>
     * The allowed dimensions are (height, width):<p>
     * 10, 10<br>
     * 12, 12<br>
     * 8, 18<br>
     * 14, 14<br>
     * 8, 32<br>
     * 16, 16<br>
     * 12, 26<br>
     * 18, 18<br>
     * 20, 20<br>
     * 12, 36<br>
     * 22, 22<br>
     * 16, 36<br>
     * 24, 24<br>
     * 26, 26<br>
     * 16, 48<br>
     * 32, 32<br>
     * 36, 36<br>
     * 40, 40<br>
     * 44, 44<br>
     * 48, 48<br>
     * 52, 52<br>
     * 64, 64<br>
     * 72, 72<br>
     * 80, 80<br>
     * 88, 88<br>
     * 96, 96<br>
     * 104, 104<br>
     * 120, 120<br>
     * 132, 132<br>
     * 144, 144<br>
     @param width the width of the barcode
     */
    public void setWidth(int width) {
        this.width = width;
    }

    /**
     * Gets the whitespace border around the barcode.
     @return the whitespace border around the barcode
     */
    public int getWs() {
        return ws;
    }

    /**
     * Sets the whitespace border around the barcode.
     @param ws the whitespace border around the barcode
     */
    public void setWs(int ws) {
        this.ws = ws;
    }

    /**
     * Gets the barcode options.
     @return the barcode options
     */
    public int getOptions() {
        return options;
    }

    /**
     * Sets the options for the barcode generation. The options can be:<p>
     * One of:<br>
     <CODE>DM_AUTO</CODE> - the best encodation will be used<br>
     <CODE>DM_ASCII</CODE> - ASCII encodation<br>
     <CODE>DM_C40</CODE> - C40 encodation<br>
     <CODE>DM_TEXT</CODE> - TEXT encodation<br>
     <CODE>DM_B256</CODE> - binary encodation<br>
     <CODE>DM_X21</CODE> - X21 encodation<br>
     <CODE>DM_EDIFACT</CODE> - EDIFACT encodation<br>
     <CODE>DM_RAW</CODE> - no encodation. The bytes provided are already encoded and will be added directly to the barcode, using padding if needed. It assumes that the encodation state is left at ASCII after the last byte.<br>
     <p>
     * One of:<br>
     <CODE>DM_EXTENSION</CODE> - allows extensions to be embedded at the start of the text:<p>
     * exxxxxx - ECI number xxxxxx<br>
     * m5 - macro 5<br>
     * m6 - macro 6<br>
     * f - FNC1<br>
     * saabbccccc - Structured Append, aa symbol position (1-16), bb total number of symbols (2-16), ccccc file identification (0-64515)<br>
     * p - Reader programming<br>
     * . - extension terminator<p>
     * Example for a structured append, symbol 2 of 6, with FNC1 and ECI 000005. The actual text is "Hello".<p>
     * s020600075fe000005.Hello<p>
     * One of:<br>
     <CODE>DM_TEST</CODE> - doesn't generate the image but returns all the other information.
     @param options the barcode options
     */
    public void setOptions(int options) {
        this.options = options;
    }

    static class Placement {
        private int nrow;
        private int ncol;
        private short[] array;
        private static final Hashtable<Integer, short[]> cache = new Hashtable<Integer, short[]>();

        private Placement() {
        }

        static short[] doPlacement(int nrow, int ncol) {
            Integer key = Integer.valueOf(nrow * 1000 + ncol);
            short[] pc = cache.get(key);
            if (pc != null)
                return pc;
            Placement p = new Placement();
            p.nrow = nrow;
            p.ncol = ncol;
            p.array = new short[nrow * ncol];
            p.ecc200();
            cache.put(key, p.array);
            return p.array;
        }

        /* "module" places "chr+bit" with appropriate wrapping within array[] */
        private void module(int row, int col, int chr, int bit) {
            if (row < 0) { row += nrow; col += (nrow+4)%8}
            if (col < 0) { col += ncol; row += (ncol+4)%8}
            array[row*ncol+col(short)(8*chr + bit);
        }
        /* "utah" places the 8 bits of a utah-shaped symbol character in ECC200 */
        private void utah(int row, int col, int chr) {
            module(row-2,col-2,chr,0);
            module(row-2,col-1,chr,1);
            module(row-1,col-2,chr,2);
            module(row-1,col-1,chr,3);
            module(row-1,col,chr,4);
            module(row,col-2,chr,5);
            module(row,col-1,chr,6);
            module(row,col,chr,7);
        }
        /* "cornerN" places 8 bits of the four special corner cases in ECC200 */
        private void corner1(int chr) {
            module(nrow-1,0,chr,0);
            module(nrow-1,1,chr,1);
            module(nrow-1,2,chr,2);
            module(0,ncol-2,chr,3);
            module(0,ncol-1,chr,4);
            module(1,ncol-1,chr,5);
            module(2,ncol-1,chr,6);
            module(3,ncol-1,chr,7);
        }
        private void corner2(int chr){
            module(nrow-3,0,chr,0);
            module(nrow-2,0,chr,1);
            module(nrow-1,0,chr,2);
            module(0,ncol-4,chr,3);
            module(0,ncol-3,chr,4);
            module(0,ncol-2,chr,5);
            module(0,ncol-1,chr,6);
            module(1,ncol-1,chr,7);
        }
        private void corner3(int chr){
            module(nrow-3,0,chr,0);
            module(nrow-2,0,chr,1);
            module(nrow-1,0,chr,2);
            module(0,ncol-2,chr,3);
            module(0,ncol-1,chr,4);
            module(1,ncol-1,chr,5);
            module(2,ncol-1,chr,6);
            module(3,ncol-1,chr,7);
        }
        private void corner4(int chr){
            module(nrow-1,0,chr,0);
            module(nrow-1,ncol-1,chr,1);
            module(0,ncol-3,chr,2);
            module(0,ncol-2,chr,3);
            module(0,ncol-1,chr,4);
            module(1,ncol-3,chr,5);
            module(1,ncol-2,chr,6);
            module(1,ncol-1,chr,7);
        }
        /* "ECC200" fills an nrow x ncol array with appropriate values for ECC200 */
        private void ecc200(){
            int row, col, chr;
            /* First, fill the array[] with invalid entries */
            Arrays.fill(array, (short)0);
            /* Starting in the correct location for character #1, bit 8,... */
            chr = 1; row = 4; col = 0;
            do {
                /* repeatedly first check for one of the special corner cases, then... */
                if (row == nrow && col == 0corner1(chr++);
                if (row == nrow-&& col == && ncol%!= 0corner2(chr++);
                if (row == nrow-&& col == && ncol%== 4corner3(chr++);
                if (row == nrow+&& col == && ncol%== 0corner4(chr++);
                /* sweep upward diagonally, inserting successive characters,... */
                do {
                    if (row < nrow && col >= && array[row*ncol+col== 0)
                        utah(row,col,chr++);
                    row -= 2; col += 2;
                while (row >= && col < ncol);
                row += 1; col += 3;
                /* & then sweep downward diagonally, inserting successive characters,... */

                do {
                    if (row >= && col < ncol && array[row*ncol+col== 0)
                        utah(row,col,chr++);
                    row += 2; col -= 2;
                while (row < nrow && col >= 0);
                row += 3; col += 1;
                /* ... until the entire array is scanned */
            while (row < nrow || col < ncol);
            /* Lastly, if the lower righthand corner is untouched, fill in fixed pattern */
            if (array[nrow*ncol-1== 0) {
                array[nrow*ncol-1= array[nrow*ncol-ncol-21;
            }
        }
    }

    static class ReedSolomon {

        private static final int log[] {
               0255,   1240,   2225241,  53,   3,  38226133242,  43,  54210,
               4195,  39114227106134,  28243140,  44,  23,  55118211234,
               5219196,  96,  40222115103228,  78107125135,   8,  29162,
             244186141180,  45,  99,  24,  49,  56,  13119153212199235,  91,
               6,  76220217197,  11,  97184,  41,  36223253116138104193,
             229,  86,  79171108165126145136,  34,   9,  74,  30,  32163,  84,
             245173187204142,  81181190,  46,  88100159,  25231,  50207,
              57147,  14,  67120128154248213167200,  63236110,  92176,
               7161,  77124221102218,  95198,  90,  12152,  98,  48185179,
              42209,  37132224,  52254239117233139,  22105,  27194113,
             230206,  87158,  80189172203109175166,  62127247146,  66,
             137192,  35252,  10183,  75216,  31,  83,  33,  73164144,  85170,
             246,  65174,  61188202205157143169,  82,  72182215191251,
              47178,  89151101,  94160123,  26112232,  21,  51238208131,
              58,  69148,  18,  15,  16,  68,  17121149129,  19155,  59249,  70,
             214250168,  71201156,  64,  60237130111,  20,  93122177150
        };

        private static final int alog[] {
               1,   2,   4,   8,  16,  32,  64128,  45,  90180,  69138,  57114228,
             229231227235251219155,  27,  54108216157,  23,  46,  92184,
              93186,  89178,  73146,   9,  18,  36,  72144,  13,  26,  52104208,
             141,  55110220149,   7,  14,  28,  56112224237247195171123,
             246193175115230225239243203187,  91182,  65130,  41,  82,
             164101202185,  95190,  81162105210137,  63126252213135,
              35,  70140,  53106212133,  39,  78156,  21,  42,  84168125250,
             217159,  19,  38,  76152,  29,  58116232253215131,  43,  86172,
             117234249223147,  11,  22,  44,  88176,  77154,  25,  50100200,
             189,  87174113226233255211139,  59118236245199163107,
             214129,  47,  94188,  85170121242201191,  83166,  97194169,
             127254209143,  51102204181,  71142,  49,  98196165103206,
             177,  79158,  17,  34,  68136,  61122244197167,  99198161111,
             222145,  15,  30,  60120240205183,  67134,  33,  66132,  37,  74,
             148,   5,  10,  20,  40,  80160109218153,  31,  62124248221151,
               3,   6,  12,  24,  48,  96192173119238241207179,  75150,   1
        };

        private static final int poly5[] {
             228,  48,  15111,  62
        };

        private static final int poly7[] {
              23,  68144134240,  92254
        };

        private static final int poly10[] {
              28,  24185166223248116255110,  61
        };

        private static final int poly11[] {
             175138205,  12194168,  39245,  60,  97120
        };

        private static final int poly12[] {
              41153158,  91,  61,  42142213,  97178100242
        };

        private static final int poly14[] {
             156,  97192252,  95,   9157119138,  45,  18186,  83185
        };

        private static final int poly18[] {
              83195100,  39188,  75,  66,  61241213109129,  94254225,  48,
              90188
        };

        private static final int poly20[] {
              15195244,   9233,  71168,   2188160153145253,  79108,  82,
              27174186172
        };

        private static final int poly24[] {
              52190,  88205109,  39176,  21155197251223155,  21,   5172,
             254124,  12181184,  96,  50193
        };

        private static final int poly28[] {
             211231,  43,  97,  71,  96103174,  37151170,  53,  75,  34249121,
              17138110213141136120151233168,  93255
        };

        private static final int poly36[] {
             245127242218130250162181102120,  84179220251,  80182,
             229,  18,   2,   4,  68,  33101137,  95119115,  44175184,  59,  25,
             225,  98,  81112
        };

        private static final int poly42[] {
              77193137,  31,  19,  38,  22153247105122,   2245133242,   8,
             175,  95100,   9167105214111,  57121,  21,   1253,  57,  54101,
             248202,  69,  50150177226,   5,   9,   5
        };

        private static final int poly48[] {
             245132172223,  96,  32117,  22238133238231205188237,  87,
             191106,  16147118,  23,  37,  90170205131,  88120100,  66138,
             186240,  82,  44176,  87187147160175,  69213,  92253225,  19
        };

        private static final int poly56[] {
             175,   9223238,  12,  17220208100,  29175170230192215235,
             150159,  36223,  38200132,  54228146218234117203,  29232,
             144238,  22150201117,  62207164,  13137245127,  67247,  28,
             155,  43203107233,  53143,  46
        };

        private static final int poly62[] {
             242,  93169,  50144210,  39118202188201189143108196,  37,
             185112134230245,  63197190250106185221175,  64114,  71,
             161,  44147,   6,  27218,  51,  63,  87,  10,  40130188,  17163,  31,
             176170,   4107232,   7,  94166224124,  86,  47,  11204
        };

        private static final int poly68[] {
             220228173,  89251149159,  56,  89,  33147244154,  36,  73127,
             213136248180234197158177,  68122,  93213,  15160227236,
              66139153185202167179,  25220232,  96210231136223239,
             181241,  59,  52172,  25,  49232211189,  64,  54108153132,  63,
              96103,  82186
        };

        private static int[] getPoly(int nc) {
            switch (nc) {
            case 5:
                return poly5;
            case 7:
                return poly7;
            case 10:
                return poly10;
            case 11:
                return poly11;
            case 12:
                return poly12;
            case 14:
                return poly14;
            case 18:
                return poly18;
            case 20:
                return poly20;
            case 24:
                return poly24;
            case 28:
                return poly28;
            case 36:
                return poly36;
            case 42:
                return poly42;
            case 48:
                return poly48;
            case 56:
                return poly56;
            case 62:
                return poly62;
            case 68:
                return poly68;
            }
            return null;
        }

        private static void reedSolomonBlock(byte[] wd, int nd, byte[] ncout, int nc, int[] c) {
            int i, j, k;

            for (i=0; i<=nc; i++ncout[i0;
            for (i=0; i<nd; i++) {
                k = (ncout[0^ wd[i]) 0xff;
                for (j=0; j<nc; j++) {
                    ncout[j(byte)(ncout[j+1(k == (byte)alog[(log[k+ log[c[nc-j-1]]) 255]));
                }
            }
        }

        static void generateECC(byte[] wd, int nd, int datablock, int nc) {
            int blocks = (nd + 2/ datablock;
            int b;
            byte[] buf = new byte[256];
            byte[] ecc = new byte[256];
            int[] c = getPoly(nc);
            for (b = 0; b < blocks; b++)
            {
                int n, p = 0;
                for (n = b; n < nd; n += blocks)
                    buf[p++= wd[n];
                reedSolomonBlock(buf, p, ecc, nc, c);
                p = 0;
                for (n = b; n < nc * blocks; n += blocks)
                    wd[nd + n= ecc[p++];
            }
        }

    }
}