Spring MVC and PDF file via AbstractPdfView

Spring MVC comes with AbstractPdfView class to export data to pdf file via Bruno Lowagie’s iText library. In this tutorial, it show the use of AbstractPdfView class in Spring MVC application to export data to pdf file for download.

1. iText

Get the iText library to generate the pdf file.

    <!-- Pdf library --> 
    <dependency>
	<groupId>com.lowagie</groupId>
	<artifactId>itext</artifactId>
	<version>2.1.7</version>
    </dependency>

2. Controller

A controller class, generate dummy data for demonstration, and get the request parameter to determine which view to return. If the request parameter is equal to “PDF“, then return an Pdf view (AbstractPdfView).

File : RevenueReportController.java

package com.mkyong.common.controller;
 
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
 
public class RevenueReportController extends AbstractController{
 
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
 
		String output =
			ServletRequestUtils.getStringParameter(request, "output");
 
		//dummy data
		Map<String,String> revenueData = new HashMap<String,String>();
		revenueData.put("1/20/2010", "$100,000");
		revenueData.put("1/21/2010", "$200,000");
		revenueData.put("1/22/2010", "$300,000");
		revenueData.put("1/23/2010", "$400,000");
		revenueData.put("1/24/2010", "$500,000");
 
		if(output ==null || "".equals(output)){
		    //return normal view
		    return new ModelAndView("RevenueSummary","revenueData",revenueData);
 
		}else if("PDF".equals(output.toUpperCase())){
		    //return excel view
		    return new ModelAndView("PdfRevenueSummary","revenueData",revenueData);
 
		}else{
		    //return normal view
		    return new ModelAndView("RevenueSummary","revenueData",revenueData);
 
		}	
	}	
}

3. PdfRevenueReportView

Create a pdf view by extends the AbstractPdfView class, override the buildExcelDocument() method to populate the data to pdf file. The AbstractPdfView is using the iText API to generate the pdf file.

File : PdfRevenueReportView.java

package com.mkyong.common.view;
 
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;
 
public class PdfRevenueReportView extends AbstractPdfView{
 
	@Override
	protected void buildPdfDocument(Map model, Document document,
		PdfWriter writer, HttpServletRequest request,
		HttpServletResponse response) throws Exception {
 
		Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");
 
		Table table = new Table(2);
		table.addCell("Month");
		table.addCell("Revenue");
 
		for (Map.Entry<String, String> entry : revenueData.entrySet()) {
			table.addCell(entry.getKey());
			table.addCell(entry.getValue());
                }
 
		document.add(table);
	}
}

4. Spring Configuration

Create a XmlViewResolver for the Pdf view.

<beans ...>
 
 <bean 
  class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
 
    <bean class="com.mkyong.common.controller.RevenueReportController" />
 
    <bean class="org.springframework.web.servlet.view.XmlViewResolver">
       <property name="location">
          <value>/WEB-INF/spring-pdf-views.xml</value>
       </property>
    </bean>
 
</beans>

File : spring-pdf-views.xml

<beans ...">
 
   <bean id="PdfRevenueSummary"
   	class="com.mkyong.common.view.PdfRevenueReportView">
   </bean>
 
</beans>

5. Demo

URL : http://localhost:8080/SpringMVC/revenuereport.htm?output=pdf

It generates a pdf file for user to download.

SpringMVC-PDF-Example

Download Source Code

Download it – SpringMVC-PDF-Example.zip (9KB)

