Wednesday, 9 December 2015

Textual description of firstImageUrl

How to Generate Barcode 128 In Java

For generating Barcodes , we can use Barcode4j library , which is opensource and free library . Let's look at some java code to generate barcode as image in java .

First of all , enter following dependency in your pom.xml.
<dependency>
 <groupId>net.sf.barcode4j</groupId>
 <artifactId>barcode4j</artifactId>
 <version>2.1</version>
   
   </dependency>

You can also download the jar from here if you are using it in a standalone java program .

Now here is the sample java program which generates the barcode 128 with codeset B and save it as a png file.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.impl.code128.Code128Constants;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;


public class MainClass2 {
  
  public static void main(String[] args) throws IOException {
    
    String barcodeString = "4888575";
    Code128Bean barcode128Bean = new Code128Bean();
    
    
    barcode128Bean.setCodeset(Code128Constants.CODESET_B);
    final int dpi = 100;

  //Configure the barcode generator
    //adjust barcode width here
  barcode128Bean.setModuleWidth(UnitConv.in2mm(5.0f / dpi)); 
  barcode128Bean.doQuietZone(false);

  //Open output file
  File outputFile = new File("G:/barcode.png");
  OutputStream out = new FileOutputStream(outputFile);
  try 
  {
      BitmapCanvasProvider canvasProvider = new BitmapCanvasProvider(
              out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);

      barcode128Bean.generateBarcode(canvasProvider,barcodeString);

      canvasProvider.finish();
  } 
  finally 
  {
      out.close();
  }
    
  }

}

Barcode4J supports other formats like EAN-128, GS1-128 , Code 39 etc as well .


Provide comments and suggestions !!!