Tuesday, September 13, 2011

Generating pdf reports in JAVA using iText library

The given Java program demonstrates a tutorial based upon iText to produce pdf report in the form of a Certificate. The final generated certificate will be a pdf file and look like the figure given. Three java classes are used for the sample as listed below. Cetrificate class represents the basic certificate object to be generated encapsulating all the required contents wanted on the certificate pdf report. CerrtificateReport is the main Java class which when run produces pdf certificate report under ./templates/ directory. The java report tutorial also uses XmlUtils file which is a xml utility class for reading xml files. The class has a method which returns the list of entries in the xml file required by our application.

Classes Used in the pdf Report generating application.

1. Cerrificate.java
2. CertificateReport.java
3. XmlUtils.java


Libraries Used:
iText1-3.jar

Certificate.java

package org.dvst.dvs;
import java.util.Date;
import java.util.List;
/**
* DTO for producing certificate
*  @author bishal acharya
*/
public class Certificate {
private int registrationNo;
private String fullName;
private String fatherName;
private String permanentAddres;
private int citizenshipNo;
private int passportNo;
private String creditHours;
private String system;
private Date fromDate;
private Date toDate;
private String course;
private String imagePath;
private List<String> headers;
private String workSystem;

public int getRegistrationNo() {
return registrationNo;
}
public void setRegistrationNo(int registrationNo) {
this.registrationNo = registrationNo;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public String getPermanentAddres() {
return permanentAddres;
}
public void setPermanentAddres(String permanentAddres) {
this.permanentAddres = permanentAddres;
}
public int getPassportNo() {
return passportNo;
}
public void setPassportNo(int passportNo) {
this.passportNo = passportNo;
}
public int getCitizenshipNo() {
return citizenshipNo;
}
public void setCitizenshipNo(int citizenshipNo) {
this.citizenshipNo = citizenshipNo;
}
public String getCreditHours() {
return creditHours;
}
public void setCreditHours(String creditHours) {
this.creditHours = creditHours;
}
public String getSystem() {
return system;
}
public void setSystem(String system) {
this.system = system;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}

public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public List<String> getHeaders() {
return headers;
}
public void setHeaders(List<String> headers) {
this.headers = headers;
}
public String getWorkSystem() {
return workSystem;
}
public void setWorkSystem(String workSystem) {
this.workSystem = workSystem;
}
}



CertificateReport.java

package org.dvst.dvs;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

/**
* @author bishal acharya
*/
public class CertificateReport {
public CertificateReport(Certificate certificate) throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy");
Document document = new Document(PageSize.A4.rotate());
document.setPageSize(PageSize.A4);
PdfWriter.getInstance(document,
new FileOutputStream("./templates/" + certificate.getFullName()
+ "-" + certificate.getRegistrationNo() + ".pdf"));
document.open();
Paragraph p1 = new Paragraph(30);
p1.add(new Chunk(certificate.getHeaders().get(0), new Font(
Font.TIMES_ROMAN, 8)));
p1.setAlignment(1);
Paragraph p2 = new Paragraph();
p2.add(new Chunk(certificate.getHeaders().get(1), new Font(
Font.TIMES_ROMAN, 9, Font.BOLD)));
p2.setAlignment(1);
Paragraph p3 = new Paragraph();
p3.add(new Chunk(certificate.getHeaders().get(2), new Font(
Font.TIMES_ROMAN, 14, Font.BOLD)));
p3.setAlignment(1);
Paragraph p4 = new Paragraph();
p4.add(new Chunk(certificate.getHeaders().get(3), new Font(
Font.TIMES_ROMAN, 14)));
p4.setAlignment(1);
Paragraph p5 = new Paragraph(60);
p5.add(new Chunk("Reg. No. (DVSDT) :- "
+ certificate.getRegistrationNo(),
new Font(Font.TIMES_ROMAN, 9)));
p5.setAlignment(0);
p5.setIndentationLeft(80);
Paragraph p6 = new Paragraph(45);
p6.add(new Chunk("Certificate", new Font(Font.TIMES_ROMAN, 17,
Font.BOLD)));
p6.setAlignment(1);
Paragraph p7 = new Paragraph(30);
p7.add(new Chunk("This certificate is awarded to " + "  ", new Font(
Font.TIMES_ROMAN, 9)));
p7.add(new Chunk(certificate.getFullName() + "  ", new Font(
Font.TIMES_ROMAN, 9, Font.BOLD)));
p7.add(new Chunk("son of  ", new Font(Font.TIMES_ROMAN, 9)));
p7.add(new Chunk("Mr.  " + certificate.getFatherName(), new Font(
Font.TIMES_ROMAN, 9, Font.BOLD)));
p7.setAlignment(1);
Paragraph p8 = new Paragraph(18);
p8.add(new Chunk("Permanent resident of" + "  ", new Font(
Font.TIMES_ROMAN, 9)));

p8.add(new Chunk(certificate.getPermanentAddres() + "  ", new Font(
Font.TIMES_ROMAN, 9, Font.BOLD)));
p8.add(new Chunk("holding citizenship No : ", new Font(
Font.TIMES_ROMAN, 9)));
p8.add(new Chunk(certificate.getCitizenshipNo() + " ", new Font(
Font.TIMES_ROMAN, 9, Font.BOLD)));
p8.setAlignment(1);
Paragraph p9 = new Paragraph(18);
p9.add(new Chunk("& passport No. ", new Font(Font.TIMES_ROMAN, 9)));
p9.add(new Chunk(certificate.getPassportNo() + " ", new Font(
Font.TIMES_ROMAN, 9, Font.BOLD)));
p9.add(new Chunk("for successful completion of "
+ certificate.getCreditHours()
+ " Credit Hours course on Preliminary", new Font(
Font.TIMES_ROMAN, 9)));
p9.setAlignment(1);
Paragraph p10 = new Paragraph(18);
p10.add(new Chunk(
"education for the workers going to Republic of Korea under",
new Font(Font.TIMES_ROMAN, 9)));
p10.add(new Chunk("  " + certificate.getWorkSystem(), new Font(
Font.TIMES_ROMAN, 9, Font.BOLD)));
p10.setAlignment(1);

Paragraph p11 = new Paragraph(18);
p11.add(new Chunk("from  "
+ formatter.format(certificate.getFromDate()) + "  " + "to  "
+ formatter.format(certificate.getToDate()), new Font(
Font.TIMES_ROMAN, 9)));
p11.setAlignment(1);

Paragraph p12 = new Paragraph(45);
p12.add(new Chunk(
"---------------------"
+ "                                                                "
+ "                                                          "
+ "  ---------------------------", new Font(
Font.TIMES_ROMAN, 8)));

p12.setAlignment(1);
Paragraph p13 = new Paragraph(10);
p13.add(new Chunk(
"   Coordinator"
+ "                                                           "
+ "                                                                        "
+ "Executive Director", new Font(Font.TIMES_ROMAN, 8)));
p13.setAlignment(1);
Paragraph p14 = new Paragraph(20);
p14.setAlignment(1);
p14.add(new Chunk(formatter.format(new Date()), new Font(
Font.TIMES_ROMAN, 7, Font.BOLD)));

document.add(p1);
document.add(p2);
document.add(p3);
document.add(p4);
document.add(p5);
document.add(p6);
document.add(p7);
document.add(p8);
document.add(p9);
document.add(p10);
document.add(p11);
document.add(p12);
document.add(p13);
document.add(p14);
com.lowagie.text.Image image = com.lowagie.text.Image
.getInstance("./templates/me.JPG");
image.setBorder(1);
image.scaleAbsolute(100, 100);
image.setAbsolutePosition(450, 730);
document.add(image);
document.close();

}

public static void main(String[] args) {
List<String> headerList = XmlUtils.getNodeValue("DataElement", "Value",
DvsdtConstants.xmlConfigurationpath);
try {
Certificate c = new Certificate();
c.setFullName("Bishal Acharya");
c.setFatherName("Manoj Acharya");
c.setRegistrationNo(15236);
c.setCitizenshipNo(102545);
c.setPassportNo(3518161);
c.setFromDate(new Date());
c.setToDate(new Date());
c.setCreditHours("Fourty Five (45)");
c.setPermanentAddres("Shahid Marga Biratnagar");
c.setWorkSystem("Employment Permit System");
c.setHeaders(headerList);
CertificateReport cR = new CertificateReport(c);

} catch (Exception e) {
System.out.println(e);
}
}
}


XmlUtils.java

package org.dvst.dvs;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
* Returns node value in given XML
* @author bishal acharya
*/
public class XmlUtils {
/**
* Gets Node Value List from given XML document with file Path
* 
* @param parentTag
* @param tagName
* @param layoutFile
* @return
*/
public static List<String> getNodeValue(String parentTag, String tagName,
String layoutFile) {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = null;
Document doc = null;
List<String> valueList = new ArrayList<String>();
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(new File(layoutFile));
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Could not load file");
}
NodeList layoutList = doc.getElementsByTagName(parentTag);

for (int s = 0; s < layoutList.getLength(); s++) {
Node firstPersonNode = layoutList.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
NodeList firstNameList = (firstPersonElement)
.getElementsByTagName(tagName);
Element firstNameElement = (Element) firstNameList.item(0);
NodeList textFNList = (firstNameElement).getChildNodes();
valueList.add(textFNList.item(0).getNodeValue().trim());
}
}
return valueList;
}

/**
* Unit test for XmlUtils class
* @param args
*/
public static void main(String args[]) {
System.out.println(XmlUtils.getNodeValue("DataElement", "Value",
"./templates/Contents.xml"));
}
}



The xml file should be present under ./templates/Contents.xml






me.JPG image file should be present under the same ./templates/me.JPG directory.

Commons Validator : Java based Validation Utility

Commons Validator : Java based Validation Utility

A utility to validate common data fields like Numeric, Double, Date, email, Integer, Currency,Percent etc using apache Commons validator library. The class below uses Commons-Validator-1.3.1.jar library. The bulk of logic is implemented in the library itself. This class is a simple java program to unite validators work with a simple utility.


/**
* Utility for validation of different fields
*
* @author Bishal Acharya
*/
public class ValidationUtility {
/**
* Check if provided String is Number
*
* @param str
* @return
*/
public static boolean checkIsNumeric(String str) {
if (str == null)
return false;
return str.matches("-?\\d+(.\\d+)?");
}

/**
* Check if given String provided is double
*
* @param str
* @return
*/
public static boolean checkIfDouble(String str) {
if (str == null)
return false;
try {
Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}

/**
* Validates whether provided string is date field or not
*
* @param date
* @param format
* defaultDate format
* @return
*/
public static boolean validateDate(String date) {
String format = "MM/dd/yyyy";
DateValidator validator = DateValidator.getInstance();

Date dateVal = validator.validate(date, format);
if (dateVal == null) {
return false;
}
return true;
}

/**
* Validates whether provided string is date field or not
*
* @param date
* @param format
* @return boolean status of whether given data is valid or not
*/
public static boolean validateDate(String date, String format) {

DateValidator validator = DateValidator.getInstance();

Date dateVal = validator.validate(date, format);
if (dateVal == null) {
return false;
}
return true;
}

/**
* Formats the given date as according to given formatter
*
* @param date
* @param format
* @return
*/
public static String formatDate(String date, String format) {
DateValidator validator = DateValidator.getInstance();

String dateVal = null;
try {
dateVal = validator.format(date, format);
} catch (IllegalArgumentException e) {
System.out.println("Bad date:" + date + ": cannot be formatted");
}
if (dateVal == null) {
return null;
}
return dateVal;
}

/**
* Validates whether clients data is Integer or not
*
* @param integer
* @return
*/
public static boolean IntegerValidator(String integer) {
IntegerValidator validator = IntegerValidator.getInstance();

Integer integerVal = validator.validate(integer, "#,##0.00");
if (integerVal == null) {
return false;
}
return true;
}

/**
* validates whether data is currency of not
*
* @param currency
* @param loc
* @return
*/
public static boolean currencyValidator(String currency, Locale loc) {
BigDecimalValidator validator = CurrencyValidator.getInstance();
if (loc == null) {
loc = Locale.US;
}
BigDecimal amount = validator.validate(currency, loc);
if (amount == null) {
return false;
}
return true;
}

/**
* Validates whether data provided is in percentage or not
*
* @param percentVal
* @return
*/
public static boolean percentValidator(String percentVal) {
BigDecimalValidator validator = PercentValidator.getInstance();
boolean valid = false;
BigDecimal Percent = validator.validate(percentVal, Locale.US);
if (Percent == null) {
valid = false;
}
// Check the percent is between 0% and 100%
if (validator.isInRange(Percent, 0, 1)) {
valid = true;
} else {
valid = false;
}
return valid;
}

/**
* validates correct email address
*
* @param email
* @return
*/
public static boolean emailValidator(String email) {
EmailValidator validator = EmailValidator.getInstance();
boolean isAddressValid = validator.isValid(email);
return isAddressValid;
}

public static void main(String args[]) {
String s = "12/18/1952";
System.out.println(DateValidator.getInstance().validate(s,
"MM/dd/yyyy"));
System.out.println("valid percent :"
+ ValidationUtility.percentValidator("100"));
System.out.println("Invalid percent :"
+ ValidationUtility.percentValidator("110"));

System.out.println("Valid Currency :"
+ ValidationUtility.currencyValidator("100", Locale.US));
System.out.println("InValid Currency :"
+ ValidationUtility.currencyValidator("Dollar", Locale.US));
System.out.println("Integer Validator :"
+ ValidationUtility.IntegerValidator("1"));
System.out.println("Integer Validator :"
+ ValidationUtility.IntegerValidator("1.2"));
System.out.println("Valid Numeric:"
+ ValidationUtility.checkIsNumeric("1"));
System.out.println("InValid Numeric:"
+ ValidationUtility.checkIsNumeric("ABCD")); }

}




Output :-

Thu Dec 18 00:00:00 NPT 1952
valid percent :true
Invalid percent :false
Valid Currency :true
InValid Currency :false
Integer Validator :true
Integer Validator :false
Valid Numeric:true
InValid Numeric:false

Utility for Evaluating XML string,Files in JAVA

Given below is a Java utility class that can be used to evaluate/parse XML files. There are three different methods which parses the given XML file or XML String.

getNodeValueListFromFile

This method can be used to get NodeValue List from the ML file given as String.

getNodeValue

This method can be used to get value of the Node from give XML file.

printNodeValueFromFile

This method prints the Node value from XML file given as string

/**
* @author bacharya
*/
public class XmlUtils {
/**
* Gets Node Value from given XML document with file Path
*
* @param parentTag
* @param tagName
* @param layoutFile
* @return
*/
public static String getNodeValue(String parentTag, String tagName,
String layoutFile) {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = null;
Document doc = null;

try {
docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(new File(layoutFile));
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Could not load file");
}
NodeList layoutList = doc.getElementsByTagName(parentTag);

for (int s = 0; s < layoutList.getLength(); s++) {
Node firstPersonNode = layoutList.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
NodeList firstNameList = (firstPersonElement)
.getElementsByTagName(tagName);
Element firstNameElement = (Element) firstNameList.item(0);
NodeList textFNList = (firstNameElement).getChildNodes();
return textFNList.item(0).getNodeValue().trim();
}
}
return null;
}

/**
* Gets Node Value from given XML as String
*
* @param parentTag
* @param tagName
* @param xmlRecords
* @return
*/
public static void printNodeValueFromFile(String parentTag, String tagName,
String xmlRecords) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));

Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName(parentTag);

