Convert BMP to PDF iText Java Example Tutorial

In this iText image conversion tutorial, we will explain how to convert a bitmap (BMP) image file into a PDF document using iText Java API. This example would be driven with a standalone Java program, later we will provide a servlet integration example where a user uploaded bitmap picture would be changed to a PDF using a Java servlet.I will be using iText 5.1.0 for this example, if you are planning to use a older version of iText, make sure you modify the import declarations accordingly. We will be making use of the following class in iText API to read a BMP image into "Image" class : com.itextpdf.text.pdf.codec.BmpImage. The complete Java code example is provided below;
//We need the library below to write the final PDF file which has our image converted to PDF
import java.io.FileOutputStream;
//The image class which will hold the bitmap image
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Document;
//This class is required to read image into Image object
import com.itextpdf.text.pdf.codec.BmpImage;
public class BmpToPDF {
public static void main(String[] args) {
try{
    //Create Document Object
    Document convertBmpToPdf=new Document();
    //Create PdfWriter for Document to hold physical file
    PdfWriter.getInstance(convertBmpToPdf, new FileOutputStream("c:\\java\\ConvertImagetoPDF.pdf"));
    convertBmpToPdf.open();
    //Get the Bitmap image to Convert to PDF
    //getImage is a static method, does not require object
    Image convertBmp=BmpImage.getImage("c:\\java\\test.bmp");
    //Add image to Document
    convertBmpToPdf.add(convertBmp);
    //Close Document
    convertBmpToPdf.close();
    System.out.println("Successfully Converted BMP to PDF in iText");
}
catch (Exception i1){
    i1.printStackTrace();
}
}
}
Now, for testing purposes, I had a 65 Kb Bitmap image file and it got converted to a PDF.The size of the PDF came around 3 Kb, which is a significant reduction in file size as well. I feel that Bitmap image is either converted / compressed before stamping it into the PDF. We will see more servlet based examples of image conversion using iText in upcoming posts.

1 comment:

  1. getting below error, used
    below dependencies

    itextpdf-5.4.0
    itextpdf-5.4.0
    system
    4
    ${basedir}/src/main/webapp/WEB-INF/lib/itextpdf-5.4.0.jar


    com.itextpdf.tool
    xmlworker
    5.5.11


    java.lang.RuntimeException: BMP version 5 not implemented yet.
    at com.itextpdf.text.pdf.codec.BmpImage.process(BmpImage.java:581)
    at com.itextpdf.text.pdf.codec.BmpImage.(BmpImage.java:170)
    at com.itextpdf.text.pdf.codec.BmpImage.getImage(BmpImage.java:211)
    at com.itextpdf.text.pdf.codec.BmpImage.getImage(BmpImage.java:199)
    at com.itextpdf.text.pdf.codec.BmpImage.getImage(BmpImage.java:182)
    at com.itextpdf.text.pdf.codec.BmpImage.getImage(BmpImage.java:229)

    ReplyDelete