Choose Your Language

Sunday, 14 April 2013

Barcode generation using servlets

BarcodeServlet.java
 
import com.onbarcode.barcode.Code128;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Aravind Sankaran
 */
public class BarcodeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String number="";
            try {
            Code128 barcode = new Code128();            
            Random randomGenerator = new Random();
            for (int idx = 1; idx <= 1; ++idx){
            long randomInt = randomGenerator.nextInt(01234567);           
            number=String.valueOf(randomInt);
            }
            System.out.println("random number generated is"+number);
            barcode.setData(number);                            
            ServletOutputStream servletoutputstream = response.getOutputStream();
             
            response.setContentType("image/jpeg");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
          
            // Generate Code-128 barcode & output to ServletOutputStream
            barcode.drawBarcode(servletoutputstream);
     
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}
jar file needed:
barcode.jar

No comments:

Post a Comment