DEV Community

Cover image for Generate a Barcode with Text in Java Using ZXing
Yaroslav Ivanovskyi
Yaroslav Ivanovskyi

Posted on

Generate a Barcode with Text in Java Using ZXing

I recently came across a barcode generation example in Python on X.com, and it inspired me to build something similar in Java.

python code

In this post, we’ll generate a CODE_128 barcode and add human-readable text below it, exporting everything as a single PNG image. We’ll use the popular https://github.com/zxing/zxing (Zebra Crossing) library to handle the barcode generation.

Dependencies
To get started, add the following dependencies to your Maven project (pom.xml):

<dependency>
     <groupId>com.google.zxing</groupId>
     <artifactId>core</artifactId>
     <version>3.5.1</version>
 </dependency>
 <dependency>
     <groupId>com.google.zxing</groupId>
     <artifactId>javase</artifactId>
     <version>3.5.1</version>
 </dependency>
Enter fullscreen mode Exit fullscreen mode

Java Code
Here’s the full code to generate the barcode image with the data displayed beneath it:

// Import required libraries for barcode generation and image processing
import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.oned.Code128Writer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * This class demonstrates how to generate a barcode with text using ZXing library.
 * It creates a CODE_128 barcode and saves it as a PNG image file with the encoded
 * text displayed below the barcode.
 */
public class Barcode {

    public static void main(String[] args) throws Exception {
        // The data to be encoded in the barcode
        String data = "1234-5678-9012";

        // Dimensions for the barcode and text area
        int width = 400;        // Width of the barcode
        int height = 100;       // Height of the barcode
        int textHeight = 30;    // Additional height for the text below the barcode

        // Generate the barcode image using ZXing library
        // Code128Writer is used to create a CODE_128 format barcode
        BufferedImage barcode = MatrixToImageWriter.toBufferedImage(
                new Code128Writer().encode(data, BarcodeFormat.CODE_128, width, height)
        );

        // Create a new image that will contain both the barcode and text
        BufferedImage combined = new BufferedImage(width, height + textHeight, BufferedImage.TYPE_INT_RGB);

        // Get the graphics context to draw on the combined image
        Graphics2D g = combined.createGraphics();

        // Fill the background with white
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height + textHeight);

        // Draw the barcode at the top of the image
        g.drawImage(barcode, 0, 0, null);

        // Set up the font and color for the text
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.PLAIN, 18));

        // Calculate the x-coordinate to center the text and draw it below the barcode
        int textX = (width - g.getFontMetrics().stringWidth(data)) / 2;
        g.drawString(data, textX, height + 20);

        // Clean up the graphics context
        g.dispose();

        // Save the combined image (barcode + text) to a PNG file
        ImageIO.write(combined, "png", new File("barcode_with_text.png"));
        System.out.println("Barcode with text saved as 'barcode.png'.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Here’s what the result looks like:

barcode

A Quick Note on CODE_128
CODE_128 is a high-density linear barcode format that supports all 128 ASCII characters. It’s widely used in logistics, shipping labels, inventory systems, and more. ZXing handles this encoding under the hood, making it easy to integrate in Java apps.

Top comments (0)