References

  1. iText website
  2. iText Wiki
  3. AbstractPdfView Javadoc
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: over here()

  • Pingback: water ionizer()

  • Pingback: alkaline water()

  • Pingback: water ionizer payment plan()

  • Pingback: water ionizer()

  • Pingback: plan()

  • Pingback: water ionizer()

  • Pingback: house blue()

  • Pingback: ben 10 plumbers helpers()

  • Pingback: see this here()

  • Pingback: m & w locksmith wilson nc()

  • Pingback: read more here()

  • Pingback: electrician tool bags leather()

  • Pingback: pay per day loan plans()

  • Pingback: car parking()

  • Pingback: paypal loans()

  • Pingback: Blue Coaster33()

  • subrat kumar nayak

    how can i get the data from the database,
    because retrieving data from buildpdfDocument function requires session to be there. but since there is no session in the buildpdfDocument function, so how can i make a database request from the buildpdfDocument.

  • phani

    Hi,

    I have few doubts,

    1. I am sending request from UI to get report data in ajax call.
    2. If data is there i ll generate pdf and i ll send back, if data is not there i have to send some string or json response how to handle this.
    3. How to handle multiple resolvers based on respose.

    Please reply me asap.

    Thank you

  • Julian
  • Shikher

    Hi,
    This post is very helpful.
    The only issue I got was generating PDF. It was always rendering through jsp.
    Finally I solved it – the internal view resolver should always be the last resolver if you have more than one and you can do it by setting the Order attribute.

    Thanks

  • surya

    I’m getting the error below :

    Resource interpreted as Document but transferred with MIME type application/pdf:

    Where do I need to set the mime type – in the controller ? in the view? in the .xml file ?

    Thanks for your help.

  • sujata

    I downloaded library from itextpdf.com Bt now im getting error that
    Table table = new Table(2); cannot be instantiated. It cannot be resolved to a type.

    Can u plz tell me wt type is this Table?

    • test

      I dont know how to do it

  • ANSON VATTOLY

    Hi Mkyong,
    When I import this project lot of errors is encountered…when i run that project i get 404 error….I think it is because of the absence of library files…..pls give valuable solution for this issue….

  • Rajagopal

    Hello,

    I want to implement the pdf and excel along with spring portlet, Could you, tell me how this can be done ? Can we use spring mvc along with spring portlet mvc ? what are all the steps needed to configure it ? how can we call the pdf controller from spring portlet page ?

  • Tapas

    Dear how it will work with spring annotation…Please demonstrate :)

    • Tapas

      Dear Issue ,I have tried with annotation it is working fine :) just want to know how it can be open in a popup windows ….

  • Sam

    You code is really helpfull, but i didn’t find any thing related to PdfWriter writer, revenuereport.htm.. I am so confused how you are getting that PDF page ??

  • Sudheendra

    Have you got this working with Spring Portlet MVC?

  • slawek

    Hello,
    It’s great example and it work fine in my spring 3 enviroment. But in my case I would like to open pdf document in new window with adobe acrobat. How can i do it?

    Regards
    sw

    • ssouas

      please tell me how you do because that is not working for me I have always arror 404

  • Emil

    Add this to the end of your config.xml and that worked for me at least
    This now finds the right controller to call and produces a pdf for me at least

  • Emil

    Hi,

    I used this example in sts 2.5.* and it worked great.

    In the 3.0.* version they dropped ajaxUrlResolver and brought in
    org.springframework.web.servlet.view.UrlBasedViewResolver

    and now the controller in this project doesnt get resolved anymore.

    Anyone have any idea how to get this working again with the new springsource ?

    Thanks in advance

  • Nitin

    Can you please tell me how to perform the same in struts 2?
    I have an application build in struts 2 in which JPA query returns the value from database , I need to export the result into PDF and mail it.

  • ditesh shetty

    Article was very good but how to add more than two columns
    or how to format pdf

    • http://www.mkyong.com mkyong

      for advance pdf manipulation, you can consult the iText documentation.

      • http://www.mkyong.com Ramu

        hi mkyong,

        U have given good example on pdf generation in spring mvc frame work, but it is nt working wn am giving url as of u..

  • Andy

    In your spring-pdf-views.xml excerpt, did you mean “PdfRevenueSummary” instead of “ExcelRevenueSummary”?

    • http://www.mkyong.com mkyong

      Thanks for the correction, article is updated.

      • http://www.mkyong.com/spring-mvc/spring-mvc-export-data-to-pdf-file-via-abstractpdfview/ gani

        when am changing the data in java class it is not responding, can u help me pls………..

  • Jan

    When I imported this project into STS and try to run it using the given url, I get a 404 error.

    • http://www.mkyong.com mkyong

      zip your project (exclude libraries) and send it to you, so that i can see what’s happened.

      • Denison

        HTTP Status 404 – /SavariWebApp/revenuereport.htm

        The problem was the html file is not present as part of the project file.

        In the above mentioned line, SavariWebApp is my Context of my web Application.

        Could you please send us the html file too.

        • http://www.mkyong.com mkyong

          The normal return is a RevenueSummary.jsp file, which is available in the attachment already.

          if(output ==null || "".equals(output)){
            //return normal view
            return new ModelAndView("RevenueSummary","revenueData",revenueData);
            //...
          }
          • Deni

            Thanks a Lot mykong. For me the URL is

            .. /SavariWebApp/revenuereport.htm?output=pdf

            In such case, Do I need to create an other JSP with the view name PdfRevenueSummary ? Could you please explain, Am just a new to this.

            Thanks in Advance.

          • Deni

            We have an entry for view for pdfRevenueSummary also, But Still why am I getting 404 error.

            Please Correct me if I am using a correct URL for getting a PDF report.

            http://localhost:8081/SavariWebApp/revenuereport.htm?output=pdf