Barcode-Lib4J requires Java 9+

Java Class «TwoDCode»  –  Generate QR Code, DataMatrix and other

java.lang.Object
de.vwsoft.barcodelib4j.twod.TwoDCode
All Implemented Interfaces:
Cloneable

public class TwoDCode extends Object implements Cloneable
Main class of the package and a wrapper for the integrated ZXing classes.

The class provides methods and constants that facilitate the integration of 2D codes into an existing application. It accepts settings in a type-safe form and validates them, catching any errors beforehand. This reduces the number of possible exceptions that can be thrown during code generation and helps to locate and handle them in a more differentiated way.

Usage:

  1. Providing common settings such as code type (QR Code, DataMatrix, ...), the content, character set and quiet zone.
  2. Providing type-specific settings for the 2D code type you want to create.
  3. Check compatibility between the content and selected charset using canEncode().
  4. Call buildSymbol() to generate the drawable code symbol.
Example:
     // Step 1: Common settings
     TwoDCode tdc = new TwoDCode();
     tdc.setType(TwoDType.QRCODE);
     tdc.setContent("Some content");
     tdc.setCharset(null); // include no ECI
     tdc.setQuietZoneSize(TwoDCode.ALL_QUIET_ZONES.get(TwoDType.QRCODE));

     // Step 2: Type-specific settings
     tdc.setQRCodeVersion(TwoDCode.QRCODE_VERSION_AUTO);
     tdc.setQRCodeErrCorr(1);

     // Step 3 and 4: Generate drawable symbol
     TwoDSymbol symbol = null;
     if (tdc.canEncode()) {
       try {
         symbol = tdc.buildSymbol();
       } catch (Exception ex) {
         // Handle the Exception
       }
     }
 
