Saturday, November 23, 2013

Simple Captcha using java script

Here you get simple way to apply captcha for your site using java script.

Steps to drive captcha on html page:

1)Assign canvas tag and image tag  on html page with width and height  whatever size you want,
2)Generate Random String of Alpha-numeric character.
3)Convert that random string to canvas->Image and print it on page.

For reCaptcha 

1)just clear the previous canvas and refill it with random string.


 Step 1: //here is html code :


  <div>
  <canvas id='textCanvas' width=100 height=40></canvas>
  <img id='image'>
  <br>
<img id="refresh_captcha" src="/oltapp/ButtonImages/Refresh.png" onClick="randomString();"/>
  </div>

Step 2: //java script


  <script type="text/javascript">
    
     // captcha when document get reload
 
         $(document).ready(function(){
         $("#refresh_captcha").click();
     
         });


      function randomString() {
   
           // Genrate random string
     
           var randomstring = '';

            var chars = "0123456789ABCDEFGHIJKL!@#$%^&*()MNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";

        var string_length = 5;  //Length of Captcha

        for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum,rnum+1);
        }

        // Getting canvas variable
        var tCtx = document.getElementById('textCanvas').getContext('2d'),
        imageElem = document.getElementById('image');



        tCtx.font= "normal 24px Verdana";  //set text fonts option for  canvas,html5
canvas: Text Option

        tCtx.strokeStyle = "#000000";    //
html5 canvas: Text Option
        
        tCtx.clearRect(0,0,100,40);        //Clear previous Canvas for redraw our captcha

        tCtx.strokeText(randomstring,30,20,70);  //Stroke random string to canvas
 
        tCtx.textBaseline = "middle";                  //html5 canvas: Text Option,line in middle of text

        imageElem.src = tCtx.canvas.toDataURL(); // provide canvas url to image src
 
        console.log(imageElem.src);  //image

    }
</script>

now we having captcha when document get ready and when click on refresh button,From HTML5 Canvas option you can set background image or another text style in captcha and having different options to make your captcha attractive.

example captcha:



For more HTML5 Canvas:Text Option - http://createdynamicgraph.blogspot.in/
 

HTML5 Canvas: Text Options

It is possible to draw text on an HTML5 canvas, using various fonts, sizes and colors. 

The look of the text is controlled by these 2D Context font property. In addition you will need to set either the fillStyle or strokeStyle 2D Context property, depending on whether you want to draw filled or stroked text.

To draw the text you use either the fillText() or strokeText() function. The fillText()
Here is a simple code example: 

var canvas  = document.getElementById("ex1");
var context = canvas.getContext("2d");

context.font      = "normal 36px Verdana";
context.fillStyle = "#000000";
context.fillText("HTML5 Canvas Text", 50, 50);

context.font        = "normal 36px Arial";
context.strokeStyle = "#000000";
context.strokeText("HTML5 Canvas Text", 50, 90);
 

    Here is the result when drawn on a canvas:
 
 
 

 

 Fonts and Styles

When drawing text on an HTML5 canvas you have to set what font to use. This is done by setting the value of the 2D Context font property. This property is a string with CSS compliant values, of the format:
[font style][font weight][font size][font face]
For instance:
context.font = "normal normal 20px Verdana";
 
Here are the values you can set for each part of the font string: 

font style normal
italic
oblique
inherit
font weightnormal
bold
bolder
lighter
auto
inherit
100
200
300
400
500
600
700
800
900
font size A size in pixels e.g 12px, 20px etc.
font face A font face (family), e.g. verdana, arial, serif, sans-serif, cursive, fantasy, monospace etc.
Note that not all values may be supported by each browser. You will have to test the values you plan to use before relying on them.
Here is another example: 

"italic bold 36px Arial"

Drawing Text

When drawing text on an HTML5 canvas you can draw either filled or outlined text, as shown earlier. You do so using the 2D Context functions fillText() and strokeText(). These functions are defined like this:

 
fillText   (textString, x, y [,maxWidth]);
strokeText (textString, x, y [,maxWidth]);

