Animated Gif to PDF Conversion - Java iText Tutorial

In the previous post, we tried converting an Animated GIF image into a PDF. The GIF image had two frames and iText was able to grab two frames as separate image objects and push them inside a PDF file. However, at the output we noticed that the GIF image's second frame was totally redundant as it contained only the changed portion due to GIF optimization. In such a case, you would only want to convert one frame of the image into PDF, which would be a safe call, given that PDF cannot handle animated GIF files directly. In this post, we will try the same code example by directly accepting the Image into Image class rather than passing it through the GifImage class of iText.
//Image class to extract frames from GIF image
import com.itextpdf.text.Image;
//PdfWriter object to write the PDF document
import com.itextpdf.text.pdf.PdfWriter;
//Document object to add logical image frames to PDF
import com.itextpdf.text.Document;
//we need the class below to read input GIF file
import com.itextpdf.text.pdf.codec.GifImage;
public class animatdGifToPDF {
public static void main(String[] args) {
    //Create Document Object
    Document convertGif2Pdf=new Document();
    //Create PdfWriter for Document to hold physical file
    PdfWriter.getInstance(convertGif2Pdf, new FileOutputStream("c:\\myjava\\ConvertImagetoPDF.pdf"));;
    //Class GifImage is redundant.    
    GifImage myGif=new GifImage("c:\\myjava\\test.gif");
    //Get the number of frames in Gif Image
    System.out.println("Number of Frames to be converted" + myGif.getFrameCount());
    //You may wish to have a If condition here
    //to use the code below if the number of frames is more than 1
    //signifying that this is a animated GIF image
    Image myimage=Image.getInstance("c:\\myjava\\test.gif");
    System.out.println("Successfully Converted Animated GIF Frame to PDF in iText");
catch (Exception i1){
Now, this code converts only the first frame of the GIF (which is usually the full image) to the PDF, which could be a desired operation when you are dealing with multiple frames in a GIF file. In the next post, we will see how to expand our servlet code, which currently handles Jpeg to PDF, Tiff to PDF conversions, to include Gif to PDF conversion. The servlet will stream a PDF file back to the user when the user uploads a GIF image. For GIF alone, we will provide an option to convert all frames or just the file alone. Keep watching this space for more.

No comments:

Post a Comment