Showing posts with label jsp servlet. Show all posts
Showing posts with label jsp servlet. Show all posts

Wednesday, 28 August 2013

How to disable back button in Web Browser

 Disable back button in Web Browser

1)Using Filter In Web.xml
<filter>
<filter-name>noCacheFilter</filter-name>
<filter-class>com.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>noCacheFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>

Call The Servlet LoginFilter for every Request 
package com;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sap.mw.jco.JCO.Request;


public class LoginFilter implements Filter{


public void init(FilterConfig config) throws ServletException {
// If you have any <init-param> in web.xml, then you could get them
// here by config.getInitParameter("name") and assign it as field.
}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
System.out.println("filter called");

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0);
chain.doFilter(req, res);
//response.sendRedirect(request.getContextPath() + "/login.jsp"); // No logged-in user found, so redirect to login page.
}

public void destroy() {
// If you have assigned any expensive resources as field of
// this Filter class, then you could clean/close them here.
}

}





Thursday, 16 May 2013

File Handling Using Java

Create Class File.Java
import FILE IO.*;

Example Code for Creating Folder



 // Report is the name of Folder Witch You want to create
    File path = new File("E:\\Report");
   System.out.println("path=="+path);

// Check Folder Is available Or Not  in given Directory

                     File file2 = new File("E:\\Report");
                    if (!file2.exists()) {
                    file2.mkdir();
                    }
//If Exist then Create Directory in file name and copy File into directory


if (file2.exists())
{
      File file1 = new File("E:\\Report\\"+filename+"\\"+filename);
                if (file1.mkdir()) {
                System.out.println("File Name Directory is created!");
                File uploadedFile = new File(file1 + "/" + filename);
                item.write(uploadedFile);
               
                } else {
                System.out.println("Failed to create directory!");
                }
      }





Delete Empty Directory
use This Code
File directory = new File("E:\\Report\\"+filename);
directory.delete();

//If the directory contain File then use this code


