Convert JPG to PDF iText Java Example Tutorial

In this tutorial, we will write a standalong Java Class that will convert a JPG file into a PDF document. For illustration purposes, we will stamp / insert the JPG into the PDF file in this tutorial. Later on, we will provide a servlet example in iText that will accept a user uploaded image file from the server and convert that image into a PDF documment and provide it back to the user. You will need the following version of iText to get started with this tutorial [ Note: This example would also work on earlier versions of iText, provided you adjust your import declarations if required ]
iText 5.1.0
You will also need a sample image file for using in this tutorial. Just create any image file with name "test.jpg" , we will be making use of this image for converting to a PDF file.You can alternatively use the image provided below for changing to PDF if you would wish to;
Convert JPG to PDF Using iText
Convert JPG to PDF Using iText
The complete commented code that explains how to convert a JPG image to PDF file using Java iText API is provided below;
package jpegtopdf;
//We need the library below to write the final PDF file which has our image converted to PDF
import java.io.FileOutputStream;
//The image class which will hold the input 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 files to PDF
import com.itextpdf.text.Document;
public class JpegToPDF {
public static void main(String[] args) {
try{
    //Create Document Object
    Document convertJpgToPdf=new Document();
    //Create PdfWriter for Document to hold physical file
    PdfWriter.getInstance(convertJpgToPdf, new FileOutputStream("c:\\java\\ConvertImagetoPDF.pdf"));
    convertJpgToPdf.open();
    //Get the input image to Convert to PDF
    Image convertJpg=Image.getInstance("c:\\java\\test.jpg");
    //Add image to Document
    convertJpgToPdf.add(convertJpg);
    //Close Document
    convertJpgToPdf.close();
    System.out.println("Successfully Converted JPG to PDF in iText");
}
catch (Exception i1){
    i1.printStackTrace();
}
}
}
When you run this code, the code will create a Document object and using an Image object of type (com.itextpdf.text.Image), we read the JPG file to be converted into PDF document. We then convert this image to PDF by stamping the image into the Document object. Now, you may wish to delete this image file post writing into PDF. As you may notice, this example is very basic and you should explore the possibilities of using the Image class to suit to your needs. In the next example, we will provide a Java servlet which will accept a file uploaded by the user (image file) and then write this file to a PDF document and send this back to the browser. Stay connected with us to learn more.

No comments:

Post a Comment