BMP to PDF Java Servlet Example - iText Tutorial

In this tutorial, we will extend the servlet code provided in the Gif to Pdf servlet tutorial, to support BMP to PDF conversion using iText library. The input to the servlet will be through a HTML form, where a user uploads a BMP file and the servlet will take care of converting the BMP image into a PDF document and stream it back to the browser. With this, the servlet code will be capable of handling the following conversions:
TIFF to PDF conversion
JPEG to PDF conversion
GIF to PDF conversion (all frames or first frame)
BMP to PDF conversion
We are slowly building an integrated image conversion servlet using iText, capable of handling any image extension type and stamp it to PDF. That is a bit far away, so we will keep ourselves satisfied with bitmap conversion now.I would recommend the readers to go through the base servlet code linked earlier, to get a feel of how the code is structured, if you are jumping right from the internet to this post. This post will focus on bitmap conversion alone. Code example to extend our servlet to support this change is provided below;

Step-1: Update your index.jsp file and add an option in the form drop down conversion type to support bmp to pdf. The code area to be modified is provided below;
  <select name="convertTo" id="convertTo" onChange="javascript:enableField()">
      <option>Tiff2Pdf</option>
      <option>Jpeg2Pdf</option>
      <option>Gif2Pdf</option> <!-- New Option to Capture Gif2Pdf conversion -->
      <option>Bmp2Pdf</option> <!-- Option to support BMP to PDF conversion -->
  </select><br></br>
Step-2: The change made in Step-2 will help to provide the servlet code an instruction to change the BMP image to PDF and render it back to the user. This option needs to be supported by an equivalent server side code which will render the PDF back to the user. The code snippet to be added in the servlet is provided below;
            //Check if the User has opted for Bmp2Pdf at the page
            //Bmp 2 PDF servlet example
            if (conversionType.equals("Bmp2Pdf")){
               Image tempImage=BmpImage.getImage(FilePath);                     
               document.add(tempImage);
            }
Now, before running this code, you will have to add the following import declaration as this is required for the conversion to work properly.
import com.itextpdf.text.pdf.codec.BmpImage;
A screendump of the FORM page from where the user uploads a BMP image is shown below;
BMP to PDF Conversion
BMP to PDF Conversion
The complete servlet image conversion code would be provided after we address all image formats. In the meantime, you can use the example link provide above and insert this code snippet to achieve BMP conversion.

No comments:

Post a Comment