Installation – Maven and Gradle
<dependency>
<groupId>de.vwsoft</groupId>
<artifactId>barcodelib4j</artifactId>
<version>3.0.0</version>
</dependency>
// Groovy DSL
implementation 'de.vwsoft:barcodelib4j:3.0.0'
// Kotlin DSL
implementation("de.vwsoft:barcodelib4j:3.0.0")
- Maven Central – Add dependency to other build tools or browse versions
- GitHub – Download Java sources, Javadoc, and precompiled JAR
- OpenPDF – Optional dependency for PDF export (v1.3.0 or higher)
- Javadoc online – Complete API documentation and reference
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 format, which only supports RGB colors. To switch to the CMYK color
model, use a CompoundColor constructor for CMYK colors in step 3. Then, in step 5, replace writeSVG with
either writeEPS or writePDF and add ImageColorModel.CMYK as the second parameter.
// 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 content validation error
}
barcode.setFont(new Font("OCR-B", Font.PLAIN, 1));
barcode.setFontSizeAdjusted(true);
barcode.setTextOffset(-0.3);
// ... add 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 a 'BarExporter' instance
BarExporter exporter = new BarExporter(widthMM, heightMM);
exporter.setTitle("Code 128: " + barcode.getText());
exporter.setForeground(new CompoundColor(Color.RED));
exporter.setBackground(new CompoundColor(Color.YELLOW));
// ... add 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
Graphics2D g2d = exporter.getGraphics2D();
barcode.draw(g2d, 0.0, 0.0, widthMM, heightMM);
g2d.dispose();
// Note: The returned 'Graphics2D' is specifically set up for barcode
// drawing, so all necessary 'RenderingHints' are preconfigured
// STEP 5: Write the barcode graphic to a vector image file
try (FileOutputStream fos = new FileOutputStream("Code 128.svg")) {
exporter.writeSVG(fos);
} catch (IOException ex) {
// Handle file writing errors
}
2D Code Example – QR Code to vector graphic with CMYK colors
This example creates a barcode graphic in EPS format with CMYK colors. To switch to RGB colors, use a
CompoundColor constructor for RGB in step 5. Then, in step 7, replace ImageColorModel.CMYK with
ImageColorModel.RGB, or use writeSVG instead (which only supports RGB).
// STEP 1: Initialize and configure a 'TwoDCode' instance
TwoDCode tdc = new TwoDCode(TwoDType.QRCODE);
tdc.setContent("Hello World!");
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(QRCodeVersion.AUTO);
tdc.setQRCodeErrCorr(QRCodeErrorCorrection.M);
// Instructs the library to automatically select the smallest
// QR code version (= size of the code symbol) capable of encoding
// the content and sets the medium error correction level ("M")
// 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 'BarExporter' instance
BarExporter exporter = new BarExporter(widthMM, heightMM);
exporter.setTitle("Sample QR Code");
exporter.setForeground(new CompoundColor(70, 60, 0, 40));
exporter.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
Graphics2D g2d = exporter.getGraphics2D();
symbol.draw(g2d, 0.0, 0.0, widthMM, heightMM);
g2d.dispose();
// Note: The returned 'Graphics2D' is specifically set up for barcode
// drawing, so all necessary 'RenderingHints' are preconfigured
// STEP 7: Write the barcode graphic to a vector image file
try (FileOutputStream fos = new FileOutputStream("QR Code.eps")) {
exporter.writeEPS(fos, ImageColorModel.CMYK);
} catch (IOException ex) {
// Handle file writing errors
}
Printing or Exporting 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 millimeters 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' method call in the above 1D example
barcode.draw(g2d, 0.0, 0.0, widthMM, heightMM, dotSizeMM, 0.0, 0.0);
// Adjust the 'draw' method call in the above 2D example
symbol.draw(g2d, 0.0, 0.0, widthMM, heightMM, dotSizeMM);
// Adjust the 'write' method call
exporter.writePNG(fos, resolutionDPI, resolutionDPI);
- For 1D barcodes, which consist of vertical bars, only one of the two resolutions is important. For example,
when creating a 1D barcode at an angle of 0° or 180°, the horizontal resolution is crucial, as the bar widths must
be adjusted to this. At an angle of 90° or 270°, the vertical resolution should be considered accordingly.
- For 2D codes, if the printer has different horizontal and vertical resolutions, regardless of the chosen
angle, always use the smaller of the two resolutions. For example, with a resolution of 300×600 DPI, the lower
resolution of 300 DPI should be considered.
Creating GS1 Barcodes – GS1-128, GS1 DataMatrix, GS1 QR Code
Depending on the type of barcode you want to create, use one of the above complete 1D or
2D examples and insert the following code before STEP 1.
// 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;
For GS1-128, replace in STEP 1:
Barcode barcode = Barcode.newInstance(BarcodeType.EAN128);
try {
barcode.setContent(content, false, false);
} catch (BarcodeException ex) {
// Handle content validation error
}
For GS1 DataMatrix or GS1 QR Code, replace in STEP 1:
// For GS1 QR Code replace GS1_DATAMATRIX with GS1_QRCODE
TwoDCode tdc = new TwoDCode(TwoDType.GS1_DATAMATRIX);
try {
GS1Validator validator = new GS1Validator(content, fnc1);
tdc.setContent(validator.getContent());
} catch (BarcodeException ex) {
// Handle content validation error
}
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().