Generate Barcode using com.itextpdf.text.pdf.Barcode39 and display in JSP / Servlet

Working example of generating and delivering given text as Barcode39 Image through Java Servlets :

import com.lowagie.text.pdf.Barcode39;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Generates barcode for the specified text.
*
* */
public class BarcodeServlet extends HttpServlet {

/**
* @param request
* @param response
* @throws java.io.IOException
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
String strBarCode = request.getParameter(“barcode”);

byte[] pngImageData = null;

try {
Barcode39 code39ext = new Barcode39();
code39ext.setCode(strBarCode);
code39ext.setStartStopText(false);
code39ext.setExtended(true);
java.awt.Image rawImage = code39ext.createAwtImage(Color.BLACK, Color.WHITE);
BufferedImage outImage = new BufferedImage(rawImage.getWidth(null), rawImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
outImage.getGraphics().drawImage(rawImage, 0, 0, null);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ImageIO.write(outImage, “png”, bytesOut);
bytesOut.flush();
pngImageData = bytesOut.toByteArray();

} catch (Exception e) {
e.printStackTrace();
}

if (pngImageData != null) {
response.setContentLength(pngImageData.length);
response.setContentType(“image/png”);
OutputStream out = response.getOutputStream();
out.write(pngImageData);
out.flush();
out.close();
} else {
// Add code to display noimage
response.sendRedirect(“/images/nophoto.jpg”);
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *