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);
- 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
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().