Tuesday, March 18, 2014

PDF password protection

In this tutorial, I am going to show you how to protect a PDF document by passwords so that users that do not have permissions cannot open or modify the content of the PDF document. You can set two passwords to the PDF document,  a user password and an owner password. The user password must be entered before the PDF document can be opened in Adobe Reader or Foxit Reader. The owner password applies restrictions to the PDF document. For example, you can  allow only printing and copying to the PDF document.
By using iText library you can set the passwords to the PDF document by using the setEncryption method of PdfWriter class. The general form of the setEncryption method is shown below:

setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType)

- userPassword--an array of bytes that is the user password.

- ownerPassword--an array of bytes that is the owner password.

- permissions--permissions or restrictions that will be applied to the PDF document. These permissions can be AllowPrinting, AllowCopy, AllowScreenReaders, AllowFillIn, AllowAssembly, or AllowDegradedPrinting.
- encryptionType--the type of encryption. The encryption type can be one of the following STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.

Example:

import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;



public class PdfItext {
public static void main(String[] args){
setPasswords();
}

static void setPasswords(){
try{
//create a document object
Document doc = new Document();
//FileOutputStream object to write the pdf file
String path="d:/pdfdocprotected.pdf";
FileOutputStream fos=new FileOutputStream(path);
//get PdfWriter object
PdfWriter writer =PdfWriter.getInstance(doc,fos);
//convert strings of passwords to arrays of bytes
byte[] USER="Hello".getBytes();
byte[] OWNER="world".getBytes();
//spcify encryption of the document
writer.setEncryption(USER, OWNER, PdfWriter.ALLOW_PRINTING,

PdfWriter.ENCRYPTION_AES_256);          
      writer.createXmpMetadata();
//open the document for writing
doc.open();
//write a paragraph to the document
doc.add(new Paragraph("This PDF document is protected."));
//close the document
doc.close();
//view the result pdf file
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
dt.open(new File(path));
}
}catch(Exception e){e.printStackTrace();}
}
}

When you run the example code above, you might get the dependency error as shown below. To fix the error, you will download the extra jar files from http://sourceforge.net/projects/itext/files/extrajars/. Then extract the zip file and add the bcprov-jdk15on-1.48.jar file to the project. After that, run the program again.

ASN1Encodable not found error


PDF Viewer - Reader

Monday, March 10, 2014

iText


iText is known to be an open source free library to create and manipulate PDF files in Java programming language. This useful library is originally developed by Bruno Lowagie and others since 2001. In this tutorial, I am going to show you how to configure iText library in Eclipse and create a PDF file to display the Hello World text.
To get start, you need to create a Java project in Eclipse. After the process of project creation  completes, you will download the latest iText library from the URL: http://sourceforge.net/projects/itext/files/latest/download. You will get the iText library in zip file format. Simply extract the zip file to a folder in your computer. In the folder, you will see a lot of jar files. However, the main one is itextpdf-5.5.0.jar. You need to add this jar file to the Java project before you begin writing Java code to create a PDF file or manipulate the file. To add the jar file to your current Java project in Eclipse, you will select Properties... from the Project menu. When the Properties dialog displays, click Java Build Path->Libraries. Then click Add External Libraries...A file dialog is open. Navigate to the folder that contains the itextpdf-5.5.0.jar. Select the file and click OK. Now the iText library is added to your project.

create pdf in itext

To create a PDF file, first you need to create a class in the project. You can name the class whatever you want. However, in this tutorial, the name of the class is PdfItext. Below is an example Java code to create a PDF file by using iText library.

import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfItext {
public static void main(String[] args){
createPdf();
}

static void createPdf(){
try{
//create a document object
Document doc = new Document();
//FileOutputStream object to write the pdf file
FileOutputStream fos=new FileOutputStream("pdfdoc.pdf");
//get PdfWriter object
PdfWriter.getInstance(doc,fos);
//open the document for writing
doc.open();
//write a paragraph to the document
doc.add(new Paragraph("Hello World"));
//close the document
doc.close();
//view the result pdf file
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
dt.open(new File("pdfdoc.pdf"));
}
}catch(Exception e){e.printStackTrace();}
}
}

