Monday, 20 January 2014

Spring MVC+ Ajax + Itext PDF

Spring MVC+ Ajax + Itext PDF
 
Hello Friends.hope you all are doing well.today i am going to demonstrate you how to display pdf using spring mvc and itext library.well i am taking my traditional Student class to demonstrate the concept.i am making ajax call to the controller from where view will be returned &  pdf will be displayed on browser.

you need to have itext library along with spring jars into your classpath.

Model Class:-  Student.java
package org.demo.model;

public class Student
{
private String id;

private String name;
private String college;

public Student() {}
public Student(String id,String name,String college)
{
    this.id=id;
    this.name=name;
    this.college=college;
   
}

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}




public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getCollege() {
    return college;
}

public void setCollege(String college) {
    this.college = college;
}
 
}

Controller :StudentController.java

package org.demo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController
{

        @RequestMapping(value="/test",method=RequestMethod.POST)
        public ModelAndView processAjax(HttpServletRequest request,HttpServletResponse response)
        {
           
           
           
            String id=request.getParameter("id");
            String username=request.getParameter("name");
            String college=request.getParameter("college");
           
            System.out.println("ID:"+id);
           
            Student s=new Student(id,username,college);
            List<Student> studList =new ArrayList<Student>();
           
            studList.add(s);
           
           
            return new ModelAndView("PdfView","listStudent",studList);
           
        }
}

User Defined View Resolver class: PdfViewHandler.java


package org.demo.view;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.demo.model.Student;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;

public class PdfViewHandler extends AbstractPdfView
{

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document,
            PdfWriter arg2, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        List<Student> listStudent=(List<Student>)model.get("listStudent");
       
        //adding Response header inorder to change default name of .pdf file
        response.addHeader("content-disposition","inline;filename=StudentReport.pdf");
       
       
        Table table=new Table(3);
        table.addCell("Id");       
        table.addCell("Name");
        table.addCell("College");
       
        for(Student  s: listStudent)
        {
            table.addCell(s.getId()+"");
            table.addCell(s.getName());
            table.addCell(s.getCollege());
        }
       
        document.add(table);
       
    }

}
index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<title>Sample pdf code</title>

 <script type="text/javascript">

$(document).ready(function(){
   
    $('#btn1').click(function() {
       
        $.ajax({
            url: "${pageContext.request.contextPath}/test.html",
            dataType:'json',
            method:'post',
            data:{id:$('#txtid').val(),name:$('#txtname').val(),college:$('#txtcollege').val()}
            });
       
    });
   
});




</script>


</head>
<body>
<form id="f1" method="post">
<table>
    <tr>
        <td>ID:<input type="text" id="txtid" name="txtid"> </td>
    </tr>
    <tr>
        <td>Name:<input type="text" id="txtname" name="txtname"> </td>
    </tr>
    <tr>
        <td>College:<input type="text"  id="txtcollege" name="txtcollege"></td>
    </tr>
     <tr>
        <td><input type="button"  id="btn1" value="submit"> </td>
    </tr>
   
</table>
</form>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringwithPdf</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
 <servlet>
     <servlet-name>dispatcherservlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>

 <servlet-mapping>
    
     <servlet-name>dispatcherservlet</servlet-name>
     <url-pattern>*.html</url-pattern>
 </servlet-mapping>
</web-app>

view.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
   
    <bean id="PdfView" class="org.demo.view.PdfViewHandler"></bean>
   
    </beans>
dispatcherservlet-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
   
   <context:annotation-config></context:annotation-config>
  
  
   <context:component-scan base-package="org.demo.controller"></context:component-scan>
  
   <bean class="org.springframework.web.servlet.view.XmlViewResolver">
       <property name="order" value="1"></property>
       <property name="location">
          <value>/WEB-INF/view.xml</value>
       </property>
    </bean>  
  
   </beans>

the output will look like given below:
1) Ajax Call 



2)dowload dialog box opened & ask to download pdf ,pdf gets opened


i hope you will get my point.
for any query related to post ping me on pathak.nisarg@yahoo.com
Thanks
Regards


3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Inconsistency in output quality: If the provider {you have chosen|you've chosen|you've selected|you have selected} is inexperienced and lacks consistency, {then it|it|this|that} {might lead to|could trigger|might trigger|may cause} problems {such as|for example|including|like} delayed submission of completed projects, processed files without accuracy and quality, inappropriate assignment of responsibilities, {lack of communication|no communication|poor communication} {and so|and thus|therefore|so} on| While the job profile {might seem|may appear|may seem|might appear} simple {it does|it will|it can|it lets you do} {in fact|actually|in reality|the truth is} {require a|need a|demand a|have to have a} certain {degree of|amount of|level of|a higher level} exactness {and an|as well as an|plus an|with an} eye for detail| My writing {is focused|is concentrated|is targeted|concentrates} {more on|more about|read more about|on} {the industry|the|a|that is a} {and quality of|and excellence of|superiority} work, not the worker| By continues monitoring the hurdles and solving it, {one can|it's possible to|you can|one can possibly} easily {increase the|boost the|raise the|improve the} productivity of business| Decline {in the|within the|inside the|inside} quality of service and delay {in the|within the|inside the|inside} execution and delivery of processes are some {of the|from the|with the|in the} risks involved, {besides the|aside from the|in addition to the|apart from the} risk {to the|towards the|for the|on the} security {of the|from the|with the|in the} data and privacy and cost-related risks| The {service provider|company|supplier|vendor} {should also|also needs to|must also|also need to} volunteer {a variety of|a number of|many different|various} profits concerning formulas {of data|of information|of knowledge|of internet data} transmission, turnaround etc}. { A lot of companies are fine with admitting this, but {others are|other medication is|other people are} {not so|not too|not|less than} sure, primarily {because this|as this|since this|simply because this} may put people {off the|from the|off of the|over} service| Such measures would {keep your|keep the|maintain your|maintain} sensitive documents from falling {into the|in to the|to the|in the} hands of unauthorized personnel| When you outsource {to an|for an|to a|with an} experienced BPO company, {they would|they'd|they might|they will} manage these risks professionally {as well as|in addition to|along with|and also} plan and implement appropriate {strategies to|ways of|ways to|methods to} avoid them in future| Outsourcing data entry is most helpful term {for all|for those|for many|for all those} these organizations| With the help of such information, {you can|you are able to|it is possible to|you'll be able to} {improve on|enhance|make improvements to} customer targeting| If you think {you are|you're|you might be|you happen to be} proficient enough in installing the payment processor {on your|in your|on your own|on the} website {on your|in your|on your own|on the} own, {you should not|you shouldn't|you ought not|it's not necassary to} hesitate doing it}.pdf data entry services

    ReplyDelete
  3. You well said!Thanks for giving such useful information. I don't know what others have to say about it, but I am 100% in agreement with you. After reading your content, I must say, you do have a lot of practical experience. I want to know more about it and get answers to my few questions about the same you discussed. My name is Shreya, and I work as a content writer at an SEO company in Dwarka. I would like to reach out to you. Please reply to this message to provide your email id.

    ReplyDelete

Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...