Exporting Excel and PDF files from EXTJS grid.

Hi All,

Sencha EXTJS as you know is a Rich Javascript platform.

Here I will describe how to export Excel and PDF files on the go from EXTJS grid on the client side using Javascript only. Well I know some of you might be aware of this feature but this post might be helpful for many.

Well to begin this tutorial will include simplest ways of achieving the desired output (i.e. generation of Excel and a PDF file.)

A> Generation of Excel file from the grid.

I will assume you have already configured your EXTJS project and everything is working fine.

For genaration of excel from EXTJS grid we would be using     —-    Ext.ux.exporter  with adobe Downloadify  for downloading the file .

  1. Download my version of Exporter from SourceForge-> https://sourceforge.net/projects/extjsexcelexport/          >              Files
  2. Once you download it, unpack the entire contents in “/extjs/ux”  folder.
  3. If you have a parent JSP file or HTML file where you already have included the ext-all-debug.js, include the following entries.              <script type=”text/javascript” src=”extjs/ux/exporter/Exporter.js”></script>
    <script type=”text/javascript” src=”extjs/ux/exporter/swfobject.js”></script>
    <script type=”text/javascript” src=”extjs/ux/exporter/downloadify.min.js”></script>
  4. Now, if you have a parent JS file like Application.js include  the following lines at the top                                                             Ext.Loader.setConfig({ enabled : true });
    Ext.Loader.setPath(‘Ext.ux’, ‘extjs/ux’);
  5. Once that is done, you can directly use the  Exporter button widget in the docked items of the Grid.{
    xtype: ‘pagingtoolbar’,
    store: ‘MyProject.CountryStore’,
    margin:’0 0 0 10′,
    id :’countryPaging’,
    cls :’paginationToolbar’,
    items: [
    {
    xtype: ‘exporterbutton’
    }]
    }

We are done…Please modify the Worksheet.js file which I have customized as per my project requirements, where in we had to include the search criteria. If you dont need that you can eliminate the buildSearchParams, method. Instead write your own logic here.

 B> Generation of PDF file from the grid.

We will be using JSPDF for this. JSPDF is a third party tool, which is developed by parallax software labs. Though it is stable I could not get it to working for generation of PDF from HTML. It is still in development phase.

JSPDF works with JQuery, EXTJs and Jqeuery usage simultaneously is not recommended in my project.

The only feature of JSPDF that works for me, is normal text generation and drawing lines.

What I did is I converted the Grid data into Arrays, i.e.      gridData = [{[cell1],[cell2]…}, {[cell1],[cell2].. }, … ]  likewise.

Now, iterate the array and manually position the elements into PDF.

var doc = new jsPDF(‘p’, ‘pt’, ‘a1’, true);

Ext.each(data, function(row, i){
       if(countRow%(maxRowsOnPage) == 0 && i != 0 ){

    //adding a new pager after max no. of rows on page         

            doc.addPage();
             pageNo ++;
            countRow = 0;
            doc.setDrawColor(0,0,0);
            doc.line(35, 125, 250*(cols), 125);
       }
       Ext.each(row, function(cell, j){
             doc.text(45+(j*200), 145+(countRow*30), cell ) ;

            //vertical lines
          doc.line(35+(j*200), 125+(countRow*30), 35+(j*200), 155+(countRow*30) );

        }

                      //Last vertical lines
         doc.line(50+((cols+1)*200), 125+(countRow*30), 50+((cols+1)*200), 155+(countRow*30) );
         //row horizontal lines
         doc.line(35, 155+(countRow*30), 250*cols , 155+(countRow*30));
});

 doc.save(‘GridExport.pdf’);

 

You can put this piece of code inside the listener   handler : function() {} of the PDF icon in your paging toolbar.

One more thing for this to work, download jsPDF from gitHub –> https://github.com/MrRio/jsPDF and  only include these two files in your parent JSP, thats it.

 <script type=”text/javascript” src=”extjs/jsPDF/dist/jspdf.debug.js”></script>
<script type=”text/javascript” src=”extjs/jsPDF/jspdf.js”></script>

Hope this solves your problems…keep posting your comments and let me know if this post is of any use to you.

For any queries please write to me on subhadip0608@gmail.com

Posted in Uncategorized | Tagged , | Leave a comment

Java Concepts that we must know.

  1. hashCode() & equals() method significance in Collections API :
  • public boolean equals(Object obj) :

This method checks if the object passed to this method is equal to the object on which it is invoked. Default implementation is just comparing the values of these two Object or “Shallow Comparison”. However we can use it to compare Object members using a “Deep Comparison”

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

equals() is used in most collections to determine if a collection contains a given element. For instance:

List list = new ArrayList();list.add(“123”); boolean contains123 = list.contains(“123”);

The ArrayList iterates all its elements and execute “123”.equals(element) to determine if the element is equal to the parameter object “123”. It is the String.equals() implementation that determines if two strings are equal.

The equals() method is also used when removing elements. For instance:

List list = new ArrayList();list.add(“123”); boolean removed = list.remove(“123”);

The ArrayList again iterates all its elements and execute “123”.equals(element) to determine if the element is equal to the parameter object “123”. The first element it finds that is equal to the given parameter “123” is removed.

  • public int hashCode()

This method returns the hashCode or an integer value for the object on which it is invoked.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

The hashCode() method of objects is used when you insert them into a HashTable, HashMap or HashSet.

When we insert an object in a HashTable the hashCode value of the Key is calculated. This value is used to find out where the actual object is stored.

hash(key)  =  Index of the bucket where the Value can be found.

The hash code value only points to certain area of the “Bucket” where the object might be found. Since hashCode does not guarantee the location of the Object as two Keys may have the same hashcode. The hashtable then iterates this area i.e, area where all the keys having same hash codeand checks with key’s equals() method to find the right key(). Once the key is found then the object for that corresponding key is returned.

2 methods to deal with collisions of hash values of the keys.

Liner Probing and Separate Chaining.

In Linear Probing, the value is stored in the next available position on the array. So this leads to problems as the next available position on the array may be last index. so this leads to issues in performance for searching ,add and delete algorithms.

Separate Chaining

hashcode

Here for example: we have keys like ‘A’,’B’, ‘C’, ‘D’, ‘E’ ….

lets say,

hash(A) = 1 ,  hash(B) = 1 ,  hash(C) = 1,  hash(D) = 2, hash(E) = 1

Then 1 is the index of the bucket. for keys A, B, C & E, so we don’t have to look anywhere other than the bucket position 1 for the values of these 4 keys. We have a linked list pointing to the next element on the same bucket. So we need to check fewer records.

a

 

  •  Why do we always override hashcode() if overriding equals() ?

In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object. If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode() will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections.

 

2) Garbage Collection : Garbage Collection in java is bit different than what we think it in JVM. We think GC tracks the dead objects but in fact JVM GC tracks live objects and rest are garbage.

The Operating System allocates HEAP memory in advance to be managed by JVM. This leads to

  • Object Creation is faster as it is not managed by the OS. Allocation simply claims the some portion of memory array and moves the offset pointer forward.
  • When Object is no longer used, the Garbage Collector reclaims the memory and re uses it for future Object allocation. No Explicit deletion occurs and no memory is given back to the OS.

All Objects like (a) Class Objects, (b) Static Variables and event the code itself are heap objects managed by the JVM and not the OS.

Now all the objects which are referenced are Alive and those which are not referenced are reclaimed for re usage by the JVM.

  • Garbage Collection Roots : GC roots are the special object that are always Alive. So all objects having GC root at their base are Alive too.gc

A simple Java Application has the following GC roots for example

  1. Local variables in main method,
  2. The Main Thread,
  3. Static variables of the main Class.
  • Mark & Sweep Algorithm:

In order to find which objects are alive and which objects are to be garbage collected. JVM uses a mark and sweep algorithm.

It is a two step process

  1. The Algorithm traverses all the objects starting from its GC root and marks every object found as Alive or referenced.
  2. All main memory which are not occupied by the marked objects are reclaimed for re use for future object allocation and marked as free i.e. swept of all unused objects.

Still there are chances that a Developer has forgotten to de-reference the unused objects in code, so the M&S algorithm can not free those memory. So we need to be careful about the same in our coding.

 

3) Threads
Two ways to create threads
1.  Thread Subclass:
We have to extend the Thread class and override the run () method.

public class MyThread extends Thread {
       public void run(){
          System.out.println(“MyThread running”);
      }
     }

To start the thread:-
MyThread myThread = new MyThread();
myTread.start();

2. Implement Runnable Interface:

Implement the runnable interface and override the run () method.

public class MyRunnable implements Runnable {
        public void run(){
        System.out.println(“MyRunnable running”);
        }
      }

To start a thread:-
Thread thread = new Thread (new MyRunnable());
 thread.start();

3. Another implementation using runnable anonymous block:

Runnable myRunnable = new Runnable(){
     public void run(){
       System.out.println(“Runnable running”);
    }
}
Thread thread = new Thread(myRunnable);
thread.start();

 

Race conditions and Critical Section.
The situation where two theads compete for the same resource and
where the sequence of access is significant, it is called Race Condition.
An the code section leading to race condition is called Critical Section.

It can be averted by proper synchronization.

Thread Life Cycle

thread-life-cycle-in-java-flowchart

Posted in Java Tutorial | Leave a comment