File fin = new File("E:\\Filename");
   System.out.println("fin-"+fin);

   for (File file : fin.listFiles()) {
       try {
FileDeleteStrategy.FORCE.delete(file);
System.out.println("delete");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      // Delete when directory is empty
              fin.delete();
   }





Tuesday, 14 May 2013

Upload and Download multiple files at a time using JSP-Servlet

Step 1:
Upload and Download multiple files at a time using JSP-Servlet.

for eg code

function displayTable(data)
{
   $("#Uploadfile table").remove();
if(data!="null"||data!="undefind")
{
    var objArray=JSON.parse(data);
    var count=1;                                      //  UserName,filename,filepath,FileID,Uplodated_Datetime                                                                                                                                          
var glacc="<center><table border='1'><tr align='center'><th></th><th>User Namer</th><th>file Name</th><th>File ID</th><th>Date Of uploading</th></tr>";
$.each(objArray, function(index,jsonObject){

glacc+="<tr align='center'><td id='uploadfile"+count+"' onclick='getid(this.id)'><a href='#'>download</a></td><td id='name"+count+"'>"+jsonObject.UserName+"</td><td id='filename"+count+"'>"+jsonObject.filename+"</td><td id='fileid"+count+"'>"+jsonObject.FileID+"</a></td><td>"+jsonObject.Uplodated_Datetime+"</td></tr>";
count=count+1;
});

 glacc+="</table></center>";
      $("#Uploadfile").append(glacc);
      $("#printPage").show();

}
}


function showfile(hid)
{
var id=hid.substring(4,hid.length);
var act=$("#activity"+id).text();

var complance=$("#complance"+id).text();
complance=complance.substring(0,10);

var name=$("#name"+id).text();

//alert("name="+name+"complance="+complance+"act="+act);
waiting_effect_on();
$.ajax({ type: "Post", url: "show_uploadfile",
data:{flag:1,Username:name,activity:act,c_date:complance},
cache:false,
success : function(data){
waiting_effect_off();
alert(data);
if(data=="]")
{
msg_box('No File Avilable','A',function(result){

});
}
else
{
$("#submitDIV2").show();
displayTable(data);
}

}
});

}











Step 2:

 click on Link to download file
  call this function 


function getid(id)
{

   $.ajax({ type: "Post", url: "downloadfile",
data:{filename:filename},
cache:false,
success : function(data){
window.location.href="tempdownloadfile.jsp?backurl="+window.location.href;

}
});

}


Step 3:
write code on Downloadfile.jsp


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<script type="text/javascript">


function whatFile()
{
alert("1");
var url='file:///' + 'C://Users/1100lt031/Desktop/2012-White-Jaguar-XKR-S-Convertible-3Q-Front-1152x2048.jpg';
alert(url);
window.open(url,'Download');
}

function startDownload()
{
   var url='http://localhost:8080/Project/Report/1368005388533/REC_ADVT_16_2013.pdf';
  /*  var url="file:///E:/Siddharth/Relese Statergy/Multi Level Purchase Order Release Strategy.pdf";
  alert(url); */
  window.open(url,'Download');

}
</script>


</head>
<body>
<input type="button" onclick="startDownload();"/>
<a href="download/VB6IP.zip">Download</a>
<a href="http://localhost:8080/Project/Multi Level Purchase Order Release Strategy.pdf">http://localhost:8080/Project/Multi Level Purchase Order Release Strategy.pdf</a>


</body>
</html>

Step 4:
Output:










Multiple File Uploading Using JSP -Servlet

Step 1:
 Create JSP And Add Controls.

<input type="button" value="Upload file..." onclick="upload();">







Step 2:
 Oen Uploading  JSP file in Window


 window.open("uploadfile.jsp","Test","width=300,height=300,scrollbars=1,resizable=1");












Step 3:

 Control Add on  uploadfile.jsp


Write Code On  uploadfile.jsp.

<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="js/jquery.plupload.queue/css/jquery.plupload.queue.css" type="text/css" media="screen" />
<title>Plupload - Events example</title>
<style type="text/css">
body {
font-family:Verdana, Geneva, sans-serif;
font-size:13px;
color:#333;
background:url(../bg.jpg);
}
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="http://bp.yahooapis.com/2.4.21/browserplus-min.js"></script>

<script type="text/javascript" src="js/plupload.js"></script>
<script type="text/javascript" src="js/plupload.gears.js"></script>
<script type="text/javascript" src="js/plupload.silverlight.js"></script>
<script type="text/javascript" src="js/plupload.flash.js"></script>
<script type="text/javascript" src="js/plupload.browserplus.js"></script>
<script type="text/javascript" src="js/plupload.html4.js"></script>
<script type="text/javascript" src="js/plupload.html5.js"></script>
<script type="text/javascript" src="js/jquery.plupload.queue/jquery.plupload.queue.js"></script>

</head>
<body>
<script type="text/javascript">
$(function() {
function log() {
var str = "";

plupload.each(arguments, function(arg) {
var row = "";

if (typeof(arg) != "string") {
plupload.each(arg, function(value, key) {
// Convert items in File objects to human readable form
if (arg instanceof plupload.File) {
// Convert status to human readable
switch (value) {
case plupload.QUEUED:
value = 'QUEUED';
break;

case plupload.UPLOADING:
value = 'UPLOADING';
break;

case plupload.FAILED:
value = 'FAILED';
break;

case plupload.DONE:
value = 'DONE';
break;
}
}

if (typeof(value) != "function") {
row += (row ? ', ': '') + key + '=' + value;
}
});

str += row + " ";
} else {
str += arg + " ";
}
});

$('#log').val($('#log').val() + str + "\r\n");
}

$("#uploader").pluploadQueue({
// General settings
runtimes: 'html5,gears,browserplus,silverlight,flash,html4',
url: 'uploadfile',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: true,

// Resize images on clientside if we can
resize: {width: 320, height: 240, quality: 90},

// Specify what files to browse for
filters: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"},
{title : "Text files", extensions : "txt"},
{title : "excel files", extensions : "xls"},
{title : "PDF files", extensions : "pdf"}
],

// Flash/Silverlight paths

// PreInit events, bound before any internal events
preinit: {
Init: function(up, info) {
log('[Init]', 'Info:', info, 'Features:', up.features);
},

UploadFile: function(up, file) {
log('[UploadFile]', file);

// You can override settings before the file is uploaded
// up.settings.url = 'upload.php?id=' + file.id;
// up.settings.multipart_params = {param1: 'value1', param2: 'value2'};
}
},

// Post init events, bound after the internal events
init: {
Refresh: function(up) {
// Called when upload shim is moved
log('[Refresh]');
},

StateChanged: function(up) {
// Called when the state of the queue is changed
log('[StateChanged]', up.state == plupload.STARTED ? "STARTED": "STOPPED");
},

QueueChanged: function(up) {
// Called when the files in queue are changed by adding/removing files
log('[QueueChanged]');
},

UploadProgress: function(up, file) {
// Called while a file is being uploaded
log('[UploadProgress]', 'File:', file, "Total:", up.total);
},

FilesAdded: function(up, files) {
// Callced when files are added to queue
log('[FilesAdded]');

plupload.each(files, function(file) {
log('  File:', file);
});
},

FilesRemoved: function(up, files) {
// Called when files where removed from queue
log('[FilesRemoved]');

plupload.each(files, function(file) {
log('  File:', file);
});
},

FileUploaded: function(up, file, info) {
// Called when a file has finished uploading
log('[FileUploaded] File:', file, "Info:", info);
},

ChunkUploaded: function(up, file, info) {
// Called when a file chunk has finished uploading
log('[ChunkUploaded] File:', file, "Info:", info);
},

Error: function(up, args) {
// Called when a error has occured

// Handle file specific error and general error
if (args.file) {
log('[error]', args, "File:", args.file);
} else {
log('[error]', args);
}
}
}
});

$('#log').val('');
$('#clear').click(function(e) {
e.preventDefault();
$("#uploader").pluploadQueue().splice();
});
});
</script>
</body>
</html>


















