Create a PDF file using IText

Posted by

If you want to create a PDF file or manipulate existing PDF file, IText is a free and open source library for doing this.Using iText you can easily create Portable Document Format (PDF).Here I am writing code to create a  PDF with some text.But using iText you can embed image,format your text as you want,give positioning to your text,image,etc.
Resources required : itextpdf-5.1.0.jar


Code:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import java.io.FileOutputStream;
import java.io.IOException;


class createPDF{
    public static void main(String java[]){
    try{
    //Step 1
            Document document = new Document();
        // step 2
        PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(“D:/Hello.pdf”));
        // step 3
        document.open();
        // step 4
       writer.setCompressionLevel(0);
        // writes something to the direct content using a convenience method
        Phrase heading1 = new Phrase(“Java 2 Career”);
        Phrase heading2=new Phrase(“A great Resouce to learn java”);
        PdfContentByte canvas = writer.getDirectContentUnder();
        ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER,
            heading1,300,812,0);
        ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER,
            heading2,300,800,0);
           document.close(); 
    }
    catch(Exception e){
        e.printStackTrace();
    }   
    }

}
To compile and  run include itext.jar into the containing folder of createPDF.java.
Compile with following command:
javac -classpath .;itextpdf-5.1.0.jar createPDF.java

Run with following command:
java -classpath .;itextpdf-5.1.0.jar createPDF

Check d:// drive you will get Hello.pdf in this drive.

Leave a Reply