Welcome to my blog, hope you enjoy reading
RSS

Saturday 5 January 2013

How to create PDF file using iText in java


How to create PDF file using iText in java

Setup iText and Hello World program using iText

iText is an API which helps in creating PDF files using java. iText is a free Java-PDF library that allows developers to create PDF files from already obtained data. iText can also be used for generate documents and reports based on data from an XML file or a database, Split, concatenate, and manipulate PDF pages, Add bookmarks, page numbers, watermarks, etc.
Serve dynamically generated or manipulated PDF documents to a web browser and many more. These features makes iText is an ideal library for developers.

How to create PDF file using iText in java

Now lets see How to create PDF file using iText in java
1. First of all you need to have JDK 1.4 or later to integrate iText PDF.
2. To create PDF File using iText you need iText jar file which can be downloaded here.
3. You need to put itext***.jar in your class path and paste following code mentioned below of this post.
If you are using Netbeans or Eclipse IDE then you can add iText jar path to the libraries section.
4. Below is the small code to write first program to create PDF in java.
As shown in the code below we need to create Document object first


Document pdfdocument = new Document(); 


Then we need to get PDFWriter instance by passing document object and File output stream of the pdf file.

Source code example for creating PDF in java

PdfWriter writer =  PdfWriter.getInstance(pdfdocument, new FileOutputStream(pdfFile)); 


To write the contents into the file we need to open pdf document first and then we need to add the text “Hello Word”. In the code below the text has been added to the Paragraph, similarly we can add text to Chunk, Phrase etc.

public class HellowWorldPDF {
public HellowWorldPDF() throws Exception{
                Document pdfdocument = new Document();
                File pdfFile = new File("E:\\HelloWorld.pdf");
                try{
                if(!pdfFile.exists()){
                    pdfFile.createNewFile();
                    System.out.println("Creating file");
                }
                }catch(Exception es){
                    es.printStackTrace();
                }
                PdfWriter writer =  PdfWriter.getInstance(pdfdocument, 
new FileOutputStream(pdfFile));
                pdfdocument.open();
pdfdocument.add(new Paragraph("Hello World"));
                System.out.println("Document written");
pdfdocument.close();
}
public static void main(String args[]){
try{
new HellowWorldPDF();
}catch(Exception e){
System.out.println(e);
}
}

0 comments: