Thymeleaf Spring Boot Example

By | | Updated : 2021-03-16 | Viewed : 4046 times

Thymeleaf Spring Boot Example

A Quick tutorial explains pdf generation with Thymeleaf and Spring Boot. Let\'s start the examination the example for the same.

A Brief Intro For Thymeleaf

Thymeleaf is a template engine that will be used in Web/Non-web applications as well. This is implemented in Java to produce the XML/XHTML/html5 content dynamically. Some of the Web MVC applications are also using this Thymeleaf template engine. It is easily been used and integrated with spring applications.

Maven dependencies

Maven dependencies used for Thymeleaf
 
 <dependency>
 <groupId>org.thymeleaf</groupId>
 <artifactId>thymeleaf</artifactId>
 <version>${thymeleaf.version}</version>
 </dependency>
 
 <dependency>
 <groupId>org.xhtmlrenderer</groupId>
 <artifactId>flying-saucer-pdf</artifactId>
 <version>${flying-saucer-pdf.version}</version>
 </dependency>

thymeleaf is useful for templating the HTML and then can be generated the HTML dynamically.flying-saucer-pdf generates the PDF file form input of html.

Thymeleaf Example for PDF Generation

Setup for ClassLoaderTemplateResolver of Thymeleaf

Please see the below method in PdfReportGenUtil.java class. Here this method takes input as an object and will pass these objects to the Template Engine for dynamic template generation.

parseThymeleafTemplate() in PdfReportGenUtil.java
public static String parseThymeleafTemplate(Map contentMap) {

        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        Context context = new Context();
        context.setVariable("schoolName", contentMap.get("schoolName"));
        context.setVariable("studentName", contentMap.get("studentName"));
        context.setVariable("className", contentMap.get("className"));
        context.setVariable("markLists", contentMap.get("markLists"));

        return templateEngine.process("progress_report_template.html", context);
    }

If you observe above code there are three important classes of Thymeleaf library.

  • 1. ClassLoaderTemplateResolver

  • 2. TemplateEngine

  • 3. Context

The ClassLoaderTemplateResolver class is used for settings where this setting is used in generation of HTML string content

Once done with settings into ClassLoaderTemplateResolver then it should be set up to TemplateEngine.

The context is the main class where data objects passed through it. So whatever data object you pass to Context class then Thymeleaf will use for parsing of the dynamic template. Finally, TemplateEngine uses the HTML template File (progress_report_template.html) and Context object to generate an HTML string after parsing the HTML file.

Create HTML Template for Thymeleaf Parsing

Notice we create the progress_report_template.html where all Thymeleaf syntaxes are placed for generating the dynamic template using. And same file name should be passed into TemplateEngine class. Please look above method.

progress_report_template.html
<table class="table table-stripped" style="color: white;background-color: #4da5a9;width:100%;">
	 <thead >
	 <tr>
	 <td>First Language</td>
	 <td>Second Language</td>
	 <td>Mathematics</td>
	 <td>General Science</td>
	 <td>Social Studies</td>
	 </tr>
	 </thead>
	 <tr th:each="marks:${markLists}">
	 <td th:text="${marks.firstLang}">Id</td>
	 <td th:text="${marks.secondLang}">Name</td>
	 <td th:text="${marks.mathematics}">Department</td>
	 <td th:text="${marks.generalScience}">Updated By</td>
	 <td th:text="${marks.socialStudies}">Updated On</td>
	 </tr>
</table>

If you notice the markLists here. The markLists are added in Context objects. Please observe the above-given method parseThymeleafTemplate. Here th:each is thymeleaf tag as like for loop in java and iterate list to generate the multiple of tr tags of HTML. These types of objects processed and parsed based on the type of thymeleaf tags.

And we used th:text to generate the text string from the respective object of th:each in each loop iteration.

Generate PDF using flying-saucer-pdf

Once the parsed the dynamic html content then it should be used to generate the pdf. Please look at the below method.

generatePdfFromHtml() in PdfReportGenUtil.java
public static void generatePdfFromHtml(String pdfDirectory, String html) throws IOException, DocumentException {
	 String outputFolder = pdfDirectory + File.separator + "Progress-Report.pdf";
	 OutputStream outputStream = new FileOutputStream(outputFolder);
	 ITextRenderer renderer = new ITextRenderer();
	 renderer.setDocumentFromString(html);
	 renderer.layout();
	 renderer.createPDF(outputStream);
	 outputStream.close();
}

Here the parsed XHTML string will be processed for generating the pdf file in the required directory. ITextRenderer is the main class for rendering the pdf file. Need to set here type of layout. And setDocumentFromString() is used from which string the pdf should be generated means the XHTML string need to pass here.

Please look at this repository Spring-Boot-PDF-Thymeleaf-Example-App for this example.

Leave A Reply