20
Jul
09

Spring MVC with PDF Output


This site is a collaborative effort! The complete text and sourcecode for this is available on GitHub. Corrections and enhancements are welcome, please make the change and submit a pull request in the comment area below.

Spring MVC takes the Model View Controller to the next level. It allows developers to separate each component of the MVC pattern very cleanly.

This tutorial will show you guys how to output the View in 2 different formats (PDF, and Excel) just by switching a configuration file. First we will display the page as a PDF then thru a configuration change the page will show up as an excel sheet.

First we start with a blank Project

Follow the instructions on setting up and configuring a basic application here:
https://numberformat.wordpress.com/2009/07/19/spring-mvc-hello-world/

Since we are working with PDF iText API we need to add one additional dependency to the maven pom.xml file.

                <dependency>
                        <groupId>com.lowagie</groupId>
                        <artifactId>itext</artifactId>
                        <version>1.3</version>
                </dependency>

Save and regenerate the eclipse project files by dropping to the command line, cd to the project folder and typing:

mvn eclipse:clean eclipse:eclipse

spring-servlet.xml should look like this




<beans>

        <bean name="/helloWorld" class="test.HelloWorldController">
        </bean>

  <bean id="mixedResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="order" value="1"></property>
<property name="basename" value="views"></property>
  </bean>
</beans>

views.properties should look like this…

#--------------------------------
# PDF
#--------------------------------
helloWorld.class=test.web.view.HelloWorldPdfView

The following java class has code that constructs the actual PDF. Here we are using iText library API to construct the page. Other API’s such as FOP can be used as well however they are beyond the scope of this simple tutorial.

HelloWorldPdfView.java should look like this…

package test.web.view;

import java.util.Map;

import java.util.List;
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.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class HelloWorldPdfView extends AbstractPdfView {

    @Override
    protected void buildPdfDocument(
        Map model,
        Document document,
        PdfWriter writer,
        HttpServletRequest request,
        HttpServletResponse response)
    throws Exception {

        Paragraph header = new Paragraph(new Chunk(
            "This is a PDF from the Hello World Web App",
            FontFactory.getFont(FontFactory.HELVETICA, 24)));
        document.add(header);

    }

}

To view the PDF navigate to the following URL:

http://localhost:8080/helloWorldPDF/app/helloWorld

A PDF should have displayed after navigating to the above URL.

Before we continue further we need to define some data to display on the page. We can only take a single “hello World” line so far. For the next part we will define some data to display in Excel and in raw XML.

Make Model Year
Ford Mustang 1966
Chevrolet Corvette 1978
Chevrolet Chevelle 1968

To get a list of these beans we need to define the Car bean:

package test;

public class Car {
        private String make;
        private String model;
        private String year;

        public Car(String make, String model, String year) {
                this.make = make;
                this.model = model;
                this.year = year;
        }
        public String getMake() {
                return make;
        }
        public void setMake(String make) {
                this.make = make;
        }
        public String getModel() {
                return model;
        }
        public void setModel(String model) {
                this.model = model;
        }
        public String getYear() {
                return year;
        }
        public void setYear(String year) {
                this.year = year;
        }

}

The Controller needs to be modified to return a list of classic cars so that they can be displayed by the view.

package test;

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

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloWorldController extends AbstractController {
        @Override
        protected ModelAndView handleRequestInternal(HttpServletRequest request,
                        HttpServletResponse response) throws Exception {

                ModelAndView mav = null;
                // control logic goes here
                mav = new ModelAndView("helloWorld");

                // Its bad but to keep things simple we will do
                // some business logic here.
                List<car> cars = new ArrayList<car>();

                cars.add(new Car("Ford", "Mustang", "1966"));
                cars.add(new Car("Chevrolet","Corvette","1978"));
                cars.add(new Car("Chevrolet","Chevelle","1968"));

                mav.addObject("cars", cars);

                return mav;
        }
}

We need to define the View that will generate the excel sheet:

package test.web.view;

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

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

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import test.Car;

public class HelloWorldExcelView extends AbstractExcelView {

    @Override
    protected void buildExcelDocument(
        Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
    throws Exception {

        List<car> cars = (List<car>)model.get("cars");

        HSSFSheet dataSheet = workbook.getSheet("ClassicCar");

        int row = 4;
        for (Car car : cars) {
            int column = 0;
            getCell(dataSheet, row, ++column).setCellValue(car.getMake());
            getCell(dataSheet, row, ++column).setCellValue(car.getModel());
            getCell(dataSheet, row, ++column).setCellValue(car.getYear());
            row++;
        }

    }
}

Then we need to define the excel sheet template that will be used to generate the excel sheet.
helloWorld.xls
Save this excel sheet in WEB-INF/excel/helloWorld.xls

Modify views.properties to look like this:

#--------------------------------
# Excel
#--------------------------------
helloWorld.class=test.web.view.HelloWorldExcelView
helloWorld.url=/WEB-INF/excel/helloWorld

#--------------------------------
# PDF
#--------------------------------
#helloWorld.class=test.web.view.HelloWorldPdfView
This site is a collaborative effort! The complete text and sourcecode for this is available on GitHub. Corrections and enhancements are welcome, please make the change and submit a pull request in the comment area below.
Advertisements

1 Response to “Spring MVC with PDF Output”


  1. 1 Noman
    May 5, 2010 at 9:27 am

    hello

    this is very nice blog which u create on Spring export data..
    i am interested to export my html data as excel format..
    the whole configuration is not enough to start please kindly explain it more..
    thanx


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

July 2009
S M T W T F S
    Aug »
 1234
567891011
12131415161718
19202122232425
262728293031  

Blog Stats

  • 846,580 hits

%d bloggers like this: