Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, 2 October 2014

Generate Pdfs in Java using iText

Today we are going to see how we can generate PDFs using java. So lets move on with a simple PDF Generation Java Class.
Let me clarify one thing that to run this code there are few prerequisites
  1. iText (You can get it from here) else its included in the code.
  2. Java Development Kit
  3. Any Compiler (Eclipse , Netbeans etc)

package com.rc.generatepdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class GeneratePdf {public static void main(String[] args) {try {
OutputStream file = new FileOutputStream(new File("D:\\PDF_RoyalCyber.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
//Inserting Image in PDF
Image image = Image.getInstance ("Images/RC Logo.png");
image.scaleAbsolute(511f, 150f);//image width,height
//Inserting Table in PDF
PdfPTable table=new PdfPTable(3);
PdfPCell cell = new PdfPCell (new Paragraph ("www.royalcyber.com"));
cell.setColspan (3);
cell.setHorizontalAlignment (Element.ALIGN_CENTER);
cell.setPadding (10.0f);
cell.setBackgroundColor (new BaseColor (140, 221, 8));
table.addCell(cell);
table.addCell("Name");
table.addCell("Address");
table.addCell("Country");
table.addCell("Royal Cyber");
table.addCell("Chicago");
table.addCell("United States");
table.setSpacingBefore(30.0f); // Space Before table starts, like margin-top in CSS
table.setSpacingAfter(30.0f); // Space After table starts, like margin-Bottom in CSS
//Inserting List in PDF
List list=new List(true,30);
list.add(new ListItem("Java"));
list.add(new ListItem("Php"));
list.add(new ListItem("IBM Webspehere Commerce"));
//Now Insert Every Thing Into PDF Document
document.open();//PDF document opened........
document.add(image);
document.add(new Paragraph("Dear www.royalcyber.com"));
document.add(new Paragraph("Document Generated On - "+new Date().toString()));
document.add(table);
document.newPage(); //Opened new page
document.add(list); //In the new page we are going to add list
document.close();
file.close();
System.out.println("Pdf created successfully..");
} catch (Exception e) {
e.printStackTrace();
}
}
}
So Now its time to explain that how this code works and what will be the output we will get after running this code. The complete Code have info comments regarding each action.
At First Step we are defining a file name with complete location (Where ever you want to generate PDF file). Then getting Image from Location as image , so that we may insert it later in PDF. Creating Table and then adding cells and then populating those cells with data.
Creating List and adding List Items in List. Till now what we have done is just write these things inside code but haven't wrote them in PDF file So now lets move towards writing all previous defined data in PDF.
First of all we need to open PDF Document for writing the we have added data in this form
  1. Added image
  2. Added 2 new paragraphs
  3. Added table which consist cells with populated data.
  4. Created New page.
  5. Added List on that new page.
  6. Then closed the document
  7. Notified User in the console by printing Document has been generated.
I am also attaching the above given code as Exported project from Eclipse, Which consist all required images and Libs and i am also attaching PDF Output generated from this Code.
You can Get Code Here : GeneratePdf
You can get output File Here : PDF_RoyalCyber


Sunday, 28 September 2014

Validating Email Address Using Regular Expressions In Java


Few days back working on some project, i come across some issue to validate just email in between complete project and email was needed to be validate at multiple places in the code so i thought to write a class like a wrapper Email Validator so that we can use at at any instance. so let me share that email Validator class with you guys. So the important thing that i have used is that i have used regular expression to validate email address. The Email Validator Class is given below.
//Email Validator Class
package EmailValidate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Validate hex with regular expression
*
* @param hex
* hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
As we have wrote wrapper class above now the question arise that how we are going use it as validator of email address.
Validating Email in a JtextField
Emailvalidator emailValidator = new Emailvalidator();
if(!emailValidator.validate(emailField.getText().trim())) {
System.out.print("Invalid Email ID");
/*
Perform any action here that you want to show while email address is invalid 
i-e change the color of the field */
}
Validating Email in Console
I will show this part writing a small program which will ask for email id in console, If the email Id is valid it will print Valid Email else it will print Invalid Email ID. So let's move on with the code
package EmailValidate;
import java.util.Scanner;
public class VEmail {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Enter email address :");
String EmText = input.next();
EmailValidator emailValidator = new EmailValidator();
if(!emailValidator.validate(EmText.trim())) {
System.out.print("Invalid Email ID");
}
else
{
System.out.print("Valid Email ID");
}
}
}
So that's all for Using Email Validator for multiple purposes by writing a general class.