How to create Barcodes in Java

Itext PDF is an open source API that allows to create bar codes in pdf documents. In this example we will see how to create a simple Code 128 using Itext.

1. Create a Maven project and add below dependency.

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.0.6</version>
        </dependency>


2. Create a Main program to create barcode

package com.vinod.test;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.Barcode128;
import com.itextpdf.text.pdf.PdfWriter;
public class JavaBarCodeExample {
    public static void main(String[] args) {
        try {
            Document document = new Document(new Rectangle(PageSize.A4));
            PdfWriter writer = PdfWriter.getInstance(document,
                    new FileOutputStream("MYBARCODE.pdf"));
            document.open();
            document.add(new Paragraph("HelloWorld"));
            Barcode128 barcode128 = new Barcode128();
            barcode128.setGenerateChecksum(true);
            barcode128.setCode("KKVINOD.COM");
            document.add(barcode128.createImageWithBarcode(
                    writer.getDirectContent(), null, null));
            document.close();
            System.out.println("PDF file created");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3. Output


 

No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts