How to generate pdf report using thymeleaf as template engine?

Anindya Chatterjee picture Anindya Chatterjee · Feb 10, 2016 · Viewed 18.2k times · Source

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.

Answer

Vijay picture Vijay · Dec 19, 2018

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.