Step 4:

Write Code On Servlet


 boolean isMultipart = ServletFileUpload.isMultipartContent(request);

   if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List items = upload.parseRequest(request);
            System.out.println("items=="+items);
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                System.out.println("item=="+item);
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    fileName=fileName;
                    fileName=fileName.replaceAll("\\s","");
                    System.out.println("fileName=="+fileName);

                    String root = getServletContext().getRealPath("/");
                    System.out.println("root=="+root);
                 
                    File path = new File(root + "/Report");
                    File path1 = new File("E:\\Report");
                    System.out.println("path=="+path);
                 
                                     
                 
                    File file2 = new File("C:\\Users\\Bharat\\
                                             workspace\\Juno Eclipse\\23.04.2013\\Project
                                              \\WebContent\\Report");
                    if (!file2.exists()) {
                    file2.mkdir();
                    }
                 
                 
                 
                if (file2.exists()) {
                File file1 = new File("C:\\Users\\Bharat\\workspace
                                                          \\Juno Eclipse\\23.04.2013\\Project
                                                             \\WebContent\\Report\\"+millisec);
                if (file1.mkdir()) {
                System.out.println("Directory is created!");
                File uploadedFile = new File(file1 + "/" + fileName);
                item.write(uploadedFile);
               
                } else {
                System.out.println("Failed to create directory!");
                }
                }
                 
                       String fid="http://localhost:8080/Project/Report/"+millisec+"/"+fileName;
                   session.setAttribute("fileName", fileName);
                 
                   session.setAttribute("fileID", fid);
               
                 
                        File uploadedFile = new File(file2 + "/" + fileName);
                   // File uploadedFile = new File(path1 + "/" +"/"+name+"/"
                                    +"/"+currDate+"/"+ fileName);
                    System.out.println(uploadedFile.getAbsolutePath());
                  //  item.write(uploadedFile);
                    System.out.println("sucess fully uploding.....");
                 
             
                   /* if (path.exists()) {
                        boolean status = path.mkdirs();
                    }
                    */
               
                File f=new File("C:\\Users\\Bharat\\workspace
                                           \\Juno Eclipse\\23.04.2013\\Project
                                           \\Report\\"+millisec+"\\"+fileName);
                    String file_path="C:\\Users\\Bharat
                                                       \\workspace\\Juno Eclipse\\23.04.2013\\Project\\Report
                                                      \\"+millisec+"\\"+fileName;
                    file_path=file_path.replace("\\", "/");
                    //File uploadedFile = new File(path2 + "/" + fileName);
                   // System.out.println("uploadedFile=="+uploadedFile);
                  /*  File uploadedFile = new File(path1 + "/" + fileName);
                   // File uploadedFile = new File(path1 + "/" +"/"+name+"/"+"/"+currDate+"/"+ fileName);
                    System.out.println(uploadedFile.getAbsolutePath());
                    item.write(uploadedFile);
                    System.out.println("sucess fully uploding.....");*/
                 
                    try
            {
            con = DBManager.openDBConnection();
            con.setAutoCommit(false);
            st = con.createStatement();
            String query = "insert into uploading_file(File,UserName,filename,filepath,FileID
                                                              ,Uplodated_Datetime,activity,Compliance_date)
                                                             values ('"+f+"','"+name+"','"+fileName+"','"+file_path+"',
                                                          '"+millisec+"','"+currDate+"','"+Activity+"','"+Compliance_date+"')";
            System.out.println("query = "+query);
            int ack = st.executeUpdate(query);
            //System.out.println("ack = "+ack);
            //System.out.println("succuess with first query.");
            }
                    catch(Exception e)
                    {
                    e.printStackTrace();
                    }
                   // out.print("sucess");
                }
             
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }
   else
   {
    System.out.println("UN sucess  uploding.....");
    //out.print("Not Uploading....");
   }


