Part 5: Programmatic Implementation and Examples of Barcode4J |
5.1 Overview of Programmatic Usage |
Barcode4J is primarily a Java-based library, designed for developers to generate barcodes programmatically within applications, web services, or reporting systems. Unlike GUI-based barcode generators, Barcode4J provides APIs that allow dynamic barcode creation based on input data, symbology selection, rendering preferences, and output formats. |
A typical programmatic workflow involves: |
1. Including Barcode4J libraries in the Java project. |
2. Selecting the appropriate barcode type (symbology). |
3. Configuring barcode parameters such as dimensions, colors, and human-readable text. |
4. Generating the barcode as an image or integrating it directly into reports or PDFs. |

|
5.2 Setting Up Barcode4J in a Java Project |
5.2.1 Including Dependencies |
To use Barcode4J, developers must include the required JAR files in the project. In a Maven project, the dependency can be declared as follows (using a public repository): |
```xml |
|
net.sourceforge.barcode4j |
barcode4j |
2.1 |
|
``` |
Alternatively, the JAR can be downloaded directly from the Barcode4J website and added to the classpath. |
5.2.2 Importing Required Classes |
Typical classes used in Barcode4J include: |
```java |
import org.krysalis.barcode4j.impl.code128.Code128Bean; |
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider; |
import org.krysalis.barcode4j.tools.UnitConv; |
import java.io.FileOutputStream; |
import java.io.OutputStream; |
``` |
These imports allow access to the barcode encoders, output providers, and utilities for converting units and generating images. |

|
5.3 Generating a Simple Code 128 Barcode |
5.3.1 Example Code |
```java |
public class BarcodeExample { |
public static void main(String[] args) { |
try { |
// 1. Create a Code128 barcode bean |
Code128Bean barcode128 = new Code128Bean(); |
|
// 2. Configure barcode properties |
barcode128.setModuleWidth(UnitConv.in2mm(0.013)); // narrow bar width |
barcode128.setBarHeight(15); // barcode height in mm |
barcode128.doQuietZone(true); // enable quiet zone |
// 3. Define output file |
OutputStream out = new FileOutputStream('barcode128.png'); |
// 4. Set up bitmap canvas provider |
BitmapCanvasProvider canvas = new BitmapCanvasProvider( |
out, 'image/png', 300, BufferedImage.TYPE_BYTE_BINARY, false, 0); |
// 5. Generate barcode |
barcode128.generateBarcode(canvas, '1234567890'); |
// 6. Finish drawing |
canvas.finish(); |
out.close(); |
System.out.println('Barcode generated successfully!'); |
} catch (Exception e) { |
e.printStackTrace(); |
} |
} |
} |
``` |
5.3.2 Explanation |
* `Code128Bean` defines the barcode type. |
* `setModuleWidth` and `setBarHeight` configure dimensions. |
* `BitmapCanvasProvider` converts the barcode into a raster image (PNG in this case). |
* `generateBarcode` encodes the data and renders it. |
* `canvas.finish()` ensures the output stream is correctly closed and the image is finalized. |

|
5.4 Generating a PDF417 (2D) Barcode |
5.4.1 Example Code |
```java |
import org.krysalis.barcode4j.impl.pdf417.PDF417Bean; |
public class PDF417Example { |
public static void main(String[] args) { |
try { |
PDF417Bean pdf417 = new PDF417Bean(); |
pdf417.setModuleWidth(UnitConv.in2mm(0.012)); |
pdf417.setBarHeight(6); |
pdf417.setErrorLevel(5); // error correction level |
OutputStream out = new FileOutputStream('pdf417.png'); |
BitmapCanvasProvider canvas = new BitmapCanvasProvider( |
out, 'image/png', 300, BufferedImage.TYPE_BYTE_BINARY, false, 0); |
pdf417.generateBarcode(canvas, 'https://www.example.com/order/12345'); |
canvas.finish(); |
out.close(); |
System.out.println('PDF417 barcode generated successfully!'); |
} catch (Exception e) { |
e.printStackTrace(); |
} |
} |
} |
``` |
5.4.2 Explanation |
* `PDF417Bean` generates high-capacity 2D barcodes. |
* `setErrorLevel` allows for Reed-Solomon error correction, which is critical for high-density data. |
* This barcode can encode URLs, tracking numbers, or serialized data for logistics and tickets. |

