In this tutorial, we will extend the example provided earlier [that explained how to convert a Tiff Image to PDF file ] to accommodate a JPG to PDF conversion using iText and Servlets. We will be adding some additional code to the same example to achieve this convert operation. If you are keen to have a servlet code, that does only JPG to PDF conversion, you should consider clipping the servlet code provided in this example to suit to your needs. It is not that difficult if you know some basics of Java. The first step to build a servlet that can convert a JPEG image file to PDF document is to have a JSP page that will accept a user uploaded page, and also obtain the type of conversion required. This servlet will support both TIFF and JPEG images. The JSP code is provided below;
A screenshot of the HTML page produced by this code is shown below;<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Convert Uploaded Image into PDF</title>
</head>
<body>
<h1>Upload a Tiff or JPEG Image which will be Converted to PDF File</h1>
<form action="Image2Pdf" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
<input type="file" name="file" id="file">
<select name="convertTo">
<option>Tiff2Pdf</option>
<option>Jpeg2Pdf</option>
</select>
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
Image to PDF Conversion Servlet |
As you may infer from the page, it provides two options to the user for generating PDF depending on the type of image. You may wish to add some form level validations to make sure that a right file has been uploaded. In the servlet code, we check the type of conversion required by reading this input and then invoke the required methods in iText to add the image to the PDF file. The servlet code with comments for this example 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 Image2Pdf 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 Input Image is Converted to PDF, Save the File"));
document.add(new Paragraph("PDF Produced by Converting Image to PDF as Servlet"));
//Get uploaded image path in string variable
String conversionType=myrequest.getParameter("convertTo");
System.out.println(conversionType);
String FilePath=myrequest.getFile("file").getAbsolutePath();
//Check if the User has opted for Tiff2Pdf at the page
if (conversionType.equals("Tiff2Pdf")){
//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);
}
}
//Check if the User has opted for Jpeg2Pdf at the page
if (conversionType.equals("Jpeg2Pdf")){
Image tempImage=Image.getInstance(FilePath);
tempImage.scaleToFit(640, 480);
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";
}//
}
In the upcoming tutorials, we will discuss how to convert other image formats to PDF in iText. We will also extend the same servlet code each time to build one big servlet that is capable of stamping any image type to a PDF document using iText.
To know how to deploy this servlet to Tomcat, refer to servlet deployment tutorial on Thinktibits
Above Example not working it shows error on MultipartRequest.I have all required jars.Please give me solution.
ReplyDelete