PDF Generation with Spring and iText

Spring makes it quite easy to generate a PDF view utilizing iText

To generate a PDF document for the Spring MVC View, simply extend AbstractPdfView.

public class WidgetListPdfView extends AbstractPdfView
{
  protected void buildPdfDocument(Map model,
                                  Document doc,
                                  PdfWriter writer, 
                                  HttpServletRequest req, 
                                  HttpServletResponse resp)
                                  throws Exception
  {
    //it's your job to simply mutate
    //the Document based on data from the model 
  }
}

AbstractPdfView implements the View’s render(Map model, HttpServletRequest request, HttpServletResponse response) for you, makes a new iText Document for you, and makes you implement protected void buildPdfDocument(Map model, Document doc, PdfWriter writer, HttpServletRequest req, HttpServletResponse resp). From there, you have to simply work with the iText Document normally as you would if you were using iText directly. Spring will handle the messy work of setting the response content type, streaming the PDF to the browser, etc.

Here is a full example to generate a PDF file given a list of Widgets in the model:

package com.zabada.springrecipes.pdf;

import java.util.Iterator;
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.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import com.zabada.springrecipes.model.Widget;

public class WidgetListPdfView extends AbstractPdfView
{
  public static final String WIDGET_LIST_KEY = "widgetList";

  protected void buildPdfDocument(Map model,
                                  Document doc,
                                  PdfWriter writer, 
                                  HttpServletRequest req,
                                  HttpServletResponse resp)
                                  throws Exception
  {
    List widgets = (List) model.get(WIDGET_LIST_KEY);

    Iterator widgetIterator = widgets.iterator();
    while(widgetIterator.hasNext())
    {
      Widget widget = (Widget)widgetIterator.next();
      doc.add(new Paragraph(widget.toString()));
    }
  }
}

Further Reading

Next: Writing a Custom Spring MVC View (RSSView)