The textString parameter is the text to draw.
The x and y represents the location where the text is be drawn. The x parameter is where the text starts. The y parameter is where the text is located vertically, but exactly how it is represented depends on the text baseline. The text baseline is covered in a later section.
The maxWidth text is covered in the section below.
Here is a code example:
 
context.font      = "36px Verdana";
context.fillStyle = "#000000";
context.fillText("HTML5 Canvas Text", 50, 50);

Text Max Width

The optional maxWidth parameter tells the canvas that the text cannot take up more space horizontally than the given parameter value. If the text is too wide to fit into the maxWidth, the text is compressed in the width. It is not cut off. Here is a code example that draws the same text with and without maxWidth:

context.font      = "36px Verdana";
context.fillStyle = "#000000";
context.fillText("HTML5 Canvas Text", 50, 50);
context.fillText("HTML5 Canvas Text", 50, 100, 200);
 
Here is what the two texts look like, when drawn on an HTML5 canvas:
As you can see, the second text is compressed in its width to fit the maxWidth of 200 pixels.

Text Color

The color of either filled or stroked text is set using the fillStyle and strokeStyle properties of the 2D Context, like with any other shape. I will not get into more detail with those properties here.

Measuring Text Width

The 2D Context object has a function that can measure the width in pixels of a text. It cannot measure the height. The function is called measureText(). Here is a code example:

var textMetrics = context.measureText("measure this");

var width = textMetrics.width; 
 
Measuring the width of a text can be used to calculate if a text string fits into a certain space etc.

Text Baseline

The text baseline determines how the y parameter of the fillText() and strokeText() is interpreted. In other words, where the text is positioned vertically, and how this position is interpreted. Notice, that there might be minor differences in how the browsers interpret this property too.
The text baseline is set using the textBaseline property of the 2D Context. Here are the values it can take, and what they mean:
top The text is aligned based on the top of the tallest glyph in the text.
hanging The text is aligned based on the line the text seems to hang from. This is almost identical to top, and in many cases you cannot see the difference.
middle The text is aligned according to the middle of the text.
alphabetic The bottom of vertically oriented glyphs, e.g. western alphabets like the latin
ideographic The bottom of horizontally oriented glyphs.
bottom The text is aligned based on bottom of the glyph in the text, that extends lowest down in the text.
Here is an example that draws text using the same y value (75) for all texts, but uses a different baseline for each text drawn. A line is drawn a y=75 to show you how the text is baselined around that y value.



For the curious, here is the code that generates the above graphics:

context.stokeStyle = "#000000";
context.lineWidth  = 1;
context.beginPath();
context.moveTo(  0, 75);
context.lineTo(500, 75);
context.stroke();
context.closePath();

context.font      = "16px Verdana";
context.fillStyle = "#000000";

context.textBaseline = "top";
context.fillText("top", 0, 75);

context.textBaseline = "hanging";
context.fillText("hanging", 40, 75);

context.textBaseline = "middle";
context.fillText("middle", 120, 75);

context.textBaseline = "alphabetic";
context.fillText("alphabetic", 200, 75);

context.textBaseline = "ideographic";
context.fillText("ideographic", 300, 75);

context.textBaseline = "bottom";
context.fillText("bottom-glyph", 400, 75);
 

Convert Text to Image using java script on html page

Here you find out way to show your text into image on html page just in few lines  of  js code.

//here is your html body ,where your text image genrate

   <div>
          <canvas id='textCanvas' width=100 height=40></canvas>
          <img id='image'>
           <br>
           <input type="button" onClick="textToImage();" >
   </div>


// here is your java script function which generate text into image

<script>

function textToImage()
{

var textCanvas= document.getElementById('textCanvas').getContext('2d'),  //Assign canvas variable,

imageElem = document.getElementById('image');                    //Image variable,

textCanvas.font= "normal 24px Verdana";                         //HTML5 Canvas:Text option for text field

textCanvas.strokeStyle = "#000000";

textCanvas.clearRect(0,0,100,40);               //clear previous canvas for redrawing image    

textCanvas.strokeText('input text',30,20,70);   //fill text into canvas

imageElem.src = textCanvas.canvas.toDataURL();  //providing canvas url to image src

console.log(imageElem.src);

}
</script>

now you have image of text that you have entered in strokeText(); 

///HTML5 Canvas:Text option for text field

[font style][font weight][font size][font face]
 
example: 
context.font = "normal normal 20px Verdana"; 


we have lot of option in HTML5 Canvas .which help to draw different structure.
you can see different option for HTML5 Canvas :Text  in next blog.
 

Genrate Random Key/Alpha-Numeric String using java Script

In this blog I am going to show you how to generate Random String/key of alpha-numeric values using java script, which may help us in many way like generate random key, any strong random password e.t.c 

Here is function which generate random string.

var string=' ';

 function randomString(){
    
var random_string=' ';  // Empty Random String
      
 var chars = "0123456789ABCDEFGHIJKL!@#$%^&* ()MNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";  // Characters from where random string generate

var string_length = 5;  //Length of random string

for (var i=0; i<string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            random_string += chars.substring(rnum,rnum+1);  //generate random string
        }

string=random_string;  //here is your generated random string
alert(random_string);
}

enjoy with your random key. :)


Wednesday, October 30, 2013

How to Download charts to PDF formate


It gives many problem to export any html or div to pdf  when it content charts because many  pdf converter library do not support chart container and not able to convert that chart or html div to pdf.

        Here I am going to sort out these problem.
These blog show you how to download Charts like google charts and others, to pdf formate at client side.

Here we use three script or technique:

1. First of all we draw charts at html div as we done in previous blog.
2. Then we convert that chart to Image(canvas) using google api (canvg.js) .
3. Convert whole html page to canvas using html2canvas library.
4.download that canvas (as image) to pdf formate using jspdf librar.

//Import html2canvas and jspdf library to you local folder.

//<Script That help to achieve our goal>

1. //script of charts that you use as google api that we use in previous blog.

//convert chart to Image(canvas) used to invoke canvg(); method

<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>

//convert html page to canvas using html2canvas library

<script type="text/javascript" src="../js/html2canvas.js"></script>

//Now export canvas to pdf using jspdf library.

<script type="text/javascript" src="/oltapp/js/FileSaver.js"></script>
<script type="text/javascript" src="/oltapp/js/jspdf.js"></script>
<script type="text/javascript" src="/oltapp/js/jspdf.plugin.addimage.js"></script>

Note: we do not need to import all js of jspdf .

lets take an example to fully understand.

Example code:
 <html>
<head>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script type="text/javascript" src="../js/html2canvas.js"></script>
<script type="text/javascript" src="../js/FileSaver.js"></script>
<script type="text/javascript" src="../js/jspdf.js"></script>
<script type="text/javascript" src="../js/jspdf.plugin.addimage.js"></script> 



<script type="text/javascript">

