Sunday, March 29, 2015

How to create Bar Code in java (using aspose and itext) ?

Using aspose API.

For creating a Bar Code is very simple in java using aspose apis. We can use “aspose-barcode-5.4.2-jdk15.jar” for this.





Step 1: Create “BarCode.java” as a servlet. Within this class we have to create BarCodeBuilder object and set certain property to it and we will get the bar code image and later we will add this image as response in form of any image format and send it to the browser.

BarCode.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package p1;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.aspose.barcode.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import javax.imageio.ImageIO;

public class BarCode extends HttpServlet
{
   public void doGet(
        HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException
    {
        System.out.println("bar code servlet");
        // Create BarCodeBuilder instance
        BarCodeBuilder b = new BarCodeBuilder();
        // Set up symboogy
        b.setSymbologyType(Symbology.Code128);
        // Set up code text
        b.setCodeText("12345678");
        
        b.setCodeLocation(CodeLocation.None);
        
        // Render barcode
        BufferedImage image = b.getBarCodeImage();

        response.setContentType("image/png");
        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
        outputStream.close();
    }

}

Step 2: Add the entry into web.xml.

web.xml

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>AllPOC</display-name>
    <servlet>
        <servlet-name>BarCode</servlet-name>
        <servlet-class>p1.BarCode</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>BarCode</servlet-name>
        <url-pattern>/BarCode</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

Step 3: Create jsp page. And use <img src="http://localhost:8084/AllPOC/BarCode" /> for rendering the Bar code at appropriate page.

BarCodeCreator.jsp

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Bar Code</title>
    </head>
    <body>
        This is a barcode image generated by servlet:
        <br />
        <img src="http://localhost:8084/AllPOC/BarCode" />
    </body>
</html>

Note: We can customize the Bar code as per our requirement. 

A) Bar Code Alignment. 
1- If you don’t want to show the code as part of barcode use b.setCodeLocation(CodeLocation.None); or b.setCodeLocation(2);
2- If you want to display the code top of bar code use b.setCodeLocation(CodeLocation.Above); or b.setCodeLocation(0);
3- If you want to display the code bottom of bar code use b.setCodeLocation(CodeLocation.Below); or b.setCodeLocation(1);

B) Bar Code pattern . 
There are so many style for bar code you can change the Symbology to obtain the different - different style.  There are 48 type of Bar code available you just use any one of them using-

b.setSymbologyType(Symbology.Code128); 

Instead of Code128 you can choose any one from below. 
1-    Codabar
2-    Code11
3-    Code39Standard 
4-    Code39Extended 
5-    Code93Standard 
6-    Code93Extended 
7-    Code128 
8-    EAN8
9-    EAN13 
10-    EAN128 
11-    EAN14 
12-    SCC14 
13-    SSCC18 
14-    UPCA 
15-    UPCE 
16-    BooklandEAN 
17-    Standard2of5 
18-    Interleaved2of5 
19-    Matrix2of5 
20-    ItalianPost25 
21-    IATA2of5 
22-    ITF14 
23-    ITF6 
24-    MSI 
25-    VIN 
26-    DeutschePostIdentcode 
27-    DeutschePostLeitcode
28-    OPC 
29-    PZN 
30-    Pharmacode
31-    DataMatrix 
32-    QR 
33-    Aztec 
34-    Pdf417 
35-    MacroPdf417 
36-    AustraliaPost 
37-    Postnet 
38-    Planet 
39-    OneCode 
40-    RM4SCC 
41-    DatabarOmniDirectional 
42-    DatabarTruncated 
43-    DatabarLimited 
44-    DatabarExpanded 
45-    SingaporePost 
46-    GS1DataMatrix 
47-    AustralianPosteParcel 
48-    SwissPostParcel

Some of the code and related bar code is given below-



Store the the Bar Code into PDF.

If you want to store BarCode in pdf file use below program using itext apis using  “itext-1.3.jar”. In this program you need not to use aspose apis.

BarCode128.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package p1;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.Barcode128;
import com.lowagie.text.pdf.PdfWriter;

public class BarCode128 {

    public static void main(String[] args) throws FileNotFoundException, DocumentException {

        Document document = new Document(new Rectangle(PageSize.A4));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("h:/a2z_BarCode_128.pdf"));

        document.open();
        document.add(new Paragraph("Generated Bar Code"));

        Barcode128 code128 = new Barcode128();
        code128.setGenerateChecksum(true);
        code128.setCode("ram123");

        document.add(code128.createImageWithBarcode(writer.getDirectContent(), null, null));
        document.close();

        System.out.println("Bar code generated.");
    }
}

You will get Generated PDF with Bar Code


Note : You can verified your generated bar code whether it’s correct or not using below url :
           http://www.onlinebarcodereader.com/

open this url browser you bar code and click on send file you will get you code and bar code format name as well



Answer 2: Using itext apis ?

Step 1: Create servlet BarCodeServlet.java

BarCodeServlet.java

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package p1;

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;

public class BarcodeServlet extends HttpServlet {

    
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
       byte[] pngImageData = null;
        System.out.println(1);
        try {
            Barcode39 code39ext = new Barcode39();
            code39ext.setCode("Testing Text");
            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");
        }
    }
}

Step 2: Add entries into web.xml.

web.xml

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>BarcodeServlet</servlet-name>
        <servlet-class>p1.BarcodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>BarcodeServlet</servlet-name>
        <url-pattern>/BarcodeServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

Step 3: Create BarCodeCreator.jsp

BarCodeCreator.jsp


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Bar Code</title>
    </head>
    <body>
        This is a barcode image generated by servlet:
        <br />
        <img src="http://localhost:8084/AllPOC/BarcodeServlet" />
    </body>
</html>

The output of this program is same as above one.

Note : The itext apis are open source.

No comments :

Post a Comment