Barcode and Label Software

Barcode-Lib4J – Open-Source Barcode Library for Java

Barcode-Lib4J

BARCODE-Lib4J – Open-Source Java library for creating, printing and storing 1D and 2D barcodes as vector (PDF, EPS, SVG) and raster (PNG, BMP, JPG) images. Proven in practice through use in our commercial software products.

Barcodes with Java

  • Drawing and printing of 1D and 2D barcodes using Java2D (java.awt.Graphics2D)
  • Barcodes as PDF: Compliance with PDF/X-1a:2001 for color-accurate printing in CMYK as well as PDF/X-3:2002 for RGB colors
  • Barcodes as EPS: Supports both RGB and CMYK color models; Optional embedding of a TIFF preview for display in graphic applications without their own EPS interpreter
  • Barcodes as SVG: This vector format inherently only supports the RGB color model
  • Barcodes as PNG, BMP, JPG: DPI resolution is stored in the file header, thereby preserving both the target resolution and the original dimensions of the graphic for later printing; No unwanted visual effects, such as aliasing, distortion or other artifacts
  • High precision: Coordinates are stored with up to six decimal places in all supported vector formats
  • Adjustment of bar widths to printer resolution (important for ensuring proper barcode quality at resolutions ≤ 600 dpi)
  • Bar width reduction/correction (useful to account for ink spread in inkjet printers)
  • Barcodes include required minimum distances ("quiet zones") according to the respective specification
  • Customizable plain text line: font, size, spacing and editable content; Optional automatic font size adjustment; Additionally, the plain text line can be positioned at the top, bottom or completely hidden
  • Advanced setting: Customizable size of the barcode bars ("module size")
  • Option for transparent background (Supported in EPS, PDF, SVG and PNG)
  • Rotation in 90-degree increments
  • Configurable bar width ratio from 2:1 to 3:1 for barcode types that support this feature: Interleaved 2 of 5, Code 39 and others
  • Add-Ons 2 or 5 for the barcode types EAN-13, EAN-8, UPC-A, UPC-E, ISBN-13 and ISMN; second plain text line for ISBN-13 and ISMN
  • Comprehensive support for GS1-128, GS1 DataMatrix and GS1 QR Code: Verification of data integrity such as correctness of application identifiers, length and format of individual data elements, verification/calculation of the check digit in SSCC and GTIN and more

Java Version and Dependencies

Java 9 or later is required. The OpenPDF library v1.3.0 or higher is needed for PDF export or during compilation. Once compiled, Barcode-Lib4J can be run without this library.

OpenPDF is available at:  GitHub  |  Maven Repository

Getting Started with Examples

In the following examples, various classes need to be imported. To avoid having to do this individually for each example, you can use the following import list, which includes all required classes at once:

import java.awt.*;
import java.io.*;

import de.vwsoft.barcodelib4j.image.*;
import de.vwsoft.barcodelib4j.oned.*;
import de.vwsoft.barcodelib4j.twod.*;

1D Barcode Example – Code 128 to vector graphic with RGB colors

This example creates a barcode graphic in SVG vector format, which only supports RGB colors. To switch to the CMYK color model, replace writeSVG with writeEPS or writePDF in step 5 and modify the method call by adding ImageCreator.COLORSPACE_CMYK as the second parameter. Then, in step 3, use one of the constructors designed for CMYK colors for CompoundColor.

// STEP 1: Initialize and configure a 'Barcode' instance
Barcode barcode = Barcode.newInstance(BarcodeType.CODE128);
try {
    barcode.setContent("Abc-12345", false, false);
} catch (BarcodeException ex) {
    // Handle invalid barcode content
}
barcode.setFont(new Font("OCR-B", Font.PLAIN, 1));
barcode.setFontSizeAdjusted(true);
barcode.setTextOffset(-0.3);
// ... More optional settings for checksum, add-ons, ratio,
// text positioning and visibility, and other barcode properties

// STEP 2: Specify dimensions of the graphic in millimeters
final double widthMM = 50.0, heightMM = 30.0;

// STEP 3: Initialize and configure an 'ImageCreator' instance
ImageCreator imageCreator = new ImageCreator(widthMM, heightMM);
imageCreator.setTitle("Code 128: " + barcode.getText());
imageCreator.setForeground(new CompoundColor(Color.RED));
imageCreator.setBackground(new CompoundColor(Color.YELLOW));
// ... More optional settings, such as background opacity,
// rotation angle and additional metadata

// STEP 4: Get a 'Graphics2D' instance, then draw the barcode at
// position [0,0] using the specified dimensions once more
Graphics2D g2d = imageCreator.getGraphics2D();
barcode.draw(g2d, 0.0, 0.0, widthMM, heightMM);
g2d.dispose();
// ... The returned 'Graphics2D' instance is specifically set up for
// barcode drawing; necessary 'RenderingHints' are preconfigured

// STEP 5: Write the barcode graphic to a vector image file
try (FileOutputStream fos = new FileOutputStream("Code 128.svg")) {
    imageCreator.writeSVG(fos);
} catch (IOException ex) {
    // Handle file writing errors
}

2D Code Example – QR Code to vector graphic with CMYK colors

For using RGB colors instead of CMYK, read the introduction to the first example. Both color models are supported by the EPS and PDF formats.

