Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate pdf report using thymeleaf as template engine? [closed]

I want to create pdf report in a spring mvc application. I want to use themeleaf for designing the html report page and then convert into pdf file. I don't want to use xlst for styling the pdf. Is it possible to do that way?

Note: It is a client requirement.

like image 650
Anindya Chatterjee Avatar asked Feb 10 '16 16:02

Anindya Chatterjee


People also ask

Is Thymeleaf a template engine?

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

What is the advantage of using Thymeleaf?

Thymeleaf provides useful formatting utilities such as ${#calendars. format(...)} , ${#strings. capitalize(...)} which are well integrated with Spring e.g. you can pass model beans propagated by Spring MVC into these functions. The build/deploy/test feedback loop is shortened by Thymeleaf.


1 Answers

You can use SpringTemplateEngine provided by thymeleaf. Below is the dependency for it:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring4</artifactId>
</dependency>

Below is the implementation I have done to generate the PDF:

@Autowired
SpringTemplateEngine templateEngine;

public File exportToPdfBox(Map<String, Object> variables, String templatePath, String out) {
    try (OutputStream os = new FileOutputStream(out);) {
        // There are more options on the builder than shown below.
        PdfRendererBuilder builder = new PdfRendererBuilder();
        builder.withHtmlContent(getHtmlString(variables, templatePath), "file:");
        builder.toStream(os);
        builder.run();
    } catch (Exception e) {
        logger.error("Exception while generating pdf : {}", e);
    }
    return new File(out);
}

private String getHtmlString(Map<String, Object> variables, String templatePath) {
    try {
        final Context ctx = new Context();
        ctx.setVariables(variables);
        return templateEngine.process(templatePath, ctx);
    } catch (Exception e) {
        logger.error("Exception while getting html string from template engine : {}", e);
        return null;
    }
}

You can store the file in Java temp directory shown below and send the file wherever you want:

System.getProperty("java.io.tmpdir");

Note: Just make sure you delete the file once used from the temp directory if your frequency of generating the pdf is high.

like image 87
Vijay Avatar answered Sep 19 '22 02:09

Vijay