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.
Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With