Sunday, 18 September 2016

gson: JSON Utility class


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * @author harikrishna_gurram
 *
 */
public class JSONUtil {
 private static Gson gson = new Gson();
 private static Gson exclusedGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
 private static Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();

 /**
  * @param obj
  * @return json string of this object.
  */
 public static String getJson(Object obj) {
  return gson.toJson(obj);
 }

 /**
  * @param obj
  * @return json string of this object.
  */
 public static String getOnlyExposedJson(Object obj) {
  return exclusedGson.toJson(obj);
 }

 /**
  * @param obj
  * @return json string of this object (Pretty json).
  */
 public static String getPrettyJson(Object obj) {
  return prettyGson.toJson(obj);
 }

 /**
  * Convert given json string to object.
  * 
  * @param json
  * @param obj
  * @return an object by populating properties with json data.
  */
 public static <T> T getObject(String json, Class<T> clazz) {
  return gson.fromJson(json, clazz);
 }

}

Previous                                                 Next                                                 Home

Saturday, 17 September 2016

Itext: Specifying margins to page

Document class provide following constructor, where you can specify page size, left, right, top and bottom margins of a page.

public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom)
pageSize specifies the pageSize
marginLeft specifies the margin on the left
marginRight specifies the margin on the right
marginTop specifies the margin on the top
marginBottom specifies the margin on the bottom

What are the default values for margins?
As per itext documentation, default constructor defined like below.

public Document(Rectangle pageSize) {
         this(pageSize, 36, 36, 36, 36);
}

36/72 = 0.5 inches is the default for margins.

I copied following content from ISO 32000 specification.

In PDF versions earlier than PDF 1.6, the size of the default user space unit is fixed at 1 / 72 inch. In Acrobat viewers earlier than version 4.0, the minimum allowed page size is 72 by 72 units in default
user space (1 by 1 inch); the maximum is 3240 by 3240 units (45 by 45 inches).

 In Acrobat versions 5.0 and later, the minimum allowed page size is 3 by 3 units (approximately 0.04 by 0.04 inch); the maximum is 14,400 by 14,400 units (200 by 200 inches).

Beginning with PDF 1.6, the size of the default user space unit may be set with the UserUnit entry of the page dictionary. Acrobat 7.0 supports a maximum UserUnit value of 75,000, which gives a

maximum page dimension of 15,000,000 inches (14,400 * 75,000 * 1 / 72). The minimum UserUnit value is 1.0 (the default).

package com.learn.tutorial;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  // 288/72 = 4 and 720/72 = 10 inches
  Document document = new Document(new Rectangle(288, 720), 36, 72, 144, 288);
  PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
  document.open();
  document.add(new Paragraph("Hello World!"));
  document.close();
 }
}




Previous                                                 Next                                                 Home

Itext: Specifying page size

itextpdf API provides PageSize class to specify page size of the pdf document. PageSize class provides number of built-in constants to support A1, A2, A3, A4...A10 and B1, B2...B10 formats.

What is the default page size in itext?
A4 (8.3 X  11.7 inches).

Following application create A4 size pdf document.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  Document document = new Document(PageSize.A4);
  PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
  document.open();
  document.add(new Paragraph("Hello World!"));
  document.close();
 }
}
By default page size is measured in inches. I copied following content from ISO 32000 specification.

In PDF versions earlier than PDF 1.6, the size of the default user space unit is fixed at 1 / 72 inch. In Acrobat viewers earlier than version 4.0, the minimum allowed page size is 72 by 72 units in default
user space (1 by 1 inch); the maximum is 3240 by 3240 units (45 by 45 inches).

 In Acrobat versions 5.0 and later, the minimum allowed page size is 3 by 3 units (approximately 0.04 by 0.04 inch); the maximum is 14,400 by 14,400 units (200 by 200 inches).

Beginning with PDF 1.6, the size of the default user space unit may be set with the UserUnit entry of the page dictionary. Acrobat 7.0 supports a maximum UserUnit value of 75,000, which gives a
maximum page dimension of 15,000,000 inches (14,400 * 75,000 * 1 / 72). The minimum UserUnit value is 1.0 (the default).

You can also specify customized page size using Rectangle instance. Rectangle class provide following constructors to get an instance of this class.

public Rectangle(final float llx, final float lly, final float urx, final float ury)
public Rectangle(final float llx, final float lly, final float urx, final float ury, final int rotation)
public Rectangle(final float urx, final float ury, final int rotation)

llx     specifies lower left x
lly     specifies lower left y
urx    specifies upper right x
ury    specifies upper right y
rotation specifies the rotation

How to create 4 X 10 inches document.
Create a rectangle instance with arguments 4*72, 10*72.

Document document = new Document(new Rectangle(288, 720));
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  // 288/72 = 4 and 720/72 = 10 inches
  Document document = new Document(new Rectangle(288, 720));
  PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
  document.open();
  document.add(new Paragraph("Hello World!"));
  document.close();
 }
}

Run above program, it creates a document with 4X10 inches. To reconfirm, open PDF document, go to file -> properties -> go to description tab, you can able to see the page size.



