Convert Tiff to PDF Java Servlet Example Tutorial

In this tutorial, we will provide a Java Servlet that can accept a user uploaded Tiff Image file and convert this Tiff image to a PDF and render it back to the browser from where the request was placed.In order to write this servlet code, we would need a jsp page that can accept a file uploaded by the user. Once the uploaded image is submitted to the server, we will have to write some code at the servlet to accept the incoming file and use iText to convert this Tiff image to PDF. This PDF can be streamed back to the browser, which will then open the PDF using Adobe PDF plugins. This does not look that complex,if you know a bit of servlet programming. Even if you are beginner, don't worry. This tutorial can help you to understand and get going quite easily. Now, for this tutorial, you can use any IDE of your choice. But, you would need the following JAR files as listed below;
itextpdf-5.1.0 - iText to write the PDF file
com.oreilly.servlet package - We need this package to process the uploaded file at the server
First, let us construct a simple JSP file which will accept a user uploaded Tiff image through a FORM. The JSP code (index.jsp) is provided below;
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>My Upload Page</title>
    </head>
    <body>
  <h1>Upload a Tiff Image which will be Converted to PDF File</h1>        
  <form action="Tiff2Pdf" method="post" enctype="multipart/form-data" name="productForm" id="productForm">  
  <input type="file" name="file" id="file">
  <input type="submit" name="Submit" value="Submit">
  </form>
    </body>
</html>
If you look at the code above, we create a FORM that will post the uploaded image to a servlet "Tiff2Pdf". The form contains a file placeholder to accept a user uploaded file. It also contains a submit button to submit the uploaded image to the server. A screenshot of how this form will look on the browser is provided below;

Tiff to PDF conversion through Servlet
Tiff to PDF conversion through Servlet
We will now write the servlet end code to handle an uploaded Tiff image. The commented servlet code is provided below;
package com.convertImage;
import java.io.IOException;
import java.io.OutputStream; // to write the PDF
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;//hold user uploaded Tiff File
import com.itextpdf.text.pdf.codec.TiffImage; // Read Tiff file for Processing
import com.itextpdf.text.Image; //Extract images from Tiff File
import com.itextpdf.text.pdf.PdfWriter; // write PDF 
import com.itextpdf.text.Document;//Logical PDF object
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.DocumentException;
import com.oreilly.servlet.MultipartRequest;//To save uploaded Tiff file for processing
public class Tiff2Pdf extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/pdf");
         OutputStream out=response.getOutputStream();
        try {
            //Save uploaded Tiff file to server
            MultipartRequest myrequest=new MultipartRequest(request,"c:\\test");            
            //Create Document object
            Document document = new Document();            
            // Create PdfWriter instance to response output stream
            PdfWriter.getInstance(document, out);
            //Open Document Object
            document.open();
            document.add(new Paragraph("Welcome, Your Tiff Image Converted to PDF, Save the File"));
            document.add(new Paragraph("PDF Produced by Converting Tiff to PDF as Servlet"));            
            //Get uploaded image path in string variable
            String FilePath=myrequest.getFile("file").getAbsolutePath();
            //Start readig the Tiff image 
            RandomAccessFileOrArray myTiffFile=new RandomAccessFileOrArray(FilePath);
            //Get number of pages
            int numberOfPages=TiffImage.getNumberOfPages(myTiffFile);
            //Extract each page and add to Document
            for(int i=1;i<=numberOfPages;i++){
            Image tempImage=TiffImage.getTiffImage(myTiffFile, i);
            document.add(tempImage);
            }
            document.close();
                       
        }  catch (DocumentException exc){
                throw new IOException(exc.getMessage());
                }
        finally {            
            out.close(); //Return PDF back to browser
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    public String getServletInfo() {
        return "Short description";
    }// 
}
All you have to do now is to deploy the servlet on your favorite web server (I used Glassfish Server 3.1) and then run the JSP file. If you have done all the configuration correctly, you will get a Tiff image converted to PDF and viewed on your browser. We will see a working demonstration of this code in the next tutorial. We will also discuss some exceptions you may get while executing this code, and how to fix them.

4 comments:

  1. Thanks for sharing the information that how convert Tiff file to Pdf. It is so informative blog!!


    Tiff Converter

    ReplyDelete
  2. i am working on eclipse ...server-tomcat
    servlet configuration is not supported ..shows a lot of error for the above code pls help

    ReplyDelete
  3. the above code is encountering many errors in tomcat server m working on eclipse
    anything else i have to do while dealing with the servlet please help

    ReplyDelete
  4. I want to this pdf to only save at the specified location without user notification

    ReplyDelete