|
5.5 Output Formats |
5.5.1 Raster Images (PNG, JPEG) |
* Generated using `BitmapCanvasProvider`. |
* Ideal for web applications, on-demand labels, and desktop printing. |
* Resolution can be configured (e.g., 300 dpi) for high-quality printing. |
5.5.2 Vector Images (SVG) |
```java |
import org.krysalis.barcode4j.output.svg.SVGCanvasProvider; |
SVGCanvasProvider svgCanvas = new SVGCanvasProvider(false, 0); |
barcode128.generateBarcode(svgCanvas, '1234567890'); |
org.w3c.dom.Document svgDoc = svgCanvas.getDOM(); |
``` |
* Vector format ensures scalability without loss of quality. |
* Perfect for embedding in PDFs, large-format printing, or responsive web pages. |
5.5.3 PDF Integration |
* Barcode4J can generate XSL-FO objects for Apache FOP or use iText for embedding into PDFs. |
* Eliminates the need for intermediate images. |
* Supports batch report generation with dynamic barcodes for each data record. |

|
5.6 Customization Options in Code |
5.6.1 Text Annotations |
Barcode4J can render human-readable text below the barcode. |
```java |
barcode128.setFontName('Arial'); |
barcode128.setFontSize(4); |
barcode128.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM); |
``` |
5.6.2 Color Customization |
```java |
canvas.getGraphics2D().setPaint(Color.BLUE); // change barcode color |
``` |
5.6.3 Quiet Zones |
* Quiet zones are mandatory blank margins around barcodes. |
* Configurable via `doQuietZone(true/false)` for scanners that require space around the code. |

|
5.7 Integration Example: Web Application |
5.7.1 Servlet-Based Barcode Generation |
```java |
@WebServlet('/barcode') |
public class BarcodeServlet extends HttpServlet { |
protected void doGet(HttpServletRequest request, HttpServletResponse response) |
throws IOException { |
response.setContentType('image/png'); |
String data = request.getParameter('data'); |
if (data == null) data = '000000'; |
Code128Bean barcode = new Code128Bean(); |
barcode.setModuleWidth(UnitConv.in2mm(0.013)); |
barcode.setBarHeight(15); |
BitmapCanvasProvider canvas = new BitmapCanvasProvider( |
response.getOutputStream(), 'image/png', 300, BufferedImage.TYPE_BYTE_BINARY, false, 0); |
barcode.generateBarcode(canvas, data); |
canvas.finish(); |
} |
} |
``` |
* Users can request a barcode by providing a `data` parameter in the URL. |
* No intermediate files are needed; the image is streamed directly to the client. |
5.7.2 Applications |
* Dynamic barcode generation for e-commerce orders. |
* On-demand ticketing or membership systems. |
* Web-based inventory management portals. |
5.8 Practical Tips for Developers |
* Batch Processing: Use streams and memory-efficient canvas providers for generating hundreds or thousands of barcodes. |
* Error Handling: Always validate input against symbology rules to avoid invalid barcodes. |
* High-Resolution Printing: Increase module width and DPI settings for thermal or label printers. |
* Font Compatibility: Ensure fonts used for human-readable text are available on the server to prevent rendering errors. |
* Thread Safety: Use separate `Bean` instances per thread in multi-threaded applications to avoid concurrency issues. |
5.9 Summary of Part 5 |
Part 5 provided practical guidance for implementing Barcode4J programmatically, covering: |
* Library setup and dependency management. |
* Examples of generating Code 128 and PDF417 barcodes. |
* Output options (raster, vector, PDF). |
* Customization of dimensions, fonts, and colors. |
* Web integration and streaming barcodes directly to clients. |
* Developer tips for batch processing, error handling, and high-resolution output. |
By following these examples, developers can integrate Barcode4J into almost any Java-based system, ensuring dynamic, reliable, and scalable barcode generation. |
Cited Reference |
* Barcode4J Official Website: [https://barcode4j.sourceforge.io/](https://barcode4j.sourceforge.io/) |