Spring offers ways to return output other than HTML, including PDF and Excel spreadsheets.

Introduction to Document Views

An HTML page is not always the best way for a user to view simulation results, and Spring makes it easy to dynamically generate a PDF document or Excel spreadsheet based on model data. The document is a representation and is sent from the server with the appropriate content type to (hopefully) allow the client PC to launch its spreadsheet or PDF viewer application in response.

In order to use Excel views, you need to add the Apache POI library to your classpath. To generate PDF you need to add (preferably) the OpenPDF library.

Where possible, you should use the latest versions of the main document generation libraries. In particular, we highly recommend OpenPDF (e.g. OpenPDF 1.2.12) over the outdated original iText 2.1.7, as OpenPDF is actively maintained and patches an important vulnerability for untrusted PDF content.

PDF views

A simple PDF view for a list of words can extend org.springframework.web.servlet.view.document.AbstractPdfView and implement the buildPdfDocument() method, as shown in the following example :

Java
public class PdfWordList extends AbstractPdfView {
    protected void buildPdfDocument(Map<String, Object> model, Document doc, PdfWriter writer,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<String> words = (List<String>) model.get("wordList");
        for (String word : words) {
            doc.add(new Paragraph(word));
        }
    }
}
Kotlin
class PdfWordList : AbstractPdfView() {
    override fun buildPdfDocument(model: Map<String, Any>, doc: Document, writer: PdfWriter,
            request: HttpServletRequest, response: HttpServletResponse) {
        val words = model["wordList"] as List<String>
        for (word in words) {
            doc.add(Paragraph(word))
        }
    }
}

The controller can return such a view either from an external view definition (referring to it by name) or as a View instance from a handler method.

Excel Views

Starting with Spring Framework 4.2, org.springframework.web.servlet.view.document.AbstractXlsView is provided as a base class for Excel views. It is based on Apache POI with specialized subclasses (AbstractXlsxView and AbstractXlsxStreamingView) that replace the legacy AbstractExcelView class.

The programming model is similar to AbstractPdfView, with buildExcelDocument() as the central template method and controllers capable of returning such a view from an external definition (by name) or as an instance of View from the handler method.