When generating GS1 DataMatrix or GS1 QR Code, the GS1Validator class from the "oned" package can be used to perform advanced content validation. See the setContent method description for more information.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final Map<TwoDType,Integer>
    Map containing the minimum quiet zones for all supported 2D code types, according to their respective specifications, specified in modules.
    static final int
    Maximum Aztec error correction level in percent; value: 95.
    static final int
    Minimum Aztec error correction level in percent; value: 5.
    static final int
    Selects the smallest possible Aztec size capable of encoding the content.
    static final TwoDSize[]
    Array of all 4 Aztec compact sizes: 15x15, 19x19, 23x23, 27x27.
    static final TwoDSize[]
    Array of all 32 Aztec normal sizes, ranging from 19x19 to 151x151.
    static final int
    When selected automatically, the smallest size with no priority for the shape is chosen.
    static final int
    When selected automatically, the smallest size with a RECTANGLE shape is chosen.
    static final int
    When selected automatically, the smallest size with a SQUARE shape is chosen.
    static final int
    Selects the smallest possible DataMatrix size capable of encoding the content.
    static final int
    Largest size of DataMatrix (144x144) according to ECC200 specification; value: 30.
    static final int
    Smallest size of DataMatrix (10x10) according to ECC200 specification; value: 1.
    static final TwoDSize[]
    Array containing all 30 DataMatrix sizes, ranging from 10x10 to 144x144.
    static final int
    Maximum number of columns (code words) in a valid PDF417 symbol; value: 30.
    static final int
    Minimum number of columns (code words) in a valid PDF417 symbol; value: 1.
    static final int
    Highest PDF417 error correction level; value: 8.
    static final int
    Lowest PDF417 error correction level; value: 0.
    static final int
    Maximum number of rows in a valid PDF417 symbol; value: 90.
    static final int
    Minimum number of rows in a valid PDF417 symbol; value: 3.
    static final int
    Highest QR Code error correction level ("H"); value: 3.
    static final int
    Lowest QR Code error correction level ("L"); value: 0.
    static final TwoDSize[]
    Array of all QR Code sizes ranging from version 1 to 40, as defined in the specification.
    static final int
    Selects the smallest possible QR Code version capable of encoding the content.
    static final int
    Maximum (largest) version of QR Code (177x177) according to specification; value: 40.
    static final int
    Minimum (smallest) version of QR Code (21x21) according to specification; value: 1.
  • Constructor Summary

    Constructors
    Constructor
    Description
    Creates a new instance with default settings.
  • Method Summary

    Modifier and Type
    Method
    Description
    Generates a drawable 2D symbol based on the provided properties.
    boolean
    Checks if the specified charset can encode the given content.
    Returns a copy of this object.
    int
    Returns the error correction level of the Aztec.
    int
    Returns the size index of the Aztec symbol.
    Returns the character set used for encoding the content.
    Returns the content encoded in the 2D code.
    int
    Returns the shape of the DataMatrix symbol.
    int
    Returns the size of the DataMatrix symbol.
    int
    Returns the error correction level of the PDF417.
    Returns the size of the PDF417 symbol.
    int
    Returns the error correction level of the QR Code.
    int
    Returns the version of the QR Code.
    int
    Returns the size of the quiet zone around the 2D code.
    Returns the type of the 2D code.
    void
    setAztecErrCorr(int errorCorrectionLevel)
    Sets the error correction level for Aztec, specified in percent.
    void
    setAztecSize(int sizeIndex)
    Sets the size of the Aztec code symbol.
    void
    Specifies the character set used to encode the content in the 2D code.
    void
    setContent(String content)
    Sets the content to be encoded in the 2D code.
    void
    setDataMatrixShape(int shape)
    Sets the shape of the DataMatrix symbol.
    void
    setDataMatrixSize(int sizeIndex)
    Sets the size of the DataMatrix symbol.
    void
    setPDF417ErrCorr(int errorCorrectionLevel)
    Sets the error correction level for PDF417.
    void
    Sets the size of the PDF417 symbol.
    void
    setQRCodeErrCorr(int errorCorrectionLevel)
    Sets the error correction level for QR Code.
    void
    setQRCodeVersion(int version)
    Sets the version of the QR Code.
    void
    setQuietZoneSize(int sizeInModules)
    Sets the size of the quiet zone for the 2D code.
    void
    setType(TwoDType codeType)
    Sets the type of the 2D code.

    Methods inherited from class java.lang.Object

    equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • ALL_QUIET_ZONES

      public static final Map<TwoDType,Integer> ALL_QUIET_ZONES
      Map containing the minimum quiet zones for all supported 2D code types, according to their respective specifications, specified in modules.
    • QRCODE_VERSION_MIN

      public static final int QRCODE_VERSION_MIN
      Minimum (smallest) version of QR Code (21x21) according to specification; value: 1.
    • QRCODE_VERSION_MAX

      public static final int QRCODE_VERSION_MAX
      Maximum (largest) version of QR Code (177x177) according to specification; value: 40.
    • QRCODE_VERSION_AUTO

      public static final int QRCODE_VERSION_AUTO
      Selects the smallest possible QR Code version capable of encoding the content.
    • QRCODE_ERR_CORR_MIN

      public static final int QRCODE_ERR_CORR_MIN
      Lowest QR Code error correction level ("L"); value: 0.
    • QRCODE_ERR_CORR_MAX

      public static final int QRCODE_ERR_CORR_MAX
      Highest QR Code error correction level ("H"); value: 3.
    • QRCODE_SIZES

      public static final TwoDSize[] QRCODE_SIZES
      Array of all QR Code sizes ranging from version 1 to 40, as defined in the specification. All QR Code symbol shapes are square, hence width equals height.
    • DATAMATRIX_SIZE_MIN

      public static final int DATAMATRIX_SIZE_MIN
      Smallest size of DataMatrix (10x10) according to ECC200 specification; value: 1.
    • DATAMATRIX_SIZE_MAX

      public static final int DATAMATRIX_SIZE_MAX
      Largest size of DataMatrix (144x144) according to ECC200 specification; value: 30.
    • DATAMATRIX_SIZE_AUTO

      public static final int DATAMATRIX_SIZE_AUTO
      Selects the smallest possible DataMatrix size capable of encoding the content.
    • DATAMATRIX_SHAPE_AUTO

      public static final int DATAMATRIX_SHAPE_AUTO
      When selected automatically, the smallest size with no priority for the shape is chosen.
    • DATAMATRIX_SHAPE_SQUARE

      public static final int DATAMATRIX_SHAPE_SQUARE
      When selected automatically, the smallest size with a SQUARE shape is chosen.
    • DATAMATRIX_SHAPE_RECTANGLE

      public static final int DATAMATRIX_SHAPE_RECTANGLE
      When selected automatically, the smallest size with a RECTANGLE shape is chosen.
    • DATAMATRIX_SIZES

      public static final TwoDSize[] DATAMATRIX_SIZES
      Array containing all 30 DataMatrix sizes, ranging from 10x10 to 144x144. The sizes are sorted by width and height and include 24 square and 6 rectangular sizes.
    • PDF417_ROWS_MIN

      public static final int PDF417_ROWS_MIN
      Minimum number of rows in a valid PDF417 symbol; value: 3.
    • PDF417_ROWS_MAX

      public static final int PDF417_ROWS_MAX
      Maximum number of rows in a valid PDF417 symbol; value: 90.
    • PDF417_COLUMNS_MIN

      public static final int PDF417_COLUMNS_MIN
      Minimum number of columns (code words) in a valid PDF417 symbol; value: 1.
    • PDF417_COLUMNS_MAX

      public static final int PDF417_COLUMNS_MAX
      Maximum number of columns (code words) in a valid PDF417 symbol; value: 30.
    • PDF417_ERR_CORR_MIN

      public static final int PDF417_ERR_CORR_MIN
      Lowest PDF417 error correction level; value: 0.
    • PDF417_ERR_CORR_MAX

      public static final int PDF417_ERR_CORR_MAX
      Highest PDF417 error correction level; value: 8.
    • AZTEC_SIZE_AUTO

      public static final int AZTEC_SIZE_AUTO
      Selects the smallest possible Aztec size capable of encoding the content.
    • AZTEC_ERR_CORR_MIN

      public static final int AZTEC_ERR_CORR_MIN
      Minimum Aztec error correction level in percent; value: 5.
    • AZTEC_ERR_CORR_MAX

      public static final int AZTEC_ERR_CORR_MAX
      Maximum Aztec error correction level in percent; value: 95.
    • AZTEC_SIZES_COMPACT

      public static final TwoDSize[] AZTEC_SIZES_COMPACT
      Array of all 4 Aztec compact sizes: 15x15, 19x19, 23x23, 27x27. All Aztec symbol shapes are square, hence width equals height.
    • AZTEC_SIZES_NORMAL

      public static final TwoDSize[] AZTEC_SIZES_NORMAL
      Array of all 32 Aztec normal sizes, ranging from 19x19 to 151x151. All Aztec symbol shapes are square, hence width equals height.
  • Constructor Details

  • Method Details

    • setType

      public void setType(TwoDType codeType)
      Sets the type of the 2D code.
      Parameters:
      codeType - the type of the 2D code to set
      Throws:
      IllegalArgumentException - if the provided codeType is null
    • setContent

      public void setContent(String content)
      Sets the content to be encoded in the 2D code.

      GS1 QR Code + GS1 DataMatrix: For GS1 formatted data, ASCII 29 must be used as FNC1 separator character where necessary. Note that the content should NOT include the leading FNC1, which indicates the GS1 data structure. It is recommended to validate the content using the GS1Validator class before setting. Example:

          import de.vwsoft.barcodelib4j.oned.BarcodeException;
          import de.vwsoft.barcodelib4j.oned.GS1Validator;
      
          String gs1 = "(01)01234567890128(15)191231";
          String validated = null;
          try {
            validated = new GS1Validator(gs1, (char)29).getContent();
          } catch (BarcodeException ex) {
            // Validation failed
          }
      
          if (validated != null)
            // ... use this method to set the validated value
       
      Parameters:
      content - the content to be encoded
      Throws:
      IllegalArgumentException - if the provided content is null or empty
      See Also:
    • setCharset

      public void setCharset(Charset charset)
      Specifies the character set used to encode the content in the 2D code.

      If set to null (default), no character set information (ECI) is built into the code, and the default ISO 8859-1 character set is used. This is the default character set for all supported 2D types unless another character set is explicitly specified.

      GS1 QR Code + GS1 DataMatrix: For GS1 code types, specifying a character set is usually unnecessary since GS1 data typically consists only of ASCII characters, compatible with ISO 8859-1.

      Parameters:
      charset - the character set to be used for encoding the content, or null to indicate the default ISO 8859-1 charset with no ECI
    • setQuietZoneSize

      public void setQuietZoneSize(int sizeInModules)
      Sets the size of the quiet zone for the 2D code.

      The quiet zone is the blank space around the 2D code that helps prevent interference or misreading of the code by surrounding elements. The size of the quiet zone is specified in modules. A module is the smallest single element in a 2D code, typically representing a single dot within the code.

      Standard quiet zones for all supported 2D codes are available in the ALL_QUIET_ZONES array.

      Note: For QR Codes, the specification defines a minimum quiet zone size of 4 modules. Although this minimum value is often used, it is not strictly adhered to and can vary depending on the application or implementation.

      Parameters:
      sizeInModules - the size of the quiet zone in modules
      Throws:
      IllegalArgumentException - if the specified size is negative
    • setQRCodeVersion

      public void setQRCodeVersion(int version)
      Sets the version of the QR Code.

      The version determines the size and data capacity of the QR Code. Valid values range from 1 to 40 inclusive. A version of 1 means a 21x21 matrix and each subsequent version increases the matrix size by 4 modules. Version 40 represents a 177x177 matrix. Use QRCODE_VERSION_AUTO instead of a version number to automatically select the smallest version capable of encoding the content.

      Parameters:
      version - the version number of the QR Code (1 to 40) or QRCODE_VERSION_AUTO
      Throws:
      IllegalArgumentException - if the specified version is not within the valid range and does not match QRCODE_VERSION_AUTO
      See Also:
    • setQRCodeErrCorr

      public void setQRCodeErrCorr(int errorCorrectionLevel)
      Sets the error correction level for QR Code.

      The error correction level specifies the amount of redundant data added to the symbol to enable error recovery. QR Codes support four levels of error correction: L (Low - ~7%), M (Medium - ~15%), Q (Quartile - ~25%), and H (High - ~30%). The higher the error correction level, the more redundancy is added, resulting in a higher resistance to errors, but also in a larger symbol size.

      The error correction level can be set to any value between 0 and 3 inclusive: 0 for "L", 1 for "M" (default), 2 for "Q", and 3 for "H".

      Parameters:
      errorCorrectionLevel - the error correction level to set for QR Code in the range 0-3
      Throws:
      IllegalArgumentException - if the specified error correction level is outside the valid range
    • setDataMatrixSize

      public void setDataMatrixSize(int sizeIndex)
      Sets the size of the DataMatrix symbol.

      The size index [minus 1] represents the index of the DataMatrix symbol size in the DATAMATRIX_SIZES array. The value ranges from 1 to 30, inclusive, where 1 corresponds to the smallest size (10x10) and 30 corresponds to the largest size (144x144). Use DATAMATRIX_SIZE_AUTO instead of a size index to automatically select the smallest size capable of encoding the content.

      Note: The DataMatrix implementation allows the use of character sets other than ISO 8859-1 only when the size is set to DATAMATRIX_SIZE_AUTO.

      Parameters:
      sizeIndex - the index (1 to 30) specifying the size of the DataMatrix symbol or DATAMATRIX_SIZE_AUTO
      Throws:
      IllegalArgumentException - if the specified size index is not within the valid range and does not match DATAMATRIX_SIZE_AUTO
      See Also:
    • setDataMatrixShape

      public void setDataMatrixShape(int shape)
      Sets the shape of the DataMatrix symbol.

      Valid values are:

      Parameters:
      shape - the shape of the DataMatrix symbol
      Throws:
      IllegalArgumentException - if the provided shape is not one of the valid constants
    • setPDF417Size

      public void setPDF417Size(TwoDSize size)
      Sets the size of the PDF417 symbol.

      The PDF417 symbol size is specified in terms of the number of columns and rows. The number of columns can range from 1 to 30, and the number of rows can range from 3 to 90. If the width or height value is set to 0, the respective value is automatically selected based on the content to be encoded.

      Parameters:
      size - the size of the PDF417 symbol represented by a TwoDSize object
      Throws:
      IllegalArgumentException - if the provided size is null, or if the specified column or row have invalid values
    • setPDF417ErrCorr

      public void setPDF417ErrCorr(int errorCorrectionLevel)
      Sets the error correction level for PDF417.

      The parameter specifies the amount of redundant data added to the symbol to enable error recovery. The higher the error correction level, the more redundancy is added, resulting in a higher resistance to errors, but also in a larger symbol size. PDF417 supports error correction levels from 0 to 8.

      Parameters:
      errorCorrectionLevel - the error correction level to set for PDF417 in the range 0-8
      Throws:
      IllegalArgumentException - if the specified error correction level is outside the valid range
    • setAztecSize

      public void setAztecSize(int sizeIndex)
      Sets the size of the Aztec code symbol. The parameter can have the following values:
      • AZTEC_SIZE_AUTO indicates that the smallest possible size capable of encoding the content is selected automatically (default).
      • Negative numbers (-1, -2, -3, -4) represent compact Aztec codes. See: AZTEC_SIZES_COMPACT.
      • Positive numbers (1, 2, ... 32) represent normal (non-compact) Aztec codes. See: AZTEC_SIZES_NORMAL.
      Parameters:
      sizeIndex - the index specifying the size of the Aztec code or AZTEC_SIZE_AUTO
      Throws:
      IllegalArgumentException - if the specified size index is not within the valid ranges and does not match AZTEC_SIZE_AUTO
    • setAztecErrCorr

      public void setAztecErrCorr(int errorCorrectionLevel)
      Sets the error correction level for Aztec, specified in percent.

      The error correction level determines the amount of redundancy data added to the symbol for error detection and correction. Aztec symbols support error correction levels ranging from 5% to 95%. Higher error correction levels add more redundancy data, increasing the symbol's ability to withstand errors but also increasing its size.

      Parameters:
      errorCorrectionLevel - the error correction level for Aztec, specified in percent
      Throws:
      IllegalArgumentException - if the specified error correction level is outside the valid range
    • canEncode

      public boolean canEncode()
      Checks if the specified charset can encode the given content.

      If no charset is specified (i.e., null), ISO 8859-1 is checked as this is the default charset used by all supported 2D code implementations.

      For several reasons, it is recommended to call this method before building the 2D code symbol:

      • Some 2D code implementations (QR Code, Aztec) will generate the symbol even if the content cannot be encoded correctly with the specified charset, resulting in a 2D code that no longer contains the original information.
      • In contrast, other implementations (DataMatrix, PDF417) will properly throw an exception if the content cannot be encoded. Such exceptions can be avoided by having this method perform the check in advance.
      Returns:
      true if the specified charset can encode the content, false otherwise.
    • buildSymbol

      public TwoDSymbol buildSymbol() throws Exception
      Generates a drawable 2D symbol based on the provided properties.

      Any exceptions thrown by this method are forwarded exceptions caused by the internal call to ZXing's Writer#encode(). Since this method is implemented differently in the ZXing classes depending on the code type, it can throw different exceptions, even though only WriterException is declared by the Writer#encode() methods. Therefore, all exceptions are forwarded as a generalized java.lang.Exception.

      For example, the DataMatrixWriter and the PDF417Writer may throw different exceptions, even for the same reason, such as when non-encodable characters are detected in the content. While the first Writer throws the declared WriterException, the second may throw an IllegalArgumentException.

      The Writer implementations of the other two code types (QR Code and Aztec) do not throw an exception at all when encountering non-encodable characters, but instead encode the content with a loss of information due to incorrect character encoding. This underlines the importance of checking this first by calling canEncode().

      Returns:
      a TwoDSymbol object representing the generated 2D symbol
      Throws:
      Exception - if an error occurs during the symbol generation process
    • getType

      public TwoDType getType()
      Returns the type of the 2D code.
      Returns:
      the type of the 2D code
    • getContent

      public String getContent()
      Returns the content encoded in the 2D code.
      Returns:
      the content encoded in the 2D code
    • getCharset

      public Charset getCharset()
      Returns the character set used for encoding the content.
      Returns:
      the character set used for encoding the content
    • getQuietZoneSize

      public int getQuietZoneSize()
      Returns the size of the quiet zone around the 2D code.
      Returns:
      the size of the quiet zone around the 2D code
    • getQRCodeVersion

      public int getQRCodeVersion()
      Returns the version of the QR Code.
      Returns:
      the version of the QR Code
    • getQRCodeErrCorr

      public int getQRCodeErrCorr()
      Returns the error correction level of the QR Code.
      Returns:
      the error correction level of the QR Code
    • getDataMatrixSize

      public int getDataMatrixSize()
      Returns the size of the DataMatrix symbol.
      Returns:
      the size of the DataMatrix symbol
    • getDataMatrixShape

      public int getDataMatrixShape()
      Returns the shape of the DataMatrix symbol.
      Returns:
      the shape of the DataMatrix symbol
    • getPDF417Size

      public TwoDSize getPDF417Size()
      Returns the size of the PDF417 symbol.
      Returns:
      the size of the PDF417 symbol
    • getPDF417ErrCorr

      public int getPDF417ErrCorr()
      Returns the error correction level of the PDF417.
      Returns:
      the error correction level of the PDF417
    • getAztecSize

      public int getAztecSize()
      Returns the size index of the Aztec symbol.
      Returns:
      the size index of the Aztec symbol
    • getAztecErrCorr

      public int getAztecErrCorr()
      Returns the error correction level of the Aztec.
      Returns:
      the error correction level of the Aztec
    • clone

      public Object clone()
      Returns a copy of this object. The returned copy can be considered and used as a "deep copy".
      Overrides:
      clone in class Object
      Returns:
      a copy of this object