Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
40 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Raghu
9 years ago

Hi Mkyong,
this is very helpful, how can i open the generated pdf in new window ?
i tried it by adding target=”_blank”, but this also opens new open window even if form validation fails.
i am trying to open the PDF doc in new window only upon form successful validation.
thanks

juehee
9 years ago
Reply to  Raghu

I’m trying the same.. did you find the solution?

Raghu
9 years ago
Reply to  juehee

i could resolve this by sending the response to some jsp page in both success and failure scenarios. from that jsp, in success scenario i have submitted hidden form by giving target=”_blank”. which opens new window only success scenario.

bala
10 years ago

mkyong, how to integrate pdf output in tiles body?

phani
10 years ago

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

Shikher
10 years ago

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
10 years ago

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
11 years ago

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
10 years ago
Reply to  sujata

I dont know how to do it

Ano
4 years ago

please get down this time waste

Raghu Ram
4 years ago

Can some one explain me the flow for this please , I did not understand how revenuereport.htm? came into ULR and also I have doubt with the flow that is whether RevenueReportController or buildPdfDocument loads first .

Johel Llanos Cueva
5 years ago

Nice example, but how can I print it instead of showing it?

James K
6 years ago

Wondering what the changes would be with newer versions of SW that are now available… Wanted to ask before I start to explore.. We use Spring Boot in our project..
Thank You

DR
8 years ago

Where is the PdfRevenueSummary file? Only the normal view .jsp is available in the download.
I want a pdf view and it is very confusing.

Sagar
8 years ago

Hello This is actually very helpful post thanks a lot for the same. I have one query, The PDF file is get open in browser not showing pop up to download. so could you please help me

subrat kumar nayak
10 years ago

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.

ANSON VATTOLY
11 years ago

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
11 years ago

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
11 years ago

Dear how it will work with spring annotation…Please demonstrate 🙂

Tapas
11 years ago
Reply to  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
11 years ago

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
12 years ago

Have you got this working with Spring Portlet MVC?

slawek
12 years ago

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
10 years ago
Reply to  slawek

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

Emil
13 years ago

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
13 years ago

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
13 years ago

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
13 years ago

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

Ramu
11 years ago
Reply to  mkyong

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
13 years ago

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

gani
11 years ago
Reply to  mkyong

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

Jan
13 years ago

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

Denison
13 years ago
Reply to  mkyong

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.

Deni
13 years ago
Reply to  mkyong

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

Deni
13 years ago
Reply to  mkyong

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.