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 the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
James K
Guest
James K

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

trackback
Spring MVC Tutorial

[…] Spring MVC and PDF file via AbstractPdfView Using AbstractPdfView to export data to Pdf file via Bruno Lowagie’s iText library. […]

DR
Guest
DR

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
Guest
Sagar

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

Raghu
Guest
Raghu

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
Guest
juehee

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

Raghu
Guest
Raghu

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
Guest
bala

mkyong, how to integrate pdf output in tiles body?

subrat kumar nayak
Guest
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
Guest
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
Guest
Julian
Shikher
Guest
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
Guest
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
Guest
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
Guest
test

I dont know how to do it

ANSON VATTOLY
Guest
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
Guest
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
Guest
Tapas

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

Tapas
Guest
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
Guest
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
Guest
Sudheendra

Have you got this working with Spring Portlet MVC?

slawek
Guest
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
Guest
ssouas

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

Emil
Guest
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
Guest
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
Guest
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
Guest
ditesh shetty

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

Andy
Guest
Andy

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

Jan
Guest
Jan

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