Saturday, 28 February 2015

CREATE PDF FILES USING iTextPdf Jar LIBRARY - BASIC EXAMPLE

iText is an API for creating and manipulating PDF files in java.

Note: you must add itextpdf jar file to your build path in order to use itext pdf API.

Download Link:

itextpdf-5.5.5.jar

(or)

Using Maven:

If you are interested to use a maven dependency - add the following to your dependencies list:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.5</version>
</dependency>

Note: you can continue reading this post even if you don't no maven.

If you are new to maven - click here ---> What is Maven & how to use it?

This post explains the creation of PDF with a specifed format like this:

Example PDF :  CWCReport.pdf

Important Classes:

Mostly all the classes I am using here are from same package:
com.itextpdf.text package


>>Document - Objects of this classes resembles the real world PDF document.

//creating an instance of Document
Document document = new Document();

Document class has different overloaded constructors. I am using one which specifies the page size of A4.

//creating an instance of Document
Document document = new Document(PageSize.A4.rotate());

Here,
>>PageSize  - class having all standard page formats like A1-A10 , B1-B10

rotate() method - creates a landscape PDF.

>>PdfWriter

* After defining a Document object - define PdfWriter object

//creating PdfWriter instance using a static method getInstance

//You can specify the path for PDF file creating using FileOutputStream
 OutputStream file=new FileOutputStream(new File("/home/dinesh/CWCReport.pdf"));

For File pass you pdf path where you want to create on your file system.

Note: On windows, you may have you give \\ (double slashes) for file's path.
Like: c:\\home\\pdfs\\create.pdf

//Parameters document & FileOutStream file
PdfWriter.getInstance(document, file);

Defining Document Information using document object:

using document object - we can define the pdf author, subject, title, & creation date.

                 //defining an author
                document.addAuthor("Dinesh Dontha");

                 //defining a subject
                document.addSubject("CWC Matches List");
   
                // title on the document-window
                document.addTitle("CWC - Schedule");

                // creation date
                document.addCreationDate();

Opening a Document:

Note: Inorder to write content into the pdf document - you must open it first

//open a document
document.open();

Adding a Paragraph:

>> Paragraph

Objects of this classes resembles real-object Paragraphs - so to create a paragraph use an object of it.

Paragraph class extends a Phrase class.

Phrase is like a sentence.

Defining Paragraphs :

//create a paragraph - using a String argument
Paragraph para2 = new Paragraph("para1....");

//create a paragraph -using a Phrase

>>Phrase
 
Phrase is a series of chunks

Here, we also have Chunk class

Chunk is the smallest significant part of the text that can be added to
document.

//creating a phrase with no parameters
Phrase phrase = new Phrase();

//Phrase with a specified font
Phrase title =new Phrase("phrase1",new Font(FontFamily.HELVETICA, 32));

Note:

>>Font  class 

 FontFamily  is an ENUM defined inside Font class

//creating Paragraph by passing Phrase instance
Paragraph para2 = new Paragraph(phrase);

//creating Paragraph with specified Font
Paragraph para2 = new Paragraph("Paragraph Text", new Font(FontFamily.HELVETICA, 16));

 Adding New Blank Lines between Paragraphs:

Using Chunk class

>>Chunk

//adds a blank line
document.add(Chunk.NEWLINE);

Creating a table:

Use  PdfPTable class instance

>>PdfPTable

While creating the instance of PdfPTable - we can define the number of columns in that table

//create a table with 2 columns
PdfPTable table = new PdfPTable(2);

Using this instance, you can set some global properties for this table elements

//setting the table width in the document
table.setWidthPercentage(100);

Here, table extends complete width of page.

 //setting a padding for all cells
table.getDefaultCell().setPadding(10);

//setting an align of cell data      
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

Defining Table Cells:

we can add table cells using  addCell() method of PdfPTable class

//adding a basic cell using addCell() method

table.addCell("Match Date");
table.addCell("Between");

(or)

you can define table cells using PdfPCell class

>>PdfPCell
PdfPCell class has many overloaded constructors

//with no parameters
PdfPCell cell1 = new PdfPCell();

//with a Phrase paramter -defines the cell content with Phrase
Phrase p1 =new Phrase("Cell Content");

//defining cell with phrase as content
PdfPCell cell = new PdfPCell(p1);

Once defined a cell instance - we can override the properties that are
globally defined- defined on table i.e, PdfPTable object.

//overrides padding defined on table object
cellHeader2.setPadding(20);

**Note:
 //setting properties on PdfPTable object-"table" are not applicable for this particular cell defined using PdfPCell class

i.e,       table.getDefaultCell().setPadding(10);

Here, padding for all cells is 10. But, for this cell - it is 20.

//similarly this overrides - alignment property set on table(PdfPTable) object
cellHeader2.setHorizontalAlignment(Element.ALIGN_CENTER);

Example:

All the data in this example are stored in a Map object.

Note: finally close the document object and file stream object.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/* GeneratePdf.java
 * Created on 26-Sep-2014
 */

public class CreatePdf {

 public static void main(String[] args) {

try {

 // creating a file stream object
 OutputStream file = new FileOutputStream(new File(
   "/home/dinesh/CWCReport.pdf"));

 // creating a document object - with A4 size
 // please see the effect of rotate() method -with and without it

 // rotate() method -creates a pdf in landscape format
 Document document = new Document(PageSize.A4.rotate());

 // must create a PdfWriter object -pass document and file output
 // stream
 PdfWriter.getInstance(document, file);

 // creating document info
 document.addAuthor("Dinesh Dontha");
 document.addSubject("CWC Matches List");
 document.addTitle("CWC - Schedule");
 document.addCreationDate();

 // must open a document -to put content
 document.open();

 // creating a Phrase
 Phrase title = new Phrase("Cricket World Cup-2015- Schedule",
   new Font(FontFamily.HELVETICA, 32));

 // creating a Paragrapgh with Phrase as parameter
 Paragraph para1 = new Paragraph(title);
 para1.setAlignment(Element.ALIGN_CENTER);

 // adding paragraph to document -this main heading for document.
 document.add(para1);

 // adding a blank line after - heading/title
 document.add(Chunk.NEWLINE);

 // creating a paragraph
 Paragraph para2 = new Paragraph(
   "Next upcoming league matches of Team India in the "
     + "giagantic Cricket World Cup-2015", new Font(
     FontFamily.HELVETICA, 16));
 para2.setAlignment(Element.ALIGN_LEFT);

 // adding a paragraph - this is infact the first paragraph in this
 // exxample
 document.add(para2);

 // adding a blank line after - first paragraph
 document.add(Chunk.NEWLINE);

 // adding all cell data to a Map object
 Map indiaMatches = new HashMap<>();

 indiaMatches.put("Sunday, March 6th 2015", "INDIA VS WEST INDIES");
 indiaMatches.put("Sunday, March 10th 2015", "INDIA VS IRELAND");
 indiaMatches.put("Sunday, March 14th 2015", "INDIA Vs ZIMBABWE");

 // Define a PDF table with 2 columns - Match Date & Between column
 // Names
 PdfPTable table = new PdfPTable(2);

 // Setting global table cell properties
 table.setWidthPercentage(100);
 table.getDefaultCell().setPadding(10);
 table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

 // table header creation -using PdfPCell class

 // creating table header -cell -first column - Match Date
 Phrase matchDate = new Phrase("Match Date", new Font(
   FontFamily.HELVETICA, 14, Font.BOLD));
 // using PdfPCell class
 PdfPCell cellHeader1 = new PdfPCell(matchDate);
 cellHeader1.setBackgroundColor(BaseColor.ORANGE);
 cellHeader1.setPadding(10);
 cellHeader1.setHorizontalAlignment(Element.ALIGN_CENTER);
 table.addCell(cellHeader1);

 // creating table header -cell -second column - Between
 Phrase matchBetween = new Phrase("Match Between", new Font(
   FontFamily.HELVETICA, 14, Font.BOLD));
 // using PdfPCell class
 PdfPCell cellHeader2 = new PdfPCell(matchBetween);
 cellHeader2.setBackgroundColor(BaseColor.ORANGE);
 cellHeader2.setPadding(10);
 cellHeader2.setHorizontalAlignment(Element.ALIGN_CENTER);
 table.addCell(cellHeader2);

 // creating cell data -other than table column headers- using
 // addCell()
 // method of PdfPTable object
 for (Map.Entry entry : indiaMatches.entrySet()) {
  table.addCell(entry.getKey());
  table.addCell(entry.getValue());
 }

 // adding table to Pdf document
 document.add(table);

 // finally close - document & file stream
 document.close();
 file.close();

} catch (DocumentException | IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
}

}

Source Code: Download
Note: To run it successfully change the file path.

No comments:

Post a Comment