So i'm trying to generate a pdf file from a thymeleaf template but I get this error when running my app.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field templateEngine in com.example.app.service.PdfService required a bean of type 'org.thymeleaf.TemplateEngine' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.thymeleaf.TemplateEngine' in your configuration.
Process finished with exit code 0
HERE IS HOW MY APPLICATION LOOKS LIKE. Everything looks correct and I don't know what i've done wrong
my configuration file :
@Configuration
public class ThymeleafConfig {
@Bean
public ClassLoaderTemplateResolver templateResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/");
templateResolver.setTemplateMode("HTML5");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("XHTML");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setOrder(1);
return templateResolver;
}
}
my PdfService :
@Service
public class PdfService {
@Autowired
private TemplateEngine templateEngine;
public void createPDF() throws DocumentException, IOException {
Context context = new Context();
context.setVariable("name","developper.com");
String processHtml = templateEngine.process("helloworld",context);
OutputStream outputStream = new FileOutputStream("message.pdf");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(processHtml);
renderer.layout();
renderer.createPDF(outputStream,false);
renderer.finishPDF();
outputStream.close();
}
}
my main app :
@Bean
CommandLineRunner run(PdfService pdfService) {
return args -> {
System.out.println("creating pdf...");
pdfService.createPDF();
System.out.println("pdf creation complete!");
};
}
CodePudding user response:
In configuration class, create template engine bean and set template resolver which you have created:
@Bean
public SpringTemplateEngine templateEngine() {
var templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
CodePudding user response:
TemplateEngine
is not autoconfigured, so you need to add to your configuration something like (remember to set the TemplateResolver
s)
@Bean
public TemplateEngine templateEngine() {
return new TemplateEngine();
}
or alternatively, you can just inject it via
final TemplateEngine templateEngine = new TemplateEngine();