You can use SpringTemplateEngine
provided by thymeleaf. Below is the dependency for it:
org.thymeleaf
thymeleaf-spring4
Below is the implementation I have done to generate the PDF:
@Autowired
SpringTemplateEngine templateEngine;
public File exportToPdfBox(Map 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 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.