Gerar codigo de barras

Pessoal, alguem ja gerou um codigo d barras, eu to fazendo assim

O BD gera um numero 0001, 0002 e este e transformado em codigo d barras, pra depois ser impresso, alguem pd me ajudar ??

1 curtida

a biblioteca do iText gera código de barras pra ti, é só dar uma olhada na API…

1 curtida

Links que podem ser uteis:

http://www.ans.gov.br/portal/site/rank/rank_faixas.asp?cons=3&lista=all
http://www.guj.com.br/java.artigo.34.1.guj

Codigo que pode ser util:

package boleto;
import java.lang.String.*;
import java.lang.*;
import javax.servlet.http.*;
import javax.servlet.*;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.*;
import java.io.*;
import java.awt.Graphics2D.*;
import java.awt.*;
import com.sun.image.codec.jpeg.*;

public class boleto {

java.awt.image.BufferedImage image;

/** Metodo criaImagem
* Usado para criacao da imagem que representa o codigo de barras
@author Ricardo Gil
*/
public boolean criaImagem(String texto,PageContext pageContext, int h)
                                 throws ServletException,IOException {
int i, j, tam;
//Variavel que contem a representacao em Codigo de Barras de cada um dos numeros.
//Nessa representacao:
// 0 significa Barra Fina (NARROW);
// 1 significa Barra Grossa (WIDE).
String[] barras = {"00110", //0
                   "10001", //1
                   "01001", //2
                   "11000", //3
                   "00101", //4
                   "10100", //5
                   "01100", //6
                   "00011", //7
                   "10010", //8
                   "01010"};//9
//O Codigo de barras e formado sempre por pares intercalados.
//Por exemplo 12:
//Pegando-se a representacao do 1 e do 2 na variavel acima teriamos o seguinte:
//1001000011.
//Com isso, o primeiro numero representa as Barras Pretas (Fina ou Grossa)
// e o Segundo numero representa as Barras Brancas, ou espacos, (Fina ou Grossa).
int preto,branco;
int w = 9 + (9 * texto.length());
HttpServletResponse response;
response = (HttpServletResponse)pageContext.getResponse();
ServletOutputStream out = response.getOutputStream();
image = new java.awt.image.BufferedImage(w,h, java.awt.image.BufferedImage.TYPE_INT_RGB);
tam = 0;
fillRect(0, 0, w, h, 0x00FFFFFF); //começo do Codigo de Barras = 0 = 00 / 1 = 00
fillRect(tam, 0, tam+1, h, 0x00000000);
tam++;
fillRect(tam, 0, tam+1, h, 0x00FFFFFF);
tam++;
fillRect(tam, 0, tam+1, h, 0);
tam++;
fillRect(tam, 0, tam+1, h, 0x00FFFFFF);
tam++;
//Conteudo do Codigo de Barras
for(i = 0; i <= texto.length()-1; i++) {
    preto = Integer.parseInt(String.valueOf(texto.charAt(i)));
    branco = Integer.parseInt(String.valueOf(texto.charAt(i+1)));
    i++;
    for(j = 0; j < 5; j++) {
        if(String.valueOf(barras[preto].charAt(j)).equals("0")) {
            fillRect(tam, 0, tam + 1, h, 0);
            tam++;
        }
        else { fillRect(tam, 0, tam + 3, h, 0);
            tam+=3;
        }
        if(String.valueOf(barras[branco].charAt(j)).equals("0")) {
            fillRect(tam, 0, tam + 1, h, 0x00FFFFFF); tam++;
        }
        else {
            fillRect(tam, 0, tam + 3, h, 0x00FFFFFF); tam += 3;
        }
    }
}

//fim da barra = 0 = 10 / 1 = 0
fillRect(tam, 0, tam+3, h, 0);
tam+=3;
fillRect(tam, 0, tam+1, h, 0x00FFFFFF);
tam++;
fillRect(tam, 0, tam+1, h, 0);
tam++;

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
//GifEncoder encoder = new GifEncoder(BarImage ,outb);
//encoder.encode();
// ESSAS DUAS LINHAS ACIMA CRIARIAM UM .gif
out.close();
return true; }

void fillRect(int x0, int y0, int x1, int y1, int color)
{
    for (int x=x0 ; x < x1 ; x++){
      for (int y=y0 ; y < y1 ; y++){
         image.setRGB(x, y, color);
      }
    }
}
}

O kra, valeu mesmo!! Me quebro um GRANDE GALHO!!

Valeu ai!!

Abracao e te + :razz:

Cara, eu criei esta classe, mas não deu certodeu erro nos importes), meu caso eu preciso gerar um código de barras para cada aluno de uma eslo com base no codogo da matricula

dele que está no banco e não tenho menor ideia de como se faz issso!!!

SE alguem tiver um bom exemplo ou omas dicas , posta aeh galera to precisando de ajuda,

sera que eh possivel fazer isso???

Valeu a todos!!

daew carssolato,


import com.lowagie.text.pdf.Barcode;
import com.lowagie.text.pdf.BarcodeEAN;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;

import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.swing.JFrame;

/**
 *
 * @author Joe Loco
 */
public class BarcodeServlet extends HttpServlet {
   
  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
			
			
        
        OutputStream out = response.getOutputStream();
        try {
			if(request.getParameter("code")!=null) {// aki o maldito numero 
				response.setContentType("image/gif");
				Long code = new Long(request.getParameter("code"));
				Barcode b = new BarcodeEAN();
				b.setCodeType(Barcode.EAN13);
				b.setCode(BarCodeUtils.longToEan13(code));
				b.setBarHeight(50);				

				Image i = b.createAwtImage(new Color(0,0,0),new Color(255,255,255));			
				JFrame f = new JFrame();				
				BufferedImage bi = new BufferedImage(100,50, BufferedImage.TYPE_INT_RGB);								
				Graphics2D g = bi.createGraphics();   
				g.setBackground(new Color(255,255,255));
				g.clearRect(0,0,100,50);
				g.drawImage(i, 0, 0, f);			
				ImageIO.write(bi, "gif", out);			
			}
        } finally { 
            out.close();
        }
    } 

   
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

  
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
   
}

BarCodeUtils

public static Long ean13toLong(String barcode, String propertyName, boolean required) {
		if(barcode==null) {
			if(required) {
				throw new FormSetPropertyException("O campo " + propertyName + " deve ser preenchido", propertyName);
			} else {
				return null;
			}
		}
		
		if(barcode.length()>13) {
			throw new FormSetPropertyException("O campo " + propertyName + " deve estar no formato EAN13 e deve ter no máximo 13 caracteres", propertyName);
		} 		
		
		int dif = 13 - barcode.length();
		for(int i=0; i< dif ; i++) {			
			barcode = "0" + barcode;
		}		
		
		int[] digitos = new int[13];
		for(int i=0; i< 13 ; i++) {
			try {
				digitos[i] = Integer.parseInt(barcode.substring(i, i+1));
			} catch(Exception ex) {
				throw new FormSetPropertyException("O campo " + propertyName + " deve ser composto apenas por números", propertyName);
			}
		}
		
		int aux1 = digitos[1] + digitos[3] + digitos[5] + digitos[7] + digitos[9] + digitos[11];
		aux1 = aux1 * 3;
		
		int aux2 = digitos[0] + digitos[2] + digitos[4] + digitos[6] + digitos[8] + digitos[10];
		
		int aux3 = aux1 + aux2;		
		
		int aux4 = 10 - (aux3 % 10);
		if(aux4 == 10) {
			aux4 = 1;
		}


		if(digitos[12]!= aux4) {
			throw new FormSetPropertyException("O digito verificador do campo " + propertyName + " não confere", propertyName);
		}	
		
		return new Long(barcode.substring(0,12));
	}
	

	public static String longToEan13(Long codigo) {
		if(codigo==null) {
			return null;
		}
		String barcode = codigo.toString();
		
		int dif = 12 - barcode.length();
		for(int i=0; i< dif ; i++) {			
			barcode = "0" + barcode;
		}		
		
		int[] digitos = new int[12];
		for(int i=0; i< 12 ; i++) {			
			digitos[i] = Integer.parseInt(barcode.substring(i, i+1));
		}
		
		int aux1 = digitos[1] + digitos[3] + digitos[5] + digitos[7] + digitos[9] + digitos[11];
		aux1 = aux1 * 3;
		
		int aux2 = digitos[0] + digitos[2] + digitos[4] + digitos[6] + digitos[8] + digitos[10];
		
		int aux3 = aux1 + aux2;		
		
		int aux4 = 10 - (aux3 % 10);
		
		if(aux4 == 10) {
			aux4 = 1;
		}
		String retorno = barcode + aux4;
		
		System.out.println(retorno  + " - "  + retorno.length());
		return retorno;
	}