Advertisement
Guest User

Luis Cantu

a guest
Jan 23rd, 2008
10,961
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.65 KB | None | 0 0
  1. package servlets;
  2. /*
  3. * barcode.java
  4. *
  5. * Created on January 23, 2008, 10:38 AM
  6. */
  7.  
  8. import com.lowagie.text.Chunk;
  9. import com.lowagie.text.Document;
  10. import com.lowagie.text.DocumentException;
  11. import com.lowagie.text.Element;
  12. import com.lowagie.text.Image;
  13. import com.lowagie.text.Phrase;
  14. import com.lowagie.text.Rectangle;
  15. import com.lowagie.text.pdf.Barcode128;
  16. import com.lowagie.text.pdf.PdfContentByte;
  17. import com.lowagie.text.pdf.PdfPCell;
  18. import com.lowagie.text.pdf.PdfPTable;
  19. import com.lowagie.text.pdf.PdfWriter;
  20. import java.awt.Color;
  21. import java.io.*;
  22. import java.net.*;
  23.  
  24. import javax.servlet.*;
  25. import javax.servlet.http.*;
  26.  
  27. /**
  28. *
  29. * @author lmcantu
  30. * @version
  31. */
  32. public class barcode extends HttpServlet {
  33.  
  34. /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
  35. * @param request servlet request
  36. * @param response servlet response
  37. */
  38. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  39. throws ServletException, IOException {
  40.  
  41. /* Revisamos que recibimos los parametros que necesitamos */
  42. if(request.getParameter("location").length()<=0){
  43. response.setContentType("text/html;charset=UTF-8");
  44. PrintWriter out = response.getWriter();
  45. out.println("Required parameter location is missing.");
  46. out.close();
  47. return;
  48. }
  49. if(request.getParameter("number").length()<=0 || Integer.parseInt(request.getParameter("number")) <= 0){
  50. response.setContentType("text/html;charset=UTF-8");
  51. PrintWriter out = response.getWriter();
  52. out.println("Required parameter number is missing.");
  53. out.close();
  54. return;
  55. }
  56.  
  57. int number = Integer.parseInt(request.getParameter("number")); // recibimos los parametros que necesitamos.
  58. String location = request.getParameter("location");
  59. String prior = "0";
  60. String value = new String(""+System.currentTimeMillis());//tomamos el tiempo porque es un numero que no se repite.
  61.  
  62. File temp = File .createTempFile( location+value, ".tmp", new File( "C:\\temp\\" ) ); //creamos un archivo temporal
  63. temp.deleteOnExit();// Arreglamos para que se borren al salir.
  64.  
  65. Document document = new Document();
  66. //la escritura del pdf la haremos dentro de try para capturar errores.
  67.  
  68. try {
  69. PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(temp));
  70. document.open();
  71. PdfContentByte cb = writer.getDirectContent();
  72. /* Empezamos a usar itext para crear una tabla. */
  73. PdfPTable page = new PdfPTable(3); //tres columnas
  74. page.getDefaultCell().setPadding(0f); //sin espacios
  75. page.getDefaultCell().setBorder(Rectangle.NO_BORDER);//sin bordos
  76. page.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);//alineado de izquierda a derecha
  77. page.setWidthPercentage(110f);
  78. /* Ciclo para generar cada codigo de barras, sin repetir el contenido*/
  79. int a = 0;
  80. for(int i = 0; i<number;i++){
  81.  
  82. PdfPTable cell = new PdfPTable(1);//hacemos una tabla para el codigo que haremos
  83. cell.getDefaultCell().setBorder(Rectangle.NO_BORDER);//sin borde
  84. cell.getDefaultCell().setPadding(40f); //medidas solicitadas
  85.  
  86. Barcode128 shipBarCode = new Barcode128();//usamos la clase Barcode128 de iText para generar la imagen
  87. shipBarCode.setX(1f);//puedes modificar estas medidas para que veas como queda tu codigo de barras (mas grande, mas ancho, etcetera)
  88. shipBarCode.setN(0.5f);
  89. shipBarCode.setChecksumText(true);
  90. shipBarCode.setGenerateChecksum(true);
  91. shipBarCode.setSize(5f);
  92. shipBarCode.setTextAlignment(Element.ALIGN_CENTER);//alineado al centro
  93. shipBarCode.setBaseline(9f);
  94. value = new String(""+System.currentTimeMillis());
  95. if(a >9){//cada 9 codigos generamos un consecutivo
  96. String ax = new String(""+System.currentTimeMillis());
  97. while(value.substring(1,value.length()-3).equals(ax.substring(1,ax.length()-3))){//nos ciclamos hasta que el tiempo cambie.
  98. ax = new String(""+System.currentTimeMillis());
  99. }
  100. a = 0;
  101. value = ax;
  102. }
  103. shipBarCode.setCode(location+value.substring(1,value.length()-3)+a);//este es el valor que tendra el codigo de barras.
  104. a++;
  105. shipBarCode.setBarHeight(40f);//altura del codigo de barras
  106.  
  107. Image imgShipBarCode = shipBarCode.createImageWithBarcode(cb, Color.black, Color.BLACK);// convertimos este codigo en una imagen
  108. Chunk cbc = new Chunk(imgShipBarCode, 0, 0);//la imagen del codigo de barras la ponemos en un chunk
  109.  
  110. Phrase p = new Phrase(cbc);//este chunk lo ponemos en un phrase.
  111.  
  112. PdfPCell c = new PdfPCell(p); //creamos una celda que contenga la frase P
  113.  
  114. c.setPaddingTop(23f); //medidas necesarias
  115. c.setPaddingBottom(3f);
  116. c.setPaddingLeft(0f);
  117. c.setPaddingRight(5f);
  118. c.setBorder(Rectangle.NO_BORDER);
  119. c.setVerticalAlignment(Element.ALIGN_TOP);
  120. c.setHorizontalAlignment(Element.ALIGN_CENTER);
  121. cell.addCell(c);//acregamos la celda a la tabla
  122. page.addCell(cell); //la tabla a la tabla principal
  123. }//seguimos en el ciclo!
  124. document.add(page);
  125. document.close();
  126.  
  127. response.setContentType("application/pdf");
  128. OutputStream out = response.getOutputStream();
  129.  
  130. FileInputStream FOS = new FileInputStream(temp);
  131.  
  132. while (FOS.available() > 0)
  133. out.write(FOS.read());
  134.  
  135. } catch (FileNotFoundException ex) {
  136. ex.printStackTrace();
  137. response.setContentType("text/html;charset=UTF-8");
  138. PrintWriter out = response.getWriter();
  139. out.println(ex.getMessage());
  140. out.close();
  141. } catch (DocumentException ex) {
  142. ex.printStackTrace();
  143. response.setContentType("text/html;charset=UTF-8");
  144. PrintWriter out = response.getWriter();
  145. out.println(ex.getMessage());
  146. out.close();
  147. }
  148.  
  149.  
  150.  
  151.  
  152.  
  153.  
  154.  
  155.  
  156.  
  157.  
  158. }
  159.  
  160. // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  161. /** Handles the HTTP <code>GET</code> method.
  162. * @param request servlet request
  163. * @param response servlet response
  164. */
  165. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  166. throws ServletException, IOException {
  167. processRequest(request, response);
  168. }
  169.  
  170. /** Handles the HTTP <code>POST</code> method.
  171. * @param request servlet request
  172. * @param response servlet response
  173. */
  174. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  175. throws ServletException, IOException {
  176. processRequest(request, response);
  177. }
  178.  
  179. /** Returns a short description of the servlet.
  180. */
  181. public String getServletInfo() {
  182. return "Short description";
  183. }
  184. // </editor-fold>
  185. }
  186.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement