Saturday, April 4, 2009

Add Header and Footer to PDF

Before start to work out on this topic. I want to give some concept regarding iText PDF.

1. onStartPage() : It is auto triggerd method when new page started. If pdf has 10 page then it would be execute 10 times. Used this method to initializing variable or setting parameter. But it is not right place add Header and Footer.

2. onEndPage() : It is also auto triggered method during before starting a new page. This is right place to add Header and Footer.


To use these method, class should be extended by com.lowagie.text.pdf.PdfPageEventHelper;


HeaderAndFooter.java


import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;
public class HeaderAndFooter extends PdfPageEventHelper{


protected Phrase header;
protected PdfPTable footer;


public static void main(String[] args) {
new HeaderAndFooter().createPDF();
System.out.println("** PDF CREATED **");
}
public void createPDF() {
Document document = new Document();
try{
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("Header_Footer_Example.pdf"));
writer.setPageEvent(new HeaderAndFooter());
document.open();
for(int i=0;i<1000;i++){
document.add(new Phrase("BINOD KUMAR SUMAN "));
}
document.close();
}catch(Exception e){
}
}
public HeaderAndFooter() {
header = new Phrase("**** THIS IS HEADER PART OF THIS PDF ****");
footer = new PdfPTable(1);
footer.setTotalWidth(300);
footer.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
footer.addCell(new Phrase(new Chunk("**** THIS IS FOOTER PART OF THIS PDF ****")
.setAction(new PdfAction(PdfAction.FIRSTPAGE))));
}
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header,(document.right() - document.left()) / 2+ document.leftMargin(), document.top() + 10, 0);

footer.writeSelectedRows(0, -1,(document.right() - document.left() - 300) / 2+ document.leftMargin(), document.bottom() - 10, cb);
}
}


Here one problem is that header will start from first page itself. If you want that header should come from second page. Then you have to put one condition like this

if (document.getPageNumber() > 1) {ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header,(document.right() - document.left()) / 2+ document.leftMargin(), document.top() + 10, 0);}

Friday, April 3, 2009

How to insert IMAGE in PDF using iText

On assuming that you should have one jpg image in the same folder. In this example I kept Binod_Flex.jpg in the same folder where this java file present.
Demo.java

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
new Demo().createPDF();
}
public void createPDF(){
Document d = new Document (PageSize.A4);
try {
PdfWriter.getInstance(d, new FileOutputStream("sample.pdf"));
d.open ();
d.addCreator("Binod by Demo.java");
d.addAuthor("Binod Suman");
d.addTitle("First PDF By Binod");
Image image = Image.getInstance("Binod_Flex.jpg");
image.scaleAbsolute(300,300);
d.add(image);
d.close ();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("******** PDF Created ***************");
}
}

You can now check that one PDF generated with specify image.

To change PDF page background color, use this

Rectangle pageSize = new Rectangle(400,400);
pageSize.setBackgroundColor(new java.awt.Color(0xDF,0xCC,0xFF));
Document d = new Document (pageSize);
and remaining same.

Insert table in PDF,


PdfPTable table=new PdfPTable(2);
table.addCell("Student Name");
table.addCell("Roll No.");
table.addCell("Binod");
table.addCell("110");
table.addCell("Pramod");
table.addCell("120");
d.add(table);

Insert Header in table in PDF


PdfPTable table=new PdfPTable(2);
PdfPCell cell = new PdfPCell(new Paragraph("Student Details"));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBackgroundColor(new Color(20,105,160));
cell.setColspan(2);
table.addCell(cell);
table.addCell("Student Name");
table.addCell("Roll No.");
table.addCell("Binod");
table.addCell("110");
table.addCell("Pramod");
table.addCell("120");
d.add(table);

How to generate PDF report from Java

1. Download iText-2.1.5.jar (You can google and get it)
2. Demo.java

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class Demo {
public static void main(String[] args) {
new Demo().createPDF();
}
public void createPDF(){
Document d = new Document (PageSize.A4);
try {
PdfWriter.getInstance(d, new FileOutputStream("sample.pdf"));
d.open ();
Paragraph p = new Paragraph ("Binod Kumar Suman,\n Bangalore, India");
d.add (p);
d.close ();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
System.out.println("******** PDF Created ***************");
}
}

Now check, you will get one pdf file sample.pdf

XPATH Java simple example

XPath is used to search any node any element in XML file. ---- very basic defination.

XPath is a fourth generation declarative language for locating nodes in XML documents. This is much more robust than writing the detailed search and navigation code yourself using DOM, SAX, or JDOM. using XPath in a Java program is like using SQL in a Java program. To extract information from a database, you write a SQL statement indicating what information you want and you ask JDBC to fetch it for you. You neither know nor care how JDBC communicates with the database. Similarly with XML, you write an XPath expression indicating what information you want from an XML document and ask the XPath engine to fetch it, without concerning yourself with the exact algorithms used to search the XML document.

1. Suppose I have persons.xml
<?xml version="1.0" ?>
<information>
<person id="1">
<name>Binod</name>
<age>24</age>
<gender>Male</gender>
</person>

<person id="2">
<name>Pramod</name>
<age>22</age>
<gender>Male</gender>
</person>

<person id="3">
<name>Swetha</name>
<age>19</age>
<gender>Female</gender>
</person>
</information>

2. XPathJavaExample.java

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathJavaExample {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//person/*/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}

The output of this xpath query ("//person/*/text()");
Binod
24
Male
Pramod
22
Male
Swetha
19
Female

XPathExpression expr = xpath.compile("//person[last()]/*/text()"); This will be give the last record
Swetha
19
Female

XPathExpression expr = xpath.compile("//person/name/text()"); Here name is mentioned instaed of *. * means all the attribute. The output
Binod
Pramod
Swetha
Only name shows here.

XPathExpression expr = xpath.compile("//person[1]/*/text()"); Retrive first record
Binod
24
Male

XPathExpression expr = xpath.compile("//name/text()"); It will show all the name tag, that would be anywhere in xml. The output
Binod
Pramod
Swetha

XPathExpression expr = xpath.compile("//person[age>20]/*/text()"); Output would be
all age that is greater than 20
Binod
24
Male
Pramod
22
Male


There are numbers of xpath expression. You can get from google. Here I showed only few of them. But it is easy to understand .......... :)

Sunday, March 22, 2009

How to use IN clause in iBatis

How to use IN clause in iBatis

1. Table Structure (Table Name: users)

CREATE TABLE users(
username varchar(15) NOT NULL,
name varchar(255) NOT NULL,
password varchar(15) NOT NULL,
CONSTRAINT users_pkey PRIMARY KEY (username))

2. Insert data in this table

3. DAO Methos to fetch username with IN clause
public void getAllUserByName() {
List users;
try {
List names = new ArrayList();
names.add("Bond");
names.add("Josef");
names.add("Robert");
names.add("abcd");

users = sqlMap.queryForList("getAllUserByName",names);
for (int i = 0; i < user =" (User)">NOTE: If you use IN clause then iBatis expects that either you will send List or array. For example you can use names as array like String names[] = {"Robert","Bush","abcd"};

4. Code in SQL config file

<resultMap id="UserMap" class="com.domain.User">
<result property="name" column="username" />
<result property="pass" column="password" />
</resultMap>

<select id="getAllUserByName" resultMap="UserMap">
SELECT username, password from users
WHERE username IN
<iterate open="(" close=")" conjunction=",">
#[]#
</iterate>
</select>

NOTE : In select tag, no need to use parameterClass, it will take either List or array as you send during call the sqlMap.queryForList("getAllUserByName",names);

:) :)

Thursday, March 19, 2009

Create XSD file from XML file

There are many tools to generate XSD from XML file, but I am using here trang.

STEP 1: First download trang from here (choose trang-20030619.zip)
STEP 2: Unzip this file at any location say C:\jar\trang-20030619\trang-20030619
STEP 3: Create one xml file at any location say C:\workspaceAll\XSD\XMLTOXSD\src\StudentInfo.xml

StudentInfo.xml

<?xml version="1.0" encoding="UTF-8"?><StudentData xmlns="http://mycompany.com/hr/schemas;
<Student>
<RollNo>110</RollNo>
<FirstName>Ultimate</FirstName>
<LastName>Answer</LastName>
<ContactNo>9900990011</ContactNo>
</Student>
<Hostel>
<Name>Ganga</Name>
<Location>South Corner</Location>
<RoomNo>20</RoomNo>
</Hostel>
</StudentData>

STEP 4: Now use this command

C:\workspaceAll\XSD\XMLTOXSD\src>java -jar C:\jar\trang-20030619\trang-20030619\trang.jar StudentInfo.xml StudentRecord.xsd

STEP 5: Now you will get StudentRecord.xsd at C:\workspaceAll\XSD\XMLTOXSD\src location. And StudentRecord.xsd will like this

<?xml version="1.0" encoding="UTF-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://mycompany.com/hr/schemas" xmlns:schemas="http://mycompany.com/hr/schemas;
<xs:element name="StudentData">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Student"/>
<xs:element ref="schemas:Hostel"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Student">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:RollNo"/>
<xs:element ref="schemas:FirstName"/>
<xs:element ref="schemas:LastName"/>
<xs:element ref="schemas:ContactNo"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="RollNo" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
<xs:element name="ContactNo" type="xs:integer"/>
<xs:element name="Hostel">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Name"/>
<xs:element ref="schemas:Location"/>
<xs:element ref="schemas:RoomNo"/>
</xs:sequence>

</xs:complexType>
</xs:element> <xs:element name="Name" type="xs:NCName"/>
<xs:element name="Location" type="xs:string"/>
<xs:element name="RoomNo" type="xs:integer"/>
</xs:schema>

It is very easy :)

IMP: If you want to develop any XSD file, so it would be better idea that first write XML file then using trang utility create XSD file. For example, I have below xml (persons.xml)
<?xml version="1.0" ?>
<information>
<person id="1">
<name>Binod</name>
<age>24</age>
<gender>Male</gender>
</person>

<person id="2">
<name>Pramod</name>
<age>22</age>
<gender>Male</gender>
</person>

<person id="3">
<name>Swetha</name>
<age>19</age>
<gender>Female</gender>
</person>
</information>
Now use the trang command and get your XSD file. I kind suggestion, never dig your head to develop XSD file by using XSD tags. Always use trang command. :)
java -jar c:\jar\trang-20030619\trang-20030619\trang.jar persons.xml personsFormat.xsd
personsFormat.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="information">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" ref="person"/>
</xs:sequence>
</xs:complexType>