try {
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Step 5:

Click on Upload Button 















check on Folder Upload file

Sunday, 21 April 2013

AutoComplet TextBox (MultiValue)

Step 1:
create JSP Page and add Control on Page












Step 2:
Create a array list and add mail id on array list

for eg

 public static  ArrayList<String> usermail()
                 {
                ArrayList<String> list11=null;
                try {
                   list11 = new ArrayList<String>();
                if(con.isClosed())
{
openConnection();
}
                   String Query="SELECT Email FROM personal_info";
                   statement=con.createStatement();
                   ResultSet rs=statement.executeQuery(Query);
                   System.out.println(Query);
                 while(rs.next())
                 {
                            list11.add(rs.getString("Email"));
                             }
                }catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
                                
             return list11;
                 }


Step 3:
Access array list On JSP Page
import class on JSP page

<%@ page import="java.util.*,util.*,dao.*;" %>
<%
  ArrayList<String> usermail= VisitorOutPassDAO.usermail();
%>

Step 4:
Given code on Java script


<script type="text/javascript">
$(function() {
var availableTags= new Object([]);
<%! int i=0;%>
<%
for(i=0;i<usermail.size();i++)
{
%>
availableTags[<%= i %>]='"<%= usermail.get(i) %>"';
<%}%>
//availableTags = availableTags.substring(0, availableTags.length - 1);
//availableTags+="]";
alert(availableTags);
    function split( val ) {
     return val.split( /,\s*/ );
   
  }
  function extractLast( term ) {
    return split( term ).pop();
  }

  $( "#mailId" )
//don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
//delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
//prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );

//remove the current input
terms.pop();
//add the selected item
terms.push( ui.item.value );

var selected_cust_name=ui.item.value;
var all_selected_cust=$("#mailId").val();
var index=all_selected_cust.indexOf(selected_cust_name);
//add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( "," );
if(index!=-1)
{
all_selected_cust=$("#mailId").val();
var all_len=all_selected_cust.length;
var seleced_len=selected_cust_name.length;
seleced_len++;
var last_index=all_len-seleced_len;
if(last_index!=0)
{
var final_value=all_selected_cust.substring(0,last_index);
$("#mailId").val(final_value);
}
alert("Already selected.");
}
return false;
}
});
});
}
</script>

