Spring Boot PDF Notes
Spring Boot PDF Notes
Home Subscrib
iText is an open source library for creating and manipulating PDF files in Java.
Spring is a Java application framework for developing Java enterprise applications. It also helps
integrate various enterprise components. Spring Boot makes it easy to create Spring-powered,
production-grade applications and services with minimum setup requirements.
H2 is an open source relational database management system implemented entirely in Java. It can be
embedded in Java applications or run in the client-server mode. It has small footprint and is easy to
deploy and install. It contains a browser based console application for viewing and editing datatabase
tables.
Spring Data JPA is part of the umbrella Spring Data project that makes it easier to implement JPA base
repositories. Spring Data JPA uses JPA to store data in a relational database. It can create repository
implementations automatically, at runtime, from a repository interface.
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ │ Application.java
│ │ ├───controller
│ │ │ MyController.java
│ │ ├───model
│ │ │ City.java
│ │ ├───repository
│ │ │ CityRepository.java
│ │ ├───service
│ │ │ CityService.java
│ │ │ ICityService.java
zetcode.com/springboot/servepdf/ 1/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
│ │ └───util
│ │ GeneratePdfReport.java
│ └───resources
│ application.yml
│ import.sql
└───test
└───java
pom.xml
<groupId>com.zetcode</groupId>
<artifactId>springbootservepdf</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
zetcode.com/springboot/servepdf/ 2/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Spring Boot starters are a set of useful dependency descriptors which greatly simplify Maven
configuration. The spring-boot-starter-parent has some common configurations for a Spring Boot
application. The spring-boot-starter-web is a starter for building web applications with Spring MVC
It uses Tomcat as the default embedded container. The spring-boot-starter-data-jpa is a starter fo
using Spring Data JPA with Hibernate.
com/zetcode/model/City.java
package com.zetcode.model;
import java.util.Objects;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "cities")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public City() {
}
zetcode.com/springboot/servepdf/ 3/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + Objects.hashCode(this.id);
hash = 79 * hash + Objects.hashCode(this.name);
hash = 79 * hash + this.population;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final City other = (City) obj;
if (this.population != other.population) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return Objects.equals(this.id, other.id);
}
@Override
public String toString() {
zetcode.com/springboot/servepdf/ 4/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
.append(population).append("}");
return builder.toString();
}
}
This is the City entity. Each entity must have at least two annotations defined: @Entity and @Id. The
default value of the spring.jpa.hibernate.ddl-auto property is create-drop which means that
Hibernate will create the table schema from this entity.
@Entity
@Table(name = "cities")
public class City {
The @Entity annotation specifies that the class is an entity and is mapped to a database table. The
@Table entity specifies the name of the database table to be used for mapping.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
The @Id annotation specifies the primary key of an entity and the @GeneratedValue provides for the
specification of generation strategies for the values of primary keys.
resources/application.yml
spring:
main:
banner-mode: "off"
logging:
level:
org:
springframework: ERROR
The application.yml is the main Spring Boot configuration file. With the banner-mode property we
turn off the Spring banner. The spring framework logging is set to ERROR.
resources/import.sql
zetcode.com/springboot/servepdf/ 5/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
The schema is automatically created by Hibernate; later, the import.sql file is executed to fill the table
with data.
com/zetcode/repository/CityRepository.java
package com.zetcode.repository;
import com.zetcode.model.City;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends CrudRepository<City, Long> {
By extending from the Spring CrudRepository, we have some methods for our data repository
implemented, including findAll() and findOne(). This way we do not have to write a lot of boilerplat
code.
com/zetcode/service/ICityService.java
package com.zetcode.service;
import com.zetcode.model.City;
import java.util.List;
List<City> findAll();
}
ICityService provides a contract method to get all cities from the database.
com/zetcode/service/CityService.java
package com.zetcode.service;
import com.zetcode.model.City;
import com.zetcode.repository.CityRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CityService implements ICityService {
@Autowired
private CityRepository repository;
@Override
public List<City> findAll() {
zetcode.com/springboot/servepdf/ 6/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
CityService contains the implementation of the findAll() method. We use repository to retrieve dat
from the database.
@Autowired
private CityRepository repository;
CityRepository is injected.
com/zetcode/controller/MyController.java
package com.zetcode.controller;
import com.zetcode.model.City;
import com.zetcode.service.ICityService;
import com.zetcode.util.GeneratePdfReport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.ByteArrayInputStream;
import java.util.List;
@Controller
public class MyController {
@Autowired
private ICityService cityService;
return ResponseEntity
.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_PDF)
.body(new InputStreamResource(bis));
}
}
zetcode.com/springboot/servepdf/ 7/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
The citiesReport() method returns the generated PDF report. The Resource interface abstracts acce
to low-level resources; InputStreamResource is its implementation for stream resources.
@Autowired
private ICityService cityService;
We inject ICityService object into the attribute. The service object is used to retrieve data from the
database.
The GeneratePdfReport.citiesReport() generates PDF file from the list of cities using iText library
By setting the Content-Disposition to inline, the PDF file is shown directly in browser.
return ResponseEntity
.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_PDF)
.body(new InputStreamResource(bis));
We create a response with ResponseEntity. We specify the headers, content type, and body. The conte
type is MediaType.APPLICATION_PDF. The body is an InputStreamResource.
com/zetcode/util/GeneratePdfReport.java
package com.zetcode.util;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.zetcode.model.City;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
zetcode.com/springboot/servepdf/ 8/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
try {
PdfPCell hcell;
hcell = new PdfPCell(new Phrase("Id", headFont));
hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hcell);
PdfPCell cell;
PdfWriter.getInstance(document, out);
document.open();
document.add(table);
document.close();
zetcode.com/springboot/servepdf/ 9/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
We put our data in a table; for this, we have the PdfPTable class. The table has three columns: Id, Nam
and Population.
PdfPCell hcell;
hcell = new PdfPCell(new Phrase("Id", headFont));
hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hcell);
The data is placed inside table cells, represented by PdfPCell. The text is horizontally aligned using the
setHorizontalAlignment() method.
PdfWriter.getInstance(document, out);
document.open();
document.add(table);
document.close();
In order for the data to be written to the ByteArrayOutputStream, the document must be closed.
com/zetcode/Application.java
package com.zetcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
zetcode.com/springboot/servepdf/ 10/11
3/25/2020 Spring Boot Serve PDF tutorial - creating PDF report in Spring Boot
@SpringBootApplication
public class Application {
$ mvn spring-boot:run
In this tutorial, we have shown how to send a generated PDF file back to the client. The PDF report was
generated with iText and the data came an H2 database. We used Spring Data JPA to access data. You
might also be interested in these related tutorials: Spring Boot basic annotations, Spring Boot H2
tutorial, Spring Boot JasperReports web integration, Java tutorial, or list all Spring Boot tutorials.
zetcode.com/springboot/servepdf/ 11/11