Spring MVC - PDF View

[Updated: Sep 20, 2017, Created: Sep 20, 2017]

This example demonstrates how to create a PDF document and use it as the view technology in a Spring MVC application. We are going to use iText library for creating the document programmatically.

Example

Additional Maven Dependency

pom.xml

<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext7-core</artifactId>
   <version>7.0.4</version>
</dependency>

Java Config class

In this example, we are going to use BeanNameViewResolver for resolving PDF view. That means we need to register an implementation of View as a bean. We will return the bean name as a view name from the Spring controller. Check out this simple example of BeanNameViewResolver as well.

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig {
  @Bean
  public ViewResolver beanNameViewResolver() {
      BeanNameViewResolver resolver = new BeanNameViewResolver();
      return resolver;
  }

  @Bean
  public ViewResolver jspViewResolver() {
      InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
      viewResolver.setPrefix("/WEB-INF/views/");
      viewResolver.setSuffix(".jsp");
      return viewResolver;
  }
}

Implementing the View

Spring provides a support class AbstractPdfView but that is based on old deprecated iText API. We are going extend AbstractView and use iText API directly.

package com.logicbig.example;

import com.itextpdf.io.font.FontConstants;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Map;

@Component("reportView")
public class ReportPdfView extends AbstractView {

  @Override
  protected void renderMergedOutputModel(Map<String, Object> model,
                                         HttpServletRequest request,
                                         HttpServletResponse response) throws Exception {
      response.setHeader("Content-Disposition", "attachment; filename=myReport.pdf");
      Report report = (Report) model.get("report");

      //IText API
      PdfWriter pdfWriter = new PdfWriter(response.getOutputStream());
      PdfDocument pdf = new PdfDocument(pdfWriter);
      Document pdfDocument = new Document(pdf);

      //title
      Paragraph title = new Paragraph(report.getName());
      title.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA));
      title.setFontSize(18f);
      title.setItalic();
      pdfDocument.add(title);

      //date
      Paragraph date = new Paragraph(report.getDate().format(
              DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
      date.setFontSize(16f);
      pdfDocument.add(date);

      //content
      Paragraph content = new Paragraph(report.getContent());
      pdfDocument.add(content);

      pdfDocument.close();
  }
}
public class Report {
  private String name;
  private String content;
  private LocalDateTime date;
    .............
}

Writing a Spring Controller

@Controller
@RequestMapping("/")
public class MyController {

  @GetMapping("/")
  public String mainView() {
      return "main";
  }

  @GetMapping("/report")
  public String handleForexRequest(Model model) {
      model.addAttribute("report", getReport());
      return "reportView";
  }

  public Report getReport() {
      //dummy report
      Report report = new Report();
      report.setName("My Report");
      report.setContent("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. "
              + "Aenean commodo ligula eget dolor. Aenean massa.");
      report.setDate(LocalDateTime.now());
      return report;
  }
}

src/main/webapp/WEB-INF/views/main.jsp

<html>
<body>
<h2>Spring Pdf View Example</h2>
<a href="/report">Get the Report</a>

</body>
</html>

Output

clicking on the link:

Example Project

Dependencies and Technologies Used :

  • spring-webmvc 4.3.11.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.1.0 Java Servlet API
  • itext7-core 7.0.4: A Free Java-PDF library.
  • JDK 1.8
  • Maven 3.3.9

Spring PDF View Example Select All Download
  • spring-pdf-view-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views

See Also