</xs:element>
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="age"/>
<xs:element ref="gender"/>
</xs:sequence>
<xs:attribute name="id" use="required" type="xs:integer"/>
</xs:complexType>
</xs:element>
<xs:element name="name" type="xs:NCName"/>
<xs:element name="age" type="xs:integer"/>
<xs:element name="gender" type="xs:NCName"/>
</xs:schema>



Validate XML file using XSD in Java

XSD stands for XML Schema Definition.
XSD can be used to express a set of rules to which an XML document must conform in order to be considered 'valid' according to that schema. It used to validate the xml file.

Here we have :
1.one xml file (holiday-request.xml),
2. one xsd file (hr.xsd) and
3. one jave file (ValidateXMLUsingXSD.java) to validate xml file using the xsd file.
4. You have to add two jar file in your project (jaxb1-impl.jar and dom4j-1.6.1.jar) that you can google and download.

holiday-request.xml
<?xml version="1.0" encoding="UTF-8"?>
<HolidayRequest xmlns="http://mycompany.com/hr/schemas;
<Holiday>
<StartDate>2006-07-03</StartDate>
<EndDate>2006-07-07</EndDate>
</Holiday>

<Employee>
<Number>42</Number>
<FirstName>Binod</FirstName>
<LastName>Suman</LastName>
</Employee>
</HolidayRequest>

hr.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://mycompany.com/hr/schemas"
xmlns:schemas="http://mycompany.com/hr/schemas;
<xs:element name="HolidayRequest">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Holiday"/>
<xs:element ref="schemas:Employee"/>
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name="Holiday">
<xs:complexType>
<xs:sequence>
<xs:element ref="schemas:StartDate"/>
<xs:element ref="schemas:EndDate"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="StartDate" type="xs:NMTOKEN"/>
<xs:element name="EndDate" type="xs:NMTOKEN"/>
<xs:element name="Employee"> <xs:complexType>
<xs:sequence>
<xs:element ref="schemas:Number"/>
<xs:element ref="schemas:FirstName"/>
<xs:element ref="schemas:LastName"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:NCName"/>
<xs:element name="LastName" type="xs:NCName"/>
</xs:schema>

ValidateXMLUsingXSD.java

import java.io.File;
import org.iso_relax.verifier.Schema;
import org.iso_relax.verifier.Verifier;
import org.iso_relax.verifier.VerifierFactory;
import org.iso_relax.verifier.VerifierHandler;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
public class ValidateXMLUsingXSD {
private String schemaURI;
private Document document;
public ValidateXMLUsingXSD(Document document, String schemaURI) {
this.schemaURI = schemaURI;
this.document = document;
}
public boolean validate() throws Exception {
VerifierFactory factory = new com.sun.msv.verifier.jarv.TheFactoryImpl();
Schema schema = factory.compileSchema(schemaURI);
Verifier verifier = schema.newVerifier();
verifier.setErrorHandler(new ErrorHandler() {
public void error(SAXParseException saxParseEx) {
System.out.println("ERROR :: ");
saxParseEx.printStackTrace();
}
public void fatalError(SAXParseException saxParseEx) {
System.out.println("FATAL ERROR :: ");
saxParseEx.printStackTrace();
}
public void warning(SAXParseException saxParseEx) {
System.out.println("WARNING :: ");
saxParseEx.printStackTrace();
}
});
VerifierHandler handler = verifier.getVerifierHandler();
SAXWriter writer = new SAXWriter(handler);
writer.write(document);
return handler.isValid();
}
public static void main(String []args) throws DocumentException{
SAXReader reader=new SAXReader();
Document document=reader.read(new File("src\\holiday-request.xml"));
ValidateXMLUsingXSD val=new ValidateXMLUsingXSD(document,"src\\hr.xsd");
try {
System.out.println("Result :: "+val.validate());
if(val.validate()){
System.out.println("XML IS COMPATIBLE WITH XSD SCHEMA");
}
} catch (Exception e) {
System.out.println("0");
e.printStackTrace();
}
}
}

Now, if you will run, then you will get "XML IS COMPATIBLE WITH XSD SCHEMA" output, if your xml is compatible with xsd otherwise you will get error output.
For test you can change any datatype in xml file and check the result.
So, simple ............. :)

java