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
//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) {
    //Create Document Object
    Document convertBmpToPdf=new Document();
    //Create PdfWriter for Document to hold physical file
    PdfWriter.getInstance(convertBmpToPdf, new FileOutputStream("c:\\java\\ConvertImagetoPDF.pdf"));;
    //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
    //Close Document
    System.out.println("Successfully Converted BMP to PDF in iText");
catch (Exception i1){
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.

No comments:

Post a Comment