// STEP 1: Initialize and configure a 'TwoDCode' instance
TwoDCode tdc = new TwoDCode();
tdc.setType(TwoDType.QRCODE);
tdc.setQuietZoneSize(TwoDCode.ALL_QUIET_ZONES.get(TwoDType.QRCODE));
tdc.setContent("I'm a QR code pretending to be important data");
tdc.setCharset(null); // ISO-8859-1 is used, no ECI is included
// Alternatively, a character set other than ISO-8859-1 (e.g., UTF-8)
// can be specified, which inserts an ECI block in the QR code

// STEP 2: Apply type-specific settings (methods for DataMatrix
// start with setDataMatrix***, for PDF417 with setPDF417***, etc.)
tdc.setQRCodeVersion(TwoDCode.QRCODE_VERSION_AUTO);
tdc.setQRCodeErrCorr(1);
// Sets the lowest error correction level ("L") and instructs
// the library to automatically select the smallest QR code version
// (= size of the code symbol) capable of encoding the content

// STEP 3: Check if the content can be encoded with the chosen
// character set; then retrieve a drawable 'TwoDSymbol' instance
TwoDSymbol symbol = null;
if (tdc.canEncode()) {
    try {
        symbol = tdc.buildSymbol();
    } catch (Exception ex) {
        // Handle the Exception
    }
}

// STEP 4: Specify the dimensions of the graphic in millimeters;
// since QR codes are always square, the symbol will be centered
// within the area (for demonstration, width and height differ)
final double widthMM = 50.0, heightMM = 30.0;

// STEP 5: Initialize and configure an 'ImageCreator' instance
ImageCreator imageCreator = new ImageCreator(widthMM, heightMM);
imageCreator.setTitle("Sample QR Code");
imageCreator.setForeground(new CompoundColor(70, 60, 0, 40));
imageCreator.setBackground(new CompoundColor(0, 5, 40, 0));
// ... Here, further optional settings can be configured, such as
// background opacity, rotation angle, additional metadata
// and settings for embedding of an optional TIFF preview

// STEP 6: Get 'Graphics2D' instance, then draw the code at
// position [0,0] using the specified dimensions once more
Graphics2D g2d = imageCreator.getGraphics2D();
symbol.draw(g2d, 0.0, 0.0, widthMM, heightMM);
g2d.dispose();
// Note: The returned 'Graphics2D' instance is specifically set up for
// barcode drawing, with necessary 'RenderingHints' preconfigured

// STEP 7: Write the barcode graphic to a vector image file
try (FileOutputStream fos = new FileOutputStream("QR Code.eps")) {
    imageCreator.writeEPS(fos, ImageCreator.COLORSPACE_CMYK);
} catch (IOException ex) {
    // Handle file writing errors
}

Printing or Exporting 1D and 2D Barcodes to Raster Formats

When exporting barcodes to raster formats (PNG, BMP, JPG) or printing to a low-resolution printer, it's important to specify the correct resolution to ensure the best possible quality. To do this, use the appropriate numerical parameter for the write method and the derived dot size in millimetres for the draw method. The dot size is calculated using the formula: 25.4 divided by the resolution in DPI. Example:

// An average label printer's typical (low) resolution
int resolutionDPI = 300;

// Calculate the dot size in millimeters
double dotSizeMM = 25.4 / resolutionDPI;

// Adjust the 'draw' and the 'write' method calls
barcode.draw(g2d, 0.0, 0.0, widthMM, heightMM, dotSizeMM, 0.0, 0.0);
// ...
imageCreator.writePNG(fos, resolutionDPI, resolutionDPI);

Creating GS1 Barcodes – GS1-128, GS1 DataMatrix, GS1 QR Code

Before creating GS1 barcodes, you should familiarize yourself with the concept of GS1 application identifiers. For a detailed description, see the tutorials on this website: GS1-128 and GS1 DataMatrix.

Depending on the type of barcode you want to create, use one of the above complete 1D or 2D examples for simplicity and insert the following code sections appropriately into the respective Java code.

For all three code types, the content string is built according to the same pattern:

// For GS1-128, use the ImplEAN128.FNC1 constant as FNC1 character;
// for GS1 DataMatrix and GS1 QR Code, replace it with (char)29
final char fnc1 = ImplEAN128.FNC1;

// A GTIN and a best-before date as sample data
final String gtinAI = "01", gtinValue = "01234567890128";
final String bestBeforeDateAI = "15", bestBeforeDateValue = "271231";

// Concatenate the content string by applying the same pattern
// to each AI+value pair; unnecessary FNC1 characters, including
// the last one, will be automatically removed by the library
String content =
        '(' + gtinAI + ')' + gtinValue + fnc1 +
        '(' + bestBeforeDateAI + ')' + bestBeforeDateValue + fnc1;
// Note: the library also accepts the content without parentheses;
// these are inserted here for easier troubleshooting

For GS1-128, proceed as follows:

Barcode barcode = Barcode.newInstance(BarcodeType.EAN128);
try {
    barcode.setContent(content, false, false);
} catch (BarcodeException ex) {
    // Handle validation error
}

For GS1 DataMatrix or GS1 QR Code, proceed as follows:

// Create a 'TwoDCode' instance and set as its type:
// TwoDType.GS1_DATAMATRIX or TwoDType.GS1_QRCODE

String validated = null;
try {
  validated = new GS1Validator(content, (char)29).getContent();
} catch (BarcodeException ex) {
  // Handle validation error
}

if (validated != null)
  // ... set 'validated' via 'setContent' method

In case of invalid content, BarcodeException provides a detailed error message. These messages are available in two languages: English and German. The English message can always be retrieved using getMessage(), while getLocalizedMessage() returns the message corresponding to Java's default locale setting, as returned by Locale.getDefault().