Previous                                                 Next                                                 Home

Friday, 16 September 2016

itext: Hello World Application

In this post, I am going to explain how to create a pdf document. Following step-by-step procedure explains, how to create and write the message “Hello World” to the pdf document.

Step 1: Create Document instance.
Document document = new Document();

Step 2: Get the instance of PdfWriter, by passing the Document instance and pdf file name as arguments.

PdfWriter.getInstance(document, new FileOutputStream("empty.pdf"));

Step 3: Open pdf document, write some data and close the document.

document.open();
document.add(new Paragraph("Hello World!"));
document.close();

Following is the complete working application.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  Document document = new Document();
  PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
  document.open();
  document.add(new Paragraph("Hello World!"));
  document.close();
 }
}


Run above application, you can able to see ‘hello.pdf’ file with message ‘Hello World!’ in it.

Previous                                                 Next                                                 Home

Thursday, 15 September 2016

Introduction to itext

Itext is open source Java API to work with PDF (Portable document format) files. Itext library released under AGPL license.(Affero General Public License) If you want to use itext for commercial purpose, you better need to purchase license. To guard your intellectual property, receive professional support and take advantage of iText's advanced features, however, a commercial license is required. In this tutorial series, I am going to cover basic itext apis.

I am going to use following maven dependency.
<dependencies>
  <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.9</version>
  </dependency>

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.5</version>
  </dependency>

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.5</version>
  </dependency>
</dependencies>

What can I do with itext library?
By using itext library, you can
a.   Create PDF documents
b.   Read PDF documents
c.    Write data to PDF documents
d.   Manipulate existing PDF documents
e.   Generate PDF files from XML file (or) from the data from database (like SQL tables).
f.    You can add page numbers, bookmarks, watermarks etc.,
g.   Fill out the data in interactive forms and lot more

Reference



Previous                                                 Next                                                 Home

Sunday, 11 September 2016

ProGuard: Code Obfuscation tool

ProGuard is a Java class file shrinker and code obfuscator.

What is Obfuscation?
Obfuscation is the process of converting programming code to some other form, so it is difficult to perform reverse engineering (Difficult to understand by humans). Now a days, sophisticated Java decompilers are available, which convert Java class files to source code. By using any good decompiler, one can reverse engineer the code, which is a security threat, by using obfuscation, we can make this reverse engineering process hard.

How ProGuard helps to my project?
a.   It detect and remove unused classes, method and attributes.
b.   List the dead code, so you can remove it from the source code.
c.    Rename the classes, fields, methods with meaning less names, so it is difficult to reverse engineer.

Where can I download Proguard?
You can download ProGuard from following location.

License
GNU General Public License (GPL)

User Interface
Provides both command line and graphical user interface.

How ProGuard perform Obfuscation?
The process is divided into 4 steps.

a.   Shrink: Detects and removes unused classes, fields, methods, and attributes.
b.   Optimize: Analyzes and optimizes the bytecode of the methods.
c.    Obfuscate: Renames the remaining classes, fields, and methods using short meaningless names.
d.   Preverify: Adds preverification information to Java classes, it is required for Java Micro Edition and for Java 6 and higher.

How to use Progard in command line mode?
java -jar proguard.jar –injars inputJarFilesLocation –outjars outputJarFilesLocation

Ex:
java -jar proguard.jar -injars input.jar -outjars out.jar

For full command line options usage, refer following link.

How to use ProGuard in GUI mode?
Use following command to open ProGuard in GUI mode.
java -jar proguardgui.jar

For more information about ProGuard in GUI mode, refer following link.

What is the current stable version?
At the time of writing this article, the stable version is Version 5.2, released in January 2015.

Useful resources       
Available Java Obfuscators

Proguard Obfuscation Metrics


Saturday, 3 September 2016

itext tutorial

Introduction To Itext

      Introduction to itext
      Hello World Application
      Specifying page size
      Specifying margins to page

Chunk Object

      Working with Chunk object
      Specify superscript and subscripts
      Add background color to chunk

Phrase & Paragraph objects

      Phrase object
      Paragraph object
      Adding chunks, phrases to a paragraph
      Set alignment to paragraph
      Changing the indentation
      Set space between two paragraphs

List Object

      Working with List object
      Changing list symbol
      Set indentation of list item
      Set prepend and append data to symbol of list items
      RomanList
      GreekList
      ZapfDingbatsNumberList
      Set the list symbol
      Set the first number in the ordered list

Anchor, Chapter

      Anchor object: Specify hyper links
      Chapter and Section Object

Working with Images

      Image object
      Rotating image

Working with tables

      Working with tables
      Create table with no border
      Set background color to table
      Adding background image to a cell in table
      Add hyper links to table
      Add list of images to same cell in table
      Align text in table
      Set border colors to a table
      change cell sizes in table
      Working with colspan and rowspan
      set headers to table
      Writing big tables
      Nested tables
      Write selected rows from table to a document
      Underline and strike-through in a cell

Previous                                                 Next                                                 Home