Out Put








Thursday, 18 April 2013

Sending Email Using JSP Servlet

Step 1: 
Create JSP file 
















Step 2:
Write a Script Code To call Servlet.


function sendmail()
{
waiting_effect_on();
alert("send mail");
$.ajax({ type: "Post", url: "send_message",
data:{mailId:$("#mailId").val(),subject:$("#subject").val(),message:$("#message").val()},
cache:false,
success : function(data){
waiting_effect_off();
alert(data);

}
});
}



Step 3:
Write given code to Servlet.


               Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("XXXXX@gmail.com", "*****");
}
});
Message simpleMessage = new MimeMessage(mailSession);


       InternetAddress fromAddress = null;
       InternetAddress toAddress = null;
       try {
           fromAddress = new InternetAddress(Email);
           toAddress = new InternetAddress(mailId);
       } catch (AddressException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

       try {
           simpleMessage.setFrom(fromAddress);
           simpleMessage.setRecipient(RecipientType.TO, toAddress);
           simpleMessage.setSubject(subject);
           simpleMessage.setText(message1);

           Transport.send(simpleMessage);
       } catch (MessagingException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }



Step 4:
Run JSP File and insert input fields















Step 4:
Check Mail To your Account









You Want to attach file into mail then replace code to this code

         
               /* String host = "smtp.gmail.com";//host name
   String from = "xxxx@gmail.com";//sender id
   String to = "xxxxx@gmail.com";//reciever id
   String pass = "*******";//sender's password
   String fileAttachment = "E:\\Exaple.txt";//file name for attachment
   //system properties
   Properties prop = System.getProperties();
   // Setup mail server properties
   prop.put("mail.smtp.gmail", host);
   prop.put("mail.smtp.starttls.enable", "true");
   prop.put("mail.smtp.host", host);
   prop.put("mail.smtp.user", from);
   prop.put("mail.smtp.password", pass);
   prop.put("mail.smtp.port", "465");
   prop.put("mail.smtp.auth", "true");
   //session
   Session session = Session.getInstance(prop, null);
   // Define message
   MimeMessage message = new MimeMessage(session);
   message.setFrom(new InternetAddress(from));
   message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
   message.setSubject("subject");
   // create the message part
   MimeBodyPart messageBodyPart = new MimeBodyPart();
   //message body
   messageBodyPart.setText("Hi");
   Multipart multipart = new MimeMultipart();
   multipart.addBodyPart(messageBodyPart);
   //attachment
   messageBodyPart = new MimeBodyPart();
   DataSource source = new FileDataSource(fileAttachment);
   messageBodyPart.setDataHandler(new DataHandler(source));
   messageBodyPart.setFileName(fileAttachment);
   multipart.addBodyPart(messageBodyPart);
   message.setContent(multipart);
   //send message to reciever
   Transport transport = session.getTransport("smtp");
   transport.connect(host, from, pass);
   transport.sendMessage(message, message.getAllRecipients());
   transport.close();*/



Friday, 5 April 2013

Add Event in Calender using JSP Page

Step 1:
          create jsp and

         <div id='calendar'></div>

Step 2:
    add js file into the JSP 
     for eg:


<link rel='stylesheet' type='text/css' href='fullcalendar/fullcalendar.css' />
<link rel='stylesheet' type='text/css' href='fullcalendar/fullcalendar.print.css' media='print' />
<script type='text/javascript' src='extensions/jquery-1.3.2.min.js'></script>

Step 3:
  Add .css in JSP



<style type='text/css'>

body {
margin-top: 40px;
text-align: center;
font-size: 14px;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
}

#loading {
position: absolute;
top: 5px;
right: 5px;
}

#calendar {
width: 900px;
margin: 0 auto;
}

</style>


Step 4:
   write code on script



<script type='text/javascript'>

$(document).ready(function() {


var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {

calendar.fullCalendar('unselect');
},
editable: true,


});


Step 5:

     Create servlet to getting event on table 
    or u direct Post the event on calender
    i am useint table for event

      write code on AJAX

$.ajax({ type: "Post", url: "Calender_Event",
data:{name:$("#Uname").val()},
cache:false,
success : function(data){

var objArray=JSON.parse(data);
 $.each(objArray, function(index,jsonObject){

   var subject = jsonObject.Description;  //the title of the event        
var dateStart = jsonObject.complDate;     // the day the event takes place
var events=new Array();  
event = new Object();    
event.title = subject;
event.start = dateStart;    // its a date string
//event.end = dateEnd;        // its a date string.
event.color = jsonObject.color;
event.allDay = false;
       event.url="Calender_Add_Report.jsp";
events.push(event);
$('#calendar').fullCalendar('addEventSource',events);

 });

  var altField = $( ".selector" ).datepicker( "option", "altField" );
 alert(altField);
}
});


Step 6:
Out Put  












Create dynamic jsp file and print this file


Step 1:
Simple Html File
add Button On Html File


 <input type="button"  onclick="a();" value="Demo Example ">






Step 2:
write code on script in  function a()

<script type="text/javascript">
    function a()
    {  
    var disp_setting="toolbar=no,location=no,directories=no,menubar=n0,";
    disp_setting+="scrollbars=yes,width=700, height=330,left=300,top=325";
    var rate_print=window.open("","",disp_setting);
    rate_print.document.open();
    rate_print.document.writeln('<html><head><title>Sample DEMO     </title>');
    rate_print.document.writeln('</head><body bgcolor="#b8f8f7"><center>');
    rate_print.document.writeln("<table align='center' cellspacing='0'
       border='1'     bordercolor='#000000'
       style='border-collapse:collapse' width='100%' id='viewparticipant'>");
    rate_print.document.writeln("<tr>");
    rate_print.document.writeln("<th class='tstyle' style='page-break-after:always'>S.NO</th>");
    rate_print.document.writeln("<th class='tstyle' style='page-break-after:always'>Vendor Name</th>");
    rate_print.document.writeln("<th class='tstyle' style='page-break-after:always'>Address</th>");
    rate_print.document.writeln("<th class='tstyle' style='page-break-after:always'>Quantity</th>");
    rate_print.document.writeln("<th class='tstyle' style='page-break-after:always'>Size</th>");
    rate_print.document.writeln("<th class='tstyle' style='page-break-after:always'>Rate</th>");
    rate_print.document.writeln("<th class='tstyle' style='page-break-after:always'>Date</th>");
    rate_print.document.writeln("</tr>");
    for(var i=0,j=1;i<100;i=i+1,j++)
    {
    rate_print.document.writeln("<tr>");
    rate_print.document.writeln("<td valign='center' align='center'> "+j+"</td>");
    rate_print.document.writeln("<td valign='center' align='left'>"+"Bharat"+" </td>");
    rate_print.document.writeln("<td valign='center' align='left'>"+"Shirur"+" </td>");
    rate_print.document.writeln("<td valign='center' align='right'>"+"24"+" </td>");
    rate_print.document.writeln("<td valign='center' align='right'>"+"22"+" </td>");
    rate_print.document.writeln("<td valign='center' align='right'>"+"32423423"+" </td>");
    rate_print.document.writeln("<td valign='center' align='center'>"+"19/10/1987"+" </td>");
    rate_print.document.writeln("</tr>");
    }/**end of the for loop*/
      rate_print.document.writeln("</table>");
    rate_print.document.writeln("<br>");
    rate_print.document.writeln("<input id='ok' type='button' value='Ok'
        class='blackbuttonlow'     tabindex='1' onclick='window.close()'> ");
    rate_print.document.writeln("&nbsp&nbsp&nbsp");
    rate_print.document.writeln("<input type='button'
        value='Print' tabindex='1'   onClick='this.style.visibility=\"hidden\"; window.print();'/>");
    rate_print.document.writeln('</center></body></html>');
    rate_print.document.close();
    rate_print.focus()
    }
 
    </script>

Step 3
Run Program (click on Button)



click on Print Button