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
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.
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
I’m trying the same.. did you find the solution?
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.
mkyong, how to integrate pdf output in tiles body?
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
Copycat
http://www.javakeexample.com/2013/01/spring-mvc-and-pdf-file-via.html
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
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.
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?
I dont know how to do it
please get down this time waste
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 .
Nice example, but how can I print it instead of showing it?
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
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.
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
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.
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….
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 ?
Dear how it will work with spring annotation…Please demonstrate 🙂
Dear Issue ,I have tried with annotation it is working fine 🙂 just want to know how it can be open in a popup windows ….
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 ??
Have you got this working with Spring Portlet MVC?
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
please tell me how you do because that is not working for me I have always arror 404
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
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
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.
Article was very good but how to add more than two columns
or how to format pdf
for advance pdf manipulation, you can consult the iText documentation.
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..
In your spring-pdf-views.xml excerpt, did you mean “PdfRevenueSummary” instead of “ExcelRevenueSummary”?
Thanks for the correction, article is updated.
when am changing the data in java class it is not responding, can u help me pls………..
When I imported this project into STS and try to run it using the given url, I get a 404 error.
zip your project (exclude libraries) and send it to you, so that i can see what’s happened.
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.
The normal return is a RevenueSummary.jsp file, which is available in the attachment already.
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
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.