The Java code above creates a PDF file called pdfdoc.pdf in the current working folder of your project. iText does five steps to create the PDF file you:
-Create a PDF document object.
-Get PDFWriter object.
-Open the document.
-Write content to the document.
-Close the document.






compass app

Sunday, December 22, 2013

Applet application

Besides, desktop applications that run on operating systems, Java allows you to create applications that can be run on web browsers that enable Java or applet viewers. These types of applications are called applet applications. The java.applet package has Applet class that provides necessary support for applet applications.

Unlike desktop or stand-alone application, applet does not require the main method. The execution of the applet does not begin at the main method. Rather, Applet class provides different methods serving as the basic mechanism of executing an applet application on a web browser or applet viewer. These methods are init(), start(), paint(), stop(), and destroy(). When an applet begins, the init() methods is called. You can use this method to initialize variables. The init() method is called once. The start() method is called after the init() method. This method is called every time the applet's HTML page displays on the web browser. When the user leaves the HTML page that contains applet, the applet stops by calling the stop() method. When he/she comes back to that page, the start() method will be called again to resume the applet. The destroy() method will be called after the stop method to free up resources used by applet from memory. The paint method is called each time the applet needs to redraw its output. For example, the applet draw its output when it starts and it is minimized and restored.

Create an applet

To create an applet application, you will extend the Applet class in java.applet package. The following example code is a simple applet application to display an image and a button that can be clicked to change the background color of the applet's window. You need an image file called gmaptr.png.

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
/* 
<applet code="AppletApp" width=600 height=300> 
</applet> 
*/

public class AppletApp extends Applet implements ActionListener{

public void init(){
setSize(600,300);
setBackground(Color.LIGHT_GRAY);
Button bt=new Button("Change Color");
bt.setBackground(Color.PINK);
bt.addActionListener(this);
add(bt);

}

public void paint(Graphics g){
try {
MediaTracker mt=new MediaTracker(this);
URL imgurl=new URL(getCodeBase().toString()+"gmaptr.png");
Image img=getImage(imgurl);
mt.addImage(img,0);
mt.waitForID(0);
g.drawImage(img,10, 10,this);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showStatus("There are one button and one image on the applet window.");
}

public void actionPerformed(ActionEvent e){
Color c=getBackground();
if(c==Color.BLACK)
setBackground(Color.BLUE);
else

setBackground(Color.BLACK);
}
}


You need to create AppletApp.class file from the source code above. This can be done by compiling the source code with the javac command from command prompt.

Embed the applet in HTML file

In order to execute the applet on a web browser, you need to create an HTML file that includes the applet. You can include the applet within the HTML document by using the <applet> tag. Below is an example HTML file.

<!DOCTYPE html>
<html>
<head> <title>Applet Test</title>
</head>
<body>
<applet code="AppletApp" width=600 height=300>
</applet>
</body>

</html>

After you create the HTML file that contains applet, you can execute the applet by using the appletviewer tool that comes with JDK. The command line below will execute the AppletApp application in the appletviewer from command prompt.

D:\sitedemo\AppletApp\AppletTest\bin>appletviewer AppletApp.html


run applet from command prompt


If you are Eclipse user, you can execute the applet in the appletviewer from Eclipse by clicking the Run menu item.
Besides running the applet from command prompt and Eclipse, you can run the applet in a web browser that supports Java. You need to copy the AppleAppt.class, AppletApp.html, and other related files to a directory of your web server. Then run the HTML file as you do with other HTML, php, or jsp pages. In my machine i have Chrome browser and WampServer installed.


run applet from web browser


Thursday, December 5, 2013

XML processing in Java

XML and HTML are Markup Languages. However, they are different. XML is generally used to store and transport structured data while HTML is used to format and present the data. Today XML is the most common tool for data transmissions on the web. In XML file, you can define your own tags or elements starting from a root tag and then its children tags. Here is an example of an XML file:

xml file example


The root element is Books. Under the root element, there are two sub-elements or children elements Book.

This tutorial is designed for people who come to work with XML file in Java. After completing the tutorial, you will be able to create an XML document and save it to a file, read data from an XML file, and modify elements in the XML file by using JDOM library. With the JDOM libary, XML file can be easily created, read, and modified.

Create XML document and Save it to a file

To create an XML document, first you will use the Element class to create a root element object. Then create a document object by using the Document class to wrap the root object. A child element object can also be constructed by using the Element class and added to root element by using the addContent method. You can add many children to the root element. To save the XML document to a file, you will use the XMLOutputter class. The XMLOutputter class has a method called output that can be used to write the document to the file.  See the example code below:

public static void createXML(){
//create a root element
Element root=new Element("Books");
//construct the document object with the root
Document doc=new Document(new Element("Books"));
//create first child element
Element b1=new Element("Book");
b1.setAttribute("Title","C++ for beginners");
b1.addContent(new Element("Author").setText("Dara"));
b1.addContent(new Element("Year").setText("2011"));
//add the first child to the root
root.addContent(b1);

//create second child element
Element b2=new Element("Book");
b2.setAttribute("Title","Java for programmers");
b2.addContent(new Element("Author").setText("Dara"));
b2.addContent(new Element("Year").setText("2012"));
//add the second child to the root
root.addContent(b2);
//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
try {
outputter.output(doc, new FileWriter("d:/books.xml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Read data from the XML file

Reading data from an XML file is a common task. This task can be accomplished easily by using JDOM. To read the data from the XML file, you will use SAXBuilder class to construct a document object from the XML file. After you have the document object, you can easily navigate through the document to access all its elements. Read the example code below:


public static void readXML(){
SAXBuilder builder=new SAXBuilder();
try {
//construct document object from the file books.xml
Document doc = (Document)builder.build(new File("d:/books.xml"));
//get the root element
Element root=doc.getRootElement();
//get all children of the root
List<Element> chs=root.getChildren();
for(Element e: chs){
System.out.println("Book:");
System.out.println("\t"+e.getChild("Author").getText());
System.out.println("\t"+e.getChild("Year").getText());
}

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

}

Modify the data in the XML file

Before you can modify the data in the XML file, first you need to read the XML file in to a document object as you did in the previous section. Then you can add new children elements to the root, update data of an element, or delete an element from the document. After you complete the tasks, call the output method of the XMLOutputter class to save change to the file. Here is the example code.

public static void ModifyXML(){
SAXBuilder builder=new SAXBuilder();
try {
Document doc = (Document)builder.build(new File("d:/books.xml"));
Element root=doc.getRootElement();
//create third child element
Element b3=new Element("Book");
b3.setAttribute("Title","C# for beginners");
b3.addContent(new Element("Author").setText("Dara"));
b3.addContent(new Element("Year").setText("2013"));

//add the third child to the root
root.addContent(b3);

//Update the year of a book
List<Element> chs=root.getChildren();
for(Element e: chs){
Element ce=e.getChild("Year");
if(ce.getText().equals("2013")){
ce.setText("2010");
break;
}
}
//Remove a book that has the title "C# for beginners"
for(Element e: chs){
if(e.getAttribute("Title").getValue().endsWith("C# for beginners")){
root.removeContent(e);
break;
}

}

//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(doc, new FileWriter("d:/books.xml"));

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

compass app flashLight app

Monday, November 18, 2013

Splash Screen

Splash screen is a special window that displays in a short time period before the main window of a program or website shows. Generally, on the splash screen, you will see an image that represents an introduction to the program or website. Sometimes, a splash screen displays a progress bar to inform the user about a process that is loading and might take a long time to complete. When the process completes, the splash screen disappears.

In Java, you can use the SplashScreen class (in awt package) to create a splash screen for your program. Alternatively, you can write your own code to create a splash screen. In this tutorial, i prefer to do the latter. First of all, you will have a class that extends the JFrame class. This class will represent the splash screen. In this tutorial, i name it as SimpleSplashScreen. The splash screen has no border and title. So will use the setUndecorated method to hide border and title. On the splash screen, there is an image that provides introductory information of the program. The JLabel component is used to wrap the image. Then it will be added on the splash screen to show the image. In the SimpleSplashScreen class, you need to add two methods. The first method (wait) allows the user to set the time delay of the splash screen. Another method (showScreen) will be invoked in the program to display the splash screen. Simply, when the time is out, the splash screen disappears and the Welcome window is shown.

splash screen

welcome


This is the complete code of the SplashScreen program.

import java.awt.Container;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

class SimpleSplashScreen extends JFrame{
int delay=2000; //default delay time 2 seconds
SimpleSplashScreen(String imgfile){
ImageIcon iicon=new ImageIcon(imgfile);
int iwidth=iicon.getIconWidth();
int iheight=iicon.getIconHeight();
setSize(iwidth,iheight);
setLocationRelativeTo(null);
setUndecorated(true);
Container cont=getContentPane();
JLabel lbl=new JLabel();
lbl.setIcon(iicon);
cont.add(lbl);
}
//set time delay
public void wait(int mills){
delay=mills;
}

public void showScreen(){
setVisible(true); //show the screen
try {
Thread.sleep(delay); //delay the screen
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//close the SplashScreen when time out
dispose();
new MaiInterface();
}
}

class MaiInterface extends JFrame{
MaiInterface(){
setSize(400,300);
setTitle("Your main interface here");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont=getContentPane();
JLabel lbl=new JLabel("Welcome");
lbl.setHorizontalAlignment(JLabel.CENTER);
lbl.setFont(new Font("Arial", Font.BOLD,30));
cont.add(lbl);
setVisible(true);
}
}
public class SplashSr {
public static void main(String[] args){
SimpleSplashScreen sss=new SimpleSplashScreen("d:/splashscreen.png");
sss.wait(5000);
sss.showScreen();
}
}

compass app flashLight app

Saturday, November 16, 2013

Open browser with Desktop class

Desktop is a useful class in Java. It can be used to open the default browser for a specified url, open a default mail client with optional e-mail address, open a file for editing or viewing, and send a file to the default printer.
To do such operatons mentioned above, first you need to create an object of the Desktop class by using the getDesktop method.

Desktop dt=Desktop.getDesktop();

To launch the default browser on your computer with a specified url, you will use the browse method. The browse method has one argument that is a uri object referencing to the url. To obtain the uri object, you have to create a url object that accepts the address of a web page. Then use the toURI method to convert the url object to uri object. The example code below will open the default browser and shows the http://javatheprogram.blogspot.com address on its address box.


open browser


import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;

public class DesktopDemo {

public static void main(String args[]){
//openMail();
try {

URL url=new URL("http://javatheprogram.blogspot.com");
openBrowser(url.toURI());

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//openFile("d:/chart.pdf");

}


public static void openBrowser(URI uri){
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
try {

dt.browse(uri);

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

You can launch an e-mail client program with your specified e-mail address by using the mail method. The mail method accepts one value that is the uri object. When you construct an url object to refer to an e-mail address, the string that will be passed to the URL constructor takes this form: "mailto:e-mail_addresss". The example below will open the e-mail client program with the e-mail address yuk.dara@gmail.com on you machine.

public static void openMail(){
try {
URL url=new URL("mailto:yuk.dara@gmail.com");
Desktop dt=Desktop.getDesktop();
if(Desktop.isDesktopSupported()){
dt.mail(url.toURI());
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

To open a file on your local computer, you will use the open method. This method will take the file object that references to a file on your computer. The code below opens the test.txt file (in drive D) of the computer.

dt.open(new File("d://test.txt"));

If you wan to print the file to the default printer that connects to your computer, you can use the print method. This method also accepts the file object that you want to print. The following code will print the file chart.pdf to the default printer.

dt.print(new File("d:/chart.pdf"));

Tuesday, November 12, 2013

Robot in Java

Robot is an automation class in AWT package of Java. The Robot class is useful when your Java programs requires test automation, mouse, and keyboard controls. The frequently used methods of the Robot class are shown in the table below.

Method Description
createScreenCapture(Rectangle r) This method returns the image (BufferedImage object) of the captured screen. The dimension of the image is specified by the rectangle r argument.
delay(int mills) The delay method will delay the robot before an event occurs.
getPixelColor(int x,int y) The getPixelColor returns the color at the specified coordinate (x,y) on the screen.
keyPress(int key) This method tells the robot to press a key specified by the key argument. The KeyEvent class defines key constants that can be used in this method.
mouseMove(int x,int y) The mouseMove method will move the mouse pointer to the coordinate (x,y) on the screen.
mousePress(int buttons) This method tells the robot to press the mouse button. The value of buttons argument can be found in the InputEvent class.

In the example code below, the robot is commanded to move to the start button on the Task Bar of Window 7 and the mouse is clicked there. Then the word notepad are typed in the search box and the Enter key is pressed to open the NotePad application.

public class RobotDemo {
public static void main(String[] args){
try {
Robot r=new Robot();
//move to the start button on the Task Bar
r.mouseMove(20, (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());
r.mousePress(InputEvent.BUTTON1_MASK); //press the left button
//type notepad in the search box
r.keyPress(KeyEvent.VK_N);
r.keyPress(KeyEvent.VK_O);
r.keyPress(KeyEvent.VK_T);
r.keyPress(KeyEvent.VK_E);
r.keyPress(KeyEvent.VK_P);
r.keyPress(KeyEvent.VK_A);
r.keyPress(KeyEvent.VK_D);
//delay the key pressed
r.delay(1000);
//press enter key
r.keyPress(KeyEvent.VK_ENTER);

} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}



}


Another example is an easy screen capture program. To capture any part of the screen, you will drag the transparent capturing rectangle to a location on the screen where you want to capture. Then press the Enter key to capture the screen. In default, the captured area is 400 pixels wide (width) and 300 pixels long (height). If you wan to increase the dimension of the area to be captured, you will press the ] symbol key. Similarly, to decrease the dimension, simply press the [ symbol key. To minimize the transparent capturing rectangle, press the minus (-) key. When your work completes, you can press the ESC key to exit the program.
The images of the captured screen are saved in the current working directory of the program.

Robot screen capture



import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;

class InUI extends JFrame{
int wWin;
int hWin;
int xWin;
int yWin;
InUI(){

wWin=400;
hWin=300;
setSize(wWin,hWin);
Point loc=MouseInfo.getPointerInfo().getLocation();
xWin=loc.x;
yWin=loc.y;
setLocation(xWin,yWin);
addKeyListener(new KeyDetector());
addMouseMotionListener(new MouseMove());
setUndecorated(true);
setOpacity(0.7f);
Container cont=getContentPane();
cont.setLayout(new BorderLayout());
JLabel lbl=new JLabel("<html>Click and drag this capture area.<br>Press Enter to capture the screen.</html>");
lbl.setHorizontalAlignment(JLabel.CENTER);
cont.add(lbl, BorderLayout.CENTER);
setVisible(true);

}

class KeyDetector extends KeyAdapter{
public void keyPressed(KeyEvent e){
System.out.println(e.getKeyCode());
int code=e.getKeyCode();
if(code==27) //exit the program when the Esc key is pressed. 
System.exit(0);
else if(code==45) //minimize the capture
minimize();
else if(code==91) //decrease capture area
decreaseSize();
else if(code==93) //increase capture area
increaseSize();
else if(code==10){ //capture the screen when Enter key is pressed
minimize();
capture();
}
//else if((code==KeyEvent.VK_X) && (e.getModifiers() & KeyEvent.ALT_MASK)!=0 )
//System.exit(0);

}
}
class MouseMove extends MouseMotionAdapter{
public void mouseDragged(MouseEvent e){
//change location of the capture area when mouse is dragged
setWinLocation(e.getXOnScreen(),e.getYOnScreen());
}
}
public void increaseSize(){
Dimension ds=Toolkit.getDefaultToolkit().getScreenSize();
if(wWin<ds.getWidth()){
wWin+=5;
this.setSize(wWin,hWin);
}
if(hWin<ds.getHeight()){
hWin+=5;
this.setSize(wWin,hWin);
}

}
public void decreaseSize(){
if(wWin>5){
wWin-=5;
this.setSize(wWin,hWin);
}
if(hWin>5){
hWin-=5;
this.setSize(wWin,hWin);
}
}
public void setWinLocation(int x,int y){
xWin=x-wWin/2;
yWin=y-wWin/2;
this.setLocation(new Point(xWin,yWin));
}
public void minimize(){
this.setExtendedState(JFrame.ICONIFIED);
}
public void capture(){
try {
Robot rb=new Robot();
//capture the target part of the screen
BufferedImage bi=rb.createScreenCapture(new Rectangle(xWin,yWin,wWin,hWin));
//save the image
ImageIO.write(bi, "png", new File(System.getProperty("user.dir")+File.separator+"image"+System.currentTimeMillis()+".png"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

public class RobotDemo {
public static void main(String[] args){
new InUI();
   }
}
compass app flashLight app