function export_PDF(chartContainer, imgContainer) {

         //main Div Hide
              var el = document.getElementById( 'chart_Container' );
             el.parentNode.removeChild( el );  

        //Chart to Image

          var doc = chartContainer.ownerDocument;
          var img = doc.createElement('img');
          img.src = getImgData(chartContainer);

          while (imgContainer.firstChild) {
               imgContainer.removeChild(imgContainer.firstChild);
           }

             imgContainer.appendChild(img);

      //Pdf Creation

                   var divElements = document.getElementById('expotPdfDiv).innerHTML;
                                         //Get the HTML of whole page
                                         var oldPage = document.body.innerHTML;

                                         //Reset the page's HTML with div's HTML only
                                         document.body.innerHTML =
                                           "<html><head><title></title></head><body>" +
                                           divElements + "</body>";

//convert whole html page to canvas
 
                             html2canvas(document.body, {
                                     onrendered: function(canvas) {
                                       
  // canvas is the final rendered <canvas> element
                                        
 var myImage = canvas.toDataURL("image/JPEG").slice('data:image/jpeg;base64,'.length);
                                        
 // Convert the data to binary form
                                         myImage = atob(myImage)

//new object of jspdf and save image to pdf.

                                         var doc = new jsPDF();
                                         doc.addImage(myImage, 'JPEG', 0, 0, 200,200);
                                          doc.save('pdfName.pdf');
                                      

                                     }
                                 });


}

function getImgData(chartContainer)
  {


     var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
     var svg = chartArea.innerHTML;
     var doc = chartContainer.ownerDocument;
     var canvas = doc.createElement('canvas');
     canvas.setAttribute('width', chartArea.offsetWidth);
     canvas.setAttribute('height', chartArea.offsetHeight);


     canvas.setAttribute(
         'style',
         'position: absolute; ' +
         'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
         'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
     doc.body.appendChild(canvas);
     canvg(canvas, svg);

     var imgData = canvas.toDataURL("image/JPEG");
    var data = canvas.toDataURL('image/JPEG').slice('data:image/JPEG;base64,'.length);
             
// Convert the data to binary form
             data = atob(data)


     canvas.parentNode.removeChild(canvas);



     return imgData;
  }

</script>

</head>

<body>
 <div id="expotPdfDiv">
<div id="chart_Container" >
----
---        //Here is script for making chart at chart_Container div.
---

</div>

 <div id="chart_image"></div>  //div where chart image genrate

 <button  Onclick=" export_PDF(document.getElementById('chart_Container'), document.getElementById('chart_image')); " > Download PDF</button>

</div>

</body>

</html>



Monday, October 28, 2013

How to make dynameic graph for website (Using Google API)

There are many open source charts library from which you can easily make dynamic charts for your website .I think it is the easiest way to make dynamic charts through Google API for any beginner .

 These tutorial show you how to make Google API Chart.

Step 1:

 <!--Load the AJAX API-->

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">


Step 2:

 // Load the Visualization API , Here we Load API for PIE Chart
 
 google.load('visualization', '1.0', {'packages':['corechart']});
 
 

Step 3:

 // Set a callback to run when the Google Visualization API is loaded ,
//In Simple manner Call the method which invoke google chart.
 
code:
 
google.setOnLoadCallback(drawChart); 


Step 4:

// Callback that creates and populates a data table, 
// instantiates the pie chart, passes in the data and
// draws it.

function drawChart() {
// Create the data table.
 
 var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Work',     11],
          ['Eat',      2],
          ['Commute',  2],
          ['Watch TV', 2],
          ['Sleep',    7]
        ]);
 
 
// Set chart options

var options = {'title':'My Daily Activities' ,
                     'width':400,
                     'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }

</script> //here script is over.



Step 5:

<!--Div that will hold the pie chart-->
 
 <div id="chart_div" style="width:400; height:300"></div>
 

Now you have pie chart on your "chart_div" with static data of  "data" variable just change the data variable according to you dynamic data and you get real pie chart. you can also change charts option according to you .

Creating PDF in spring MVC

Maven Dependency :

Add following dependency in your pom.xml 
        
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.3.4</version>
        </dependency>


Controller code :

    @RequestMapping(value = "/generatePDF/{empId}",method = RequestMethod.GET)
    private void downloadPDF(@PathVariable Integer empId,
                                    HttpServletResponse response,
                                    HttpServletRequest request, ModelMap model) 
                                    throws IOException {
        
        List<TaskEntry> taskEntryList =  taskEntryService.retrieveAllTask(empId);\
       //here TaskEntry is your Domain of respective class
       //here taskEntryService is your service layer from which you are accessing Data.
       String orignalFileName="sample.pdf";

        try {
            Document document = new Document();
            response.setHeader("Content-Disposition", "outline;filename=\"" +orignalFileName+ "\"");
            PdfWriter.getInstance(document, response.getOutputStream());

            document.open();
            document.add(createFirstTable(taskEntryList ));
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






public PdfPTable createFirstTable(List<TaskEntry> taskEntryList ) throws ParseException {
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        String fromDate=sdf.format(pdfForm.getFromDate());
        String toDate=sdf.format(pdfForm.getToDate());
        // a table with three columns
        PdfPTable table = new PdfPTable(2);
        // the cell object
        PdfPCell cell;
        // we add a cell with colspan 3
        cell = new PdfPCell(new Phrase("TASK DETAILS"));
        cell.setColspan(2);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("From"+fromDate+"TO"+toDate));
        cell.setColspan(2);
        table.addCell(cell);
        table.addCell("DATE:");
        table.addCell("TASK:");
        for(TaskEntry taskEntry: taskEntryList)  
       {
           table.addCell(taskEntry.task);
        }
        return table;
    }

For any query Do comment