Friday, 18 December 2015

JAVA - Generating Barcode and adding to a pdf

Generating Barcode and adding to a pdf :
Barcode can be easily generated through barcode4j.jar, which can be downloaded from many sites. Moreover, its integration with the PDF file can done through itextpdf jar.

Here is a complete program to generate bar code and integrate with pdf file. You need to download these two jars and add in libraries.

import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
public class barcodeGeneration {

public static void main(String[] args) {
Code128Bean obj = new Code128Bean();
obj.setHeight(15f);
obj.setModuleWidth(0.3);
obj.setQuietZone(10);
obj.doQuietZone(true);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
BitmapCanvasProvider canvas = new BitmapCanvasProvider(baos, "image/x-png", 300, BufferedImage.TYPE_BYTE_BINARY, false, 0);
obj.generateBarcode(canvas, "1234567890");

try {
canvas.finish();
//writing bar to png file
FileOutputStream fos = new FileOutputStream("barcode.png");
fos.write(baos.toByteArray());
fos.flush();
fos.close();
//writing  to pdf
Image png = Image.getInstance(baos.toByteArray());
png.setAbsolutePosition(400, 685);
png.scalePercent(25);
Rectangle rec = new Rectangle(595,595,842,842);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("barcodeFile.pdf"));
document.open();
document.add(png);
document.close();
writer.close();
} catch (FileNotFoundException e) {
System.out.println("file not foundException");
e.printStackTrace();
} catch (BadElementException e) {
System.out.println("BadExcption");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("MalformedURLException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
} catch (DocumentException e) {
System.out.println("DocumentException");
e.printStackTrace();
}
}

}

No comments:

Post a Comment