Generating and downloading PDF using spring boot and Thymeleaf

Posted By : Bhanu Pratap Singh | 28-Feb-2021

Spring boot

Loading...

In this blog, we will be generating a pdf document using the thymeleaf template. For this, we need to add these dependencies in our pom.xml or build.gradle file. In this blog, we will be using gradle dependencies.

spring-boot-starter-thymeleaf

flying-saucer-pdf

Follow these steps :

STEP 1 : Create Project

Let us use the Spring Initializer page to create the project.

add these dependencies :

1. Spring Web

2. Lombok

3. Thymeleaf

STEP 2 : Import project to IDE

STEP 3 : Add the Flying Saucer dependency.

STEP 4 : Create Model class

@Entity

public class Student {

private Integer id;

private String firstName;

private String lastName;

private String class;

}

STEP 4 : Create StudentRepository.java

@Repository

public interface StudentRepository extends JPARepository<Student, Integer>{

}

STEP 5 : Create StudentController.java

@RestController

public class StudentController{

@Autowired

private StudentRepository studentRepository;

@Autowired

private PdfGenaratorUtil pdfGenaratorUtil;

@GetMapping("student/{studentId}")

public ResponseEntity getStudentInfoPdf(@PathVariable Integer studentId){

Student student = studentRepository.findById(studentId).orElse(null);

if(student == null)

throw new Exception("Student not present");

Map<String,Object> studentMap = new HashMap<>();

studentMap.put("ID",student.getId());

studentMap.put("firstName",student.getFirstName());

studentMap.put("lastName",student.getLastName());

studentMap.put("class",student.getClass());

Resource resource = null;

try {

String property = "java.io.tmpdir";

String tempDir = System.getProperty(property);

String fileNameUrl = pdfGenaratorUtil.createPdf("Student", studentMap);

Path path = Paths.get(tempDir+"/" + fileNameUrl);

resource = new UrlResource(path.toUri());

} catch (Exception e) {

e.printStackTrace();

}

return ResponseEntity.ok()

.contentType(MediaType.parseMediaType(MediaType.APPLICATION_PDF_VALUE))

.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")

.body(resource);

}

}

STEP 6 : Create PdfGenaratorUtil.java

@Component

public class PdfGenaratorUtil {

@Autowired

private TemplateEngine templateEngine;

public String createPdf(String templatename, Map map) throws IOException, DocumentException {

String fileNameUrl = "";

Context ctx = new Context();

if (map != null) {

Iterator itMap = map.entrySet().iterator();

while (itMap.hasNext()) {

Map.Entry pair = (Map.Entry) itMap.next();

ctx.setVariable(pair.getKey().toString(), pair.getValue());

}

}

String processedHtml = templateEngine.process(templatename, ctx);

FileOutputStream os = null;

String studentId = map.get("ID").toString();

try {

final File outputFile = File.createTempFile("Student_"+studentId+"_", ".pdf");

os = new FileOutputStream(outputFile);

ITextRenderer itr = new ITextRenderer();

itr.setDocumentFromString(processedHtml);

itr.layout();

itr.createPDF(os, false);

itr.finishPDF();

fileNameUrl = outputFile.getName();

}

finally {

if (os != null) {

try {

os.close();

} catch (IOException e) { }

}

}

return fileNameUrl;

}

}

STEP 7 : Create Thymleaf configuration file ThymeleafConfig.java

@Configuration

public class ThymeleafConfig {

@Bean

public ClassLoaderTemplateResolver emailTemplateResolver(){

ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();

emailTemplateResolver.setPrefix("templates/");

emailTemplateResolver.setTemplateMode("HTML5");

emailTemplateResolver.setSuffix(".html");

emailTemplateResolver.setTemplateMode("XHTML");

emailTemplateResolver.setCharacterEncoding("UTF-8");

emailTemplateResolver.setOrder(1);

return emailTemplateResolver;

}

}

STEP 8 : Create thymleaf template inside

src>main>resources>templates>Student.html

<!DOCTYPE HTML>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<title>Student Details</title>

</head>

<body>

<img class="logo" src="images/logo.png"/>

<div>

<p>Student id : <span th:text="${ID}"></span></p>

<p>First Name : <span th:text="${firstName}"></span></p>

<p>Last Name : <span th:text="${lastName}"></span></p>

<p>Class : <span th:text="${class}"></span></p>

</div>

</body>

</html>

STEP 9 : Run the project and hit the endpoint student/{studentId


At Oodles ERP, we provide end-to-end ERP development services with a focus on implementing next-gen technologies to enhance business productivity. Our development team specializes in using open-source tools like Odoo, OFBiz, ERPNext, and Opentaps to address cross-industry enterprise challenges and solve complex business problems. For more information, reach us out at [email protected].