Ai WC, segue um explo de c�digo de
barras no modelo da febraban
"interliv 2/5".
No main gera-se c�digo de
barra da String
barras.
Boa Sorte
Daniel Shimura Goldszmit.
//package barcode;
import
com.sun.image.codec.jpeg.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* A class that produces a Barcode component.
*/
public class BarCode2of5 extends Canvas {
* A class that produces a Barcode component.
*/
public class BarCode2of5 extends Canvas {
private static String
alphabet2of5 = "0123456789";
private static String coded2of5Char[] = {"00110", "10001", "01001", "11000",
"00101", "10100", "01100", "00011",
"10010", "01010"};
private static String coded2of5Char[] = {"00110", "10001", "01001", "11000",
"00101", "10100", "01100", "00011",
"10010", "01010"};
/** Constant for variant of
the code. */
public static final int CODE2OF5 = 0;
public static final int CODE2OF5 = 0;
/** Constant for variant of
the code. */
public static final int CODE2OF5CHK = 1;
public static final int CODE2OF5CHK = 1;
/** Constant for size of the
narrowest bar. */
public static final int SMALL = 1;
public static final int SMALL = 1;
/** Costant for size of the
narrowest bar. */
public static final int MEDIUM = 2;
public static final int MEDIUM = 2;
/** Constant for size of the
narrowest bar. */
public static final int LARGE = 3;
public static final int LARGE = 3;
/** Constant for text
alignment. */
public static final int BASELINE = 0;
public static final int BASELINE = 0;
/** Constant for text
alignment. */
public static final int MIDDLELINE = 1;
public static final int MIDDLELINE = 1;
/** Constant for text
alignment. */
public static final int TOPLINE = 2;
private static final int DEFWIDTH = 50;
private static final int DEFHEIGHT = 25;
private static final boolean DEFTEXTINS = true;
private static final int DEFSIZE = 1;
private static final Color DEFBACKCOLOR;
private static final Color DEFFORECOLOR;
private static final Font DEFFONT = new Font("Courier", 0, 12);
private String strStartPattern;
private String strStopPattern;
private double wideToNarrowRatio;
private double marginWidth;
private double marginHeight;
private double labelLength;
private double labelHeight;
private String stringToEncode;
private String filledStringToEncode;
private String encodedString;
private int narrowestDim;
private boolean textInside;
private int style;
private int initialWidth;
private int initialHeight;
private Color backColor;
private Color foreColor;
private Font font;
private int textAlign;
public static final int TOPLINE = 2;
private static final int DEFWIDTH = 50;
private static final int DEFHEIGHT = 25;
private static final boolean DEFTEXTINS = true;
private static final int DEFSIZE = 1;
private static final Color DEFBACKCOLOR;
private static final Color DEFFORECOLOR;
private static final Font DEFFONT = new Font("Courier", 0, 12);
private String strStartPattern;
private String strStopPattern;
private double wideToNarrowRatio;
private double marginWidth;
private double marginHeight;
private double labelLength;
private double labelHeight;
private String stringToEncode;
private String filledStringToEncode;
private String encodedString;
private int narrowestDim;
private boolean textInside;
private int style;
private int initialWidth;
private int initialHeight;
private Color backColor;
private Color foreColor;
private Font font;
private int textAlign;
static {
DEFBACKCOLOR = Color.white;
DEFFORECOLOR = Color.black;
}
DEFBACKCOLOR = Color.white;
DEFFORECOLOR = Color.black;
}
/**
* <P>Constructs a Barcode object with an empty string and the following defaults:
* <BR>size 100x50;
* <BR>label inside;
* <BR>small rendering;
* <BR>black on white color;
* <BR>Courier,12 font;
*/
public BarCode2of5() {
this("012345", 50, 25, 1, 0, true, DEFBACKCOLOR, DEFFORECOLOR, DEFFONT, 2);
}
* <P>Constructs a Barcode object with an empty string and the following defaults:
* <BR>size 100x50;
* <BR>label inside;
* <BR>small rendering;
* <BR>black on white color;
* <BR>Courier,12 font;
*/
public BarCode2of5() {
this("012345", 50, 25, 1, 0, true, DEFBACKCOLOR, DEFFORECOLOR, DEFFONT, 2);
}
private BarCode2of5(String s,
int i, int j, int k, int l, boolean
flag,
Color color, Color color1, Font font1, int i1) {
strStartPattern = "0000";
strStopPattern = "100";
//wideToNarrowRatio = 3D;
wideToNarrowRatio = 2D; //*******
stringToEncode = "";
filledStringToEncode = "";
encodedString = "";
narrowestDim = 1;
textInside = true;
> initialWidth = 50;
initialHeight = 25;
backColor = DEFBACKCOLOR;
foreColor = DEFFORECOLOR;
font = DEFFONT;
textAlign = 1;
stringToEncode = s;
narrowestDim = k;
initialWidth = i;
initialHeight = j;
textInside = flag;
> backColor = color;
foreColor = color1;
font = font1;
textAlign = i1;
Encode();
}
Color color, Color color1, Font font1, int i1) {
strStartPattern = "0000";
strStopPattern = "100";
//wideToNarrowRatio = 3D;
wideToNarrowRatio = 2D; //*******
stringToEncode = "";
filledStringToEncode = "";
encodedString = "";
narrowestDim = 1;
textInside = true;
> initialWidth = 50;
initialHeight = 25;
backColor = DEFBACKCOLOR;
foreColor = DEFFORECOLOR;
font = DEFFONT;
textAlign = 1;
stringToEncode = s;
narrowestDim = k;
initialWidth = i;
initialHeight = j;
textInside = flag;
> backColor = color;
foreColor = color1;
font = font1;
textAlign = i1;
Encode();
}
/////////////////////////////////////////////////////////////////////////////
// Public methods
/////////////////////////////////////////////////////////////////////////////
// Public methods
/////////////////////////////////////////////////////////////////////////////
/**
* Returns the mininimum size of this component.
*/
public Dimension getMinimumSize() {
return minimumSize();
}
* Returns the mininimum size of this component.
*/
public Dimension getMinimumSize() {
return minimumSize();
}
/**
* Returns the minimum size of this component.
*/
public Dimension minimumSize() {
Dimension dimension = new Dimension(initialWidth, initialHeight);
return dimension;
}
* Returns the minimum size of this component.
*/
public Dimension minimumSize() {
Dimension dimension = new Dimension(initialWidth, initialHeight);
return dimension;
}
public Dimension
getPreferredSize() {
return preferredSize();
}
return preferredSize();
}
public Dimension
preferredSize() {
return minimumSize();
}
return minimumSize();
}
public void setSize(int i, int
j) {
initialWidth = i;
initialHeight = j;
super.setSize(i, j);
repaint();
}
initialWidth = i;
initialHeight = j;
super.setSize(i, j);
repaint();
}
public void setSize(Dimension
dimension) {
initialWidth = dimension.width;
initialHeight = dimension.height;
super.setSize(dimension.width, dimension.height);
repaint();
}
initialWidth = dimension.width;
initialHeight = dimension.height;
super.setSize(dimension.width, dimension.height);
repaint();
}
public String toString()
{
return getClass().getName() + "[" + paramString() + "]";
}
return getClass().getName() + "[" + paramString() + "]";
}
public Dimension
requestedMinimunSize(String s) {
int i = s.length() * 16 * narrowestDim + 31 * narrowestDim;
if( 1)
i += 16 * narrowestDim;
int j = Math.max((int)(0.14999999999999999D * (double)i), 35);
return new Dimension(i, j);
}
int i = s.length() * 16 * narrowestDim + 31 * narrowestDim;
if( 1)
i += 16 * narrowestDim;
int j = Math.max((int)(0.14999999999999999D * (double)i), 35);
return new Dimension(i, j);
}
public void setString(String
s) throws IllegalArgumentException {
stringToEncode = s;
stringValidate();
Encode();
}
stringToEncode = s;
stringValidate();
Encode();
}
public String getString()
{
return stringToEncode;
}
return stringToEncode;
}
public void setDimension(int
i) {
switch(i) {
case 1: // '\001'
case 2: // '\002'
case 3: // '\003'
narrowestDim = i;
repaint();
return;
}
narrowestDim = 1;
repaint();
}
switch(i) {
case 1: // '\001'
case 2: // '\002'
case 3: // '\003'
narrowestDim = i;
repaint();
return;
}
narrowestDim = 1;
repaint();
}
public int getDimension()
{
return narrowestDim;
}
return narrowestDim;
}
public void
setTextInside(boolean flag) {
textInside = flag;
repaint();
}
textInside = flag;
repaint();
}
public boolean isTextInside()
{
return textInside;
}
return textInside;
}
public void setStyle(int i)
{
switch(i) {
case 0: // '\0'
case 1: // '\001'
> Encode();
return;
}
> Encode();
}
switch(i) {
case 0: // '\0'
case 1: // '\001'
> Encode();
return;
}
> Encode();
}
public int getStyle()
{
return style;
}
return style;
}
public void
setBackground(Color color) {
backColor = color;
repaint();
}
backColor = color;
repaint();
}
public Color getBackground()
{
return backColor;
}
return backColor;
}
public void
setForeground(Color color) {
foreColor = color;
repaint();
}
foreColor = color;
repaint();
}
public Color getForeground()
{
return foreColor;
}
return foreColor;
}
public void setFont(Font
font1) {
font = font1;
repaint();
}
font = font1;
repaint();
}
public Font getFont()
{
return font;
}
return font;
}
public void setTextAlign(int
i) {
switch(i) {
case 0: // '\0'
case 1: // '\001'
case 2: // '\002'
textAlign = i;
repaint();
return;
}
textAlign = 1;
repaint();
}
switch(i) {
case 0: // '\0'
case 1: // '\001'
case 2: // '\002'
textAlign = i;
repaint();
return;
}
textAlign = 1;
repaint();
}
public int getTextAlign()
{
return textAlign;
}
return textAlign;
}
public synchronized void
paint(Graphics g) {
int i = getSize().width;
int j = getSize().height;
g.setFont(font);
FontMetrics fontmetrics = g.getFontMetrics(font);
int k = fontmetrics.getAscent();
labelLength = filledStringToEncode.length() * 8 * narrowestDim;
//marginWidth = ((double)i - labelLength) / 2D;
//marginHeight = ((double)j - labelLength) / 2D;
marginWidth = 0;
marginHeight = 0;
if(textInside) {
if(textAlign == 0) {
labelHeight = j;
}
int i = getSize().width;
int j = getSize().height;
g.setFont(font);
FontMetrics fontmetrics = g.getFontMetrics(font);
int k = fontmetrics.getAscent();
labelLength = filledStringToEncode.length() * 8 * narrowestDim;
//marginWidth = ((double)i - labelLength) / 2D;
//marginHeight = ((double)j - labelLength) / 2D;
marginWidth = 0;
marginHeight = 0;
if(textInside) {
if(textAlign == 0) {
labelHeight = j;
}
if(textAlign == 1) {
labelHeight = j - k / 2;
}
labelHeight = j - k / 2;
}
if(textAlign == 2) {
labelHeight = j - k;
}
}
else {
labelHeight = j;
}
labelHeight = j - k;
}
}
else {
labelHeight = j;
}
g.setColor(backColor);
g.fillRect(0, 0, i, j);
int l = encodedString.length();
int i1 = 0;
int j1 = 0;
int k1 = 0;
int l1 = 0;
boolean flag = false;
i1 = (int)marginWidth;
j1 = 0;
k1 = 0;
l1 = 0;
for(int j2 = 0; j2 < l; j2++) {
if(j2 % 2 == 0) {
g.setColor(foreColor);
}
else {
g.setColor(backColor);
}
g.fillRect(0, 0, i, j);
int l = encodedString.length();
int i1 = 0;
int j1 = 0;
int k1 = 0;
int l1 = 0;
boolean flag = false;
i1 = (int)marginWidth;
j1 = 0;
k1 = 0;
l1 = 0;
for(int j2 = 0; j2 < l; j2++) {
if(j2 % 2 == 0) {
g.setColor(foreColor);
}
else {
g.setColor(backColor);
}
int
i2;
if(encodedString.charAt(j2) == '1') {
i2 = (int)((double)narrowestDim * wideToNarrowRatio);
}
else {
i2 = narrowestDim;
}
g.fillRect(k1 + i1, l1 + j1, i2, (int)labelHeight);
k1 += i2;
} //************
if(encodedString.charAt(j2) == '1') {
i2 = (int)((double)narrowestDim * wideToNarrowRatio);
}
else {
i2 = narrowestDim;
}
g.fillRect(k1 + i1, l1 + j1, i2, (int)labelHeight);
k1 += i2;
} //************
if(textInside)
{
int k2 = fontmetrics.stringWidth(filledStringToEncode);
int l2 = getSize().height;
int i3 = (int)((marginWidth + labelLength / 2D) - (double)(k2 / 2));
g.setColor(backColor);
g.fillRect(i3, l2 - k, k2, k);
g.setColor(foreColor);
g.drawString(filledStringToEncode, i3, l2);
}
}
int k2 = fontmetrics.stringWidth(filledStringToEncode);
int l2 = getSize().height;
int i3 = (int)((marginWidth + labelLength / 2D) - (double)(k2 / 2));
g.setColor(backColor);
g.fillRect(i3, l2 - k, k2, k);
g.setColor(foreColor);
g.drawString(filledStringToEncode, i3, l2);
}
}
/////////////////////////////////////////////////////////////////////////////
// Protected methods
/////////////////////////////////////////////////////////////////////////////
// Protected methods
/////////////////////////////////////////////////////////////////////////////
protected String paramString()
{
String s = filledStringToEncode + "," + initialWidth + "x" + initialHeight;
return s;
}
String s = filledStringToEncode + "," + initialWidth + "x" + initialHeight;
return s;
}
/////////////////////////////////////////////////////////////////////////////
// Private methods
/////////////////////////////////////////////////////////////////////////////
// Private methods
/////////////////////////////////////////////////////////////////////////////
private void stringValidate()
throws IllegalArgumentException {
int i = stringToEncode.length();
for(int j = 0; j < i; j++) {
if(alphabet2of5.indexOf(stringToEncode.charAt(j)) == -1) {
throw new IllegalArgumentException("only digits for 2of5 code");
}
}
}
int i = stringToEncode.length();
for(int j = 0; j < i; j++) {
if(alphabet2of5.indexOf(stringToEncode.charAt(j)) == -1) {
throw new IllegalArgumentException("only digits for 2of5 code");
}
}
}
private char
addCheckChar(String s) {
int i = 0;
int j = 0;
int l = 0;
int k = 0;
int i1 = s.length();
for(int j1 = 0; j1 < i1; j1++) {
if(j1 % 2 == 0) {
l += alphabet2of5.indexOf(stringToEncode.charAt(j1));
}
else {
k += alphabet2of5.indexOf(stringToEncode.charAt(j1));
}
}
int i = 0;
int j = 0;
int l = 0;
int k = 0;
int i1 = s.length();
for(int j1 = 0; j1 < i1; j1++) {
if(j1 % 2 == 0) {
l += alphabet2of5.indexOf(stringToEncode.charAt(j1));
}
else {
k += alphabet2of5.indexOf(stringToEncode.charAt(j1));
}
}
if(i1 % 2 == 0)
{
i = l;
j = k;
}
else {
i = k;
j = l;
}
i = l;
j = k;
}
else {
i = k;
j = l;
}
j *=
3;
j += i;
if(j % 10 == 0) {
return alphabet2of5.charAt(0);
}
else {
return alphabet2of5.charAt(10 - j % 10);
}
}
j += i;
if(j % 10 == 0) {
return alphabet2of5.charAt(0);
}
else {
return alphabet2of5.charAt(10 - j % 10);
}
}
private void Encode()
{
filledStringToEncode = new String(stringToEncode);
filledStringToEncode = new String(stringToEncode);
if( 1)
{
filledStringToEncode += addCheckChar(stringToEncode);
}
filledStringToEncode += addCheckChar(stringToEncode);
}
if(filledStringToEncode.length() % 2 != 0)
{
filledStringToEncode = "0" + filledStringToEncode;
}
filledStringToEncode = "0" + filledStringToEncode;
}
StringBuffer
stringbuffer = new StringBuffer();
for(int i = 0; i < filledStringToEncode.length(); i += 2) {
stringbuffer.append(funInterleave(filledStringToEncode.charAt(i), filledStringToEncode.charAt(i + 1)));
}
for(int i = 0; i < filledStringToEncode.length(); i += 2) {
stringbuffer.append(funInterleave(filledStringToEncode.charAt(i), filledStringToEncode.charAt(i + 1)));
}
encodedString =
stringbuffer.toString();
encodedString = strStartPattern + stringbuffer.toString();
encodedString += strStopPattern;
repaint();
}
encodedString = strStartPattern + stringbuffer.toString();
encodedString += strStopPattern;
repaint();
}
private String
funInterleave(char c, char c1) {
StringBuffer stringbuffer = new StringBuffer();
for(int i = 0; i < 5; i++) {
stringbuffer.append(coded2of5Char[alphabet2of5.indexOf(c)].charAt(i));
stringbuffer.append(coded2of5Char[alphabet2of5.indexOf(c1)].charAt(i));
}
StringBuffer stringbuffer = new StringBuffer();
for(int i = 0; i < 5; i++) {
stringbuffer.append(coded2of5Char[alphabet2of5.indexOf(c)].charAt(i));
stringbuffer.append(coded2of5Char[alphabet2of5.indexOf(c1)].charAt(i));
}
return
stringbuffer.toString();
}
}
/**
* Constr�i uma imagem contendo o c�digo de barra.
* <p>
* @param Stream onde ser� retornada a imagem
* @param Codigo que dar� origem a imagem
* <p>
* @return imagem no formato stream
*/
public void createBarCode(OutputStream imageStream, String codigo) {
* Constr�i uma imagem contendo o c�digo de barra.
* <p>
* @param Stream onde ser� retornada a imagem
* @param Codigo que dar� origem a imagem
* <p>
* @return imagem no formato stream
*/
public void createBarCode(OutputStream imageStream, String codigo) {
this.setDimension
(BarCode2of5.SMALL);
//this.setTextInside (true);
this.setTextInside (false);
this.setStyle (BarCode2of5.CODE2OF5);
this.setForeground (Color.black);
this.setTextAlign (BarCode2of5.TOPLINE);
//this.setTextInside (true);
this.setTextInside (false);
this.setStyle (BarCode2of5.CODE2OF5);
this.setForeground (Color.black);
this.setTextAlign (BarCode2of5.TOPLINE);
this.setSize(360,
35);
// this.setSize(360, 45);
// this.setSize(360, 45);
try
{
this.setString(codigo);
}
catch (Exception e){
e.printStackTrace(System.err);
throw new RuntimeException("Erro ao configurar o C�digo de Barras: \n"
+e.getMessage());
}
this.setString(codigo);
}
catch (Exception e){
e.printStackTrace(System.err);
throw new RuntimeException("Erro ao configurar o C�digo de Barras: \n"
+e.getMessage());
}
try {
BufferedImage image = createComponentImage(this);
JPEGImageEncoder jpegEncoder =
JPEGCodec.createJPEGEncoder(imageStream);
JPEGEncodeParam param = jpegEncoder.getDefaultJPEGEncodeParam(image);
JPEGEncodeParam param = jpegEncoder.getDefaultJPEGEncodeParam(image);
param.setQuality(1.0f, true);
jpegEncoder.setJPEGEncodeParam(param);
jpegEncoder.setJPEGEncodeParam(param);
jpegEncoder.encode(image);
imageStream.flush();
imageStream.close();
}
catch(IOException e) {
e.printStackTrace(System.err);
throw new RuntimeException("Erro na gera��o da imagem do C�digo de Barras: \n"
+e.getMessage());
}
imageStream.close();
}
catch(IOException e) {
e.printStackTrace(System.err);
throw new RuntimeException("Erro na gera��o da imagem do C�digo de Barras: \n"
+e.getMessage());
}
}
/**
* Cosntr�i uma imagem conforme o componente informado.
*
* @param component desenho que ser� transformado
* @return imagem desenhada
*/
private BufferedImage createComponentImage(Component component) {
Rectangle rect = component.getBounds();
* Cosntr�i uma imagem conforme o componente informado.
*
* @param component desenho que ser� transformado
* @return imagem desenhada
*/
private BufferedImage createComponentImage(Component component) {
Rectangle rect = component.getBounds();
BufferedImage
image = new
BufferedImage(rect.width
,rect.height
,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
,rect.height
,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
//write to the
image
component.paint(g);
component.paint(g);
//dispose of the
graphics content
g.dispose();
g.dispose();
return
image;
}
}
public static void main (String[] args){
BarCode2of5 bc = new BarCode2of5();
try
{
BufferedOutputStream buffer =
new BufferedOutputStream (
new FileOutputStream("bc1.jpg")
);
//bc.createBarCode(buffer,"9876543");
//bc.createBarCode(buffer,"001052589224");
String barras="3333111111222223333332222222323233232323232323";
bc.createBarCode(buffer,barras);
} catch (Exception e){
e.printStackTrace(System.err);
throw new RuntimeException(e.getLocalizedMessage());
} finally {
System.out.println ("*** FIM !! :) ***");
}
System.exit(0);
BufferedOutputStream buffer =
new BufferedOutputStream (
new FileOutputStream("bc1.jpg")
);
//bc.createBarCode(buffer,"9876543");
//bc.createBarCode(buffer,"001052589224");
String barras="3333111111222223333332222222323233232323232323";
bc.createBarCode(buffer,barras);
} catch (Exception e){
e.printStackTrace(System.err);
throw new RuntimeException(e.getLocalizedMessage());
} finally {
System.out.println ("*** FIM !! :) ***");
}
System.exit(0);
}
}
-----Original Message-----
From: f�bio valen�a [mailto:[EMAIL PROTECTED]
Sent: segunda-feira, 24 de fevereiro de 2003 07:49
To: [EMAIL PROTECTED]
Subject: Re: [java-list] C�digo de BarrasCara, eu j� tive de fazer isso, o que vc deve fazer � primeiramente entrar no site da febraban, e procurar algo sobre "interliv 2/5" esse � o padr�o de c�digo de barras para boletos banc�rios, e leia com bastante aten��o por que o documento � meio chato de se entender.
Qualquer coisa e-mailme!
Wellerson Costa <[EMAIL PROTECTED]> wrote:
Estou precisando colocar em uma aplica��o c�digos de barras para impress�o
de boletos banc�rios... N�o tenho id�ia de como fazer isto...
Alg�em poderia me ajudar...Onde encontro literaturas sobre tal assunto?
Atenciosamente,
Wellerson Costa
_________________________________________________________________
MSN Hotmail, o maior webmail do Brasil. http://www.hotmail.com
------------------------------ LISTA SOUJAVA ----------------------------
http://www.soujava.org.br - Sociedade de Usu�rios Java da Sucesu-SP
d�vidas mais comuns: http://www.soujava.org.br/faq.htm
regras da lista: http://www.soujava.org.br/regras.htm
historico: http://www.mail-archive.com/java-list%40soujava.org.br
para sair da lista: envie email para [EMAIL PROTECTED]
-------------------------------------------------------------------------
Busca Yahoo!
O servi�o de busca mais completo da Internet. O que voc� pensar o Yahoo! encontra.
