Tuesday, September 6, 2011

Creation Of PDF Document in JAVA

Here i'm giving a simple program for creating a pdf document using java.
Prerequsite jars are :-
iText.jar


Remark:
  1. Once a document is created you can add some meta information.
  2. You can also set the headers/footers.
  3. You have to open the document before you can write content.
  4. You can only write content (no more meta-formation!) once a document is opened.
  5. When you change the header/footer on a certain page, this will be effective starting on the next page.
  6. After closing the document, every listener (as well as its OutputStream) is closed too.
Below is the main program:-
import com.itextpdf.text.*;

public class DataIntoPDF{


public static void main(String args[]){
//create a document
Document PDFDocument = new Document(PageSize.A4,50,50,50,50);
try{
//pdfwriter instance for writing the data to a file.FileOutput writes the data using output stream to the file specified.If the file doesn't exists throws file not found exception.
PdfWriter pdfWriter  = PdfWriter.getInstance(PDFDocument, new FileOutputStream("E:/pdfData.pdf"));
//add meta information to document
pDFDocument.addAuthor("Anand Kumar");
pDFDocument.addCreator("Anand Kumar");
pDFDocument.addSubject("PDF Creation");
pDFDocument.addCreationDate();
pDFDocument.addTitle("PDf Creation");
PDFDocument.open();
                        String dataToPDF  = 
                                        "Anand Kumar,
                                            " +
 Information only
                                           " +
"Nothing Confidential," +
"
                                                   Just Follow,
                                                  " +
"
                                     Address– " +
"Not Mine Write your Own 
                                      ";

Paragraph p = new Paragraph(dataToPDF);
PDFDocument.add(p);
//Adds a new page to the existing document
PDFDocument.newPage();
Image image = getImageFromResource("/PathtoImage/ImageFile");
Chunk imageChunk = new Chunk(image,-5,0);
PDFDocument.add(imageChunk);
}catch(DocumentException de){
de.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
PDFDocument.close();

}


//For Image resource
private static Image getImageFromResource(String URI){
Image image = null;
try{
image = Image.getInstance(URI);
}catch(IOException ioe){
de.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return image;
}


}

If any modifications are appreciated.
Thankyou.......................!!!!!!!!!!!!!!!!:-)

No comments:

Post a Comment