You can do this with Itext and Thymeleaf.
In your controller you will receive one HttpServletResponse
responsible for the response stream of your PDF. In the class that will do the processing you must inject a SpringTemplateEngine
, which in the example was attributed to the templateEngine
.
Variables will be set in your html template in the same way as with Thymeleaf.
The variable nomeTemplate
is the name of the html file in your /Resources folder. For example: report.html. It must be a valid Thymeleaf template!
public void download(String nomeTemplate, HttpServletResponse response){
Context context = new Context();
Map<String, Object> variaveis = getAlgumasVariaveis();
variaveis.forEach(context::setVariable);
String html = templateEngine.process(nomeTemplate, context);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
try {
renderer.createPDF(outputStream);
} catch (DocumentException e) {
e.printStackTrace();
}
}