for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);

NodeList name = element.getElementsByTagName(tagName);
Element line = (Element) name.item(0);
System.out.println(": " + getCharacterDataFromElement(line));
}
} catch (Exception e) {
e.printStackTrace();
}
return "";

}

/**
* Gets Node Value from given XML as Map of List of Strings
*
* @param parentTag
* @param tagName
* @param xmlRecords
* @return
*/
public static Map<String, List<String>> getNodeValueListFromFile(
String parentTag, String tagName, String xmlRecords) {
Map<String, List<String>> nodeMapList = new HashMap<String, List<String>>();
List<String> valueList = new ArrayList<String>();

try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));

Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName(parentTag);

for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);

NodeList name = element.getElementsByTagName(tagName);
Element line = (Element) name.item(0);
valueList.add(getCharacterDataFromElement(line));
}
} catch (Exception e) {
e.printStackTrace();
}
nodeMapList.put(tagName, valueList);
return nodeMapList;

}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}

/**
* Unit test for XmlUtils class
*
* @param args
*/
public static void main(String args[]) {
String rec = "<Layout>" + " <Data>" + " <Name>testLayout</Name>"
+ " <Delimiter>s</Delimiter>" + " </Data>" + " <Details>"
+ " <DataElement>" + " <fieldName>GROUP</fieldName>"
+ " <Type>String</Type>" + " <Location>" + " <Num>1</Num>"
+ " </Location>" + " </DataElement>" + " <DataElement>"
+ " <fieldName>ENTITY_CODE</fieldName>"
+ " <Type>String</Type>" + " <Location>" + " <Num>2</Num>"
+ " </Location>" + " </DataElement>" + " </Details>"
+ "</Layout>";

Map<String, List<String>> nodeMapList = XmlUtils
.getNodeValueListFromFile("DataElement", "fieldName", rec);
Map<String, List<String>> nodeMapList1 = XmlUtils
.getNodeValueListFromFile("DataElement", "Type", rec);
Map<String, List<String>> nodeMapList2 = XmlUtils
.getNodeValueListFromFile("Location", "Num", rec);

List<String> val = nodeMapList.get("fieldName");

System.out.println(val.size());
for (int i = 0; i < val.size(); i++) {
System.out.println(nodeMapList1.get("Type").get(i));
System.out.println(nodeMapList2.get("Num").get(i));
}

System.out.println(
XmlUtils.getNodeValueFromFile("DataElement", "fieldName",
rec));

}
}



Test Output :

2
String
1
String
2
: GROUP
: ENTITY_CODE