Wednesday, April 19, 2017

Generating Pagination Numbers

Very often we need to generate series of numbers for pagination. For small number of pages, all the page numbers can be displayed. However, when there are large number of pages, then we need to display only appropriate page numbers.

Below is a Java Code that can be used to generate the sequence.

It can be easily converted into Javascript function and make necessary changes as required to display in your web site.

public class Pagination {

     public static void main(String []args){
        generatePaginationNumbers(150, 5, 13);
     }
     
     public static void generatePaginationNumbers(int totalItems, int pageSize, int currentPage) {
         int DELTA = 3;
         int SHOW_ALL_SIZE = 10;
         int lastPage = totalItems/pageSize;
         if (totalItems > lastPage * pageSize) {
             lastPage++;
         }
         
         currentPage = currentPage < 1 ? 1 : currentPage;
         if (currentPage > lastPage) {
             currentPage = 1;
         }
         
         if (totalItems < 1) {
             return;
         }
         
         if (currentPage > 1) {
             System.out.print("prev ");
         }
         printPaginationPage(1, currentPage);
         if (totalItems > pageSize) {
             printPaginationPage(2, currentPage);
         } else {
             return;
         }
         
         if (currentPage - DELTA > 3 && lastPage > SHOW_ALL_SIZE) {
             System.out.print(" ... ");
         }
         
         int page = lastPage > SHOW_ALL_SIZE ? currentPage - DELTA : 3;
         page = page <= 2 ? 3 : page;
         int end = currentPage + DELTA;
         end = end >= lastPage - 1 ? lastPage - 2 : end;
         for( ; page <= end; page++) {
             printPaginationPage(page, currentPage);
         }
         
         if (page <= lastPage - 2 && lastPage > SHOW_ALL_SIZE) {
             System.out.print(" ... ");
         }
         
         printPaginationPage(lastPage - 1, currentPage);
         printPaginationPage(lastPage, currentPage);
         
         if (currentPage < lastPage) {
             System.out.print("next");
         }
     }
     
     public static void printPaginationPage(int page, int current) {
         if (page == current) {
             System.out.print("[" + page + "] ");
         } else {
             System.out.print(page + " ");
         }
     }
}


Sample Inputs and Outputs


generatePaginationNumbers(150, 5, 13);
Output: prev 1 2  ... 10 11 12 [13] 14 15 16  ... 29 30 next

generatePaginationNumbers(150, 5, 28);
Output: prev 1 2  ... 25 26 27 [28] 29 30 next

generatePaginationNumbers(150, 5, 2);
Output: prev 1 [2] 3 4 5  ... 29 30 next

generatePaginationNumbers(150, 5, 1);
Output: [1] 2 3 4  ... 29 30 next

generatePaginationNumbers(150, 5, 30);
Output: prev 1 2  ... 27 28 29 [30]