I am working on a functionality where the application needs to generate user specific emails. This will be setup or configured on the user level using a email template which essentially contains a SQL query, column model, data type, subject, header, footer etc. The template serves as the dataset and layout for the email.
Now using this XML template I need to generate the HTML email. The application will read the XML, execute the SQL query and then match the resultset to the column model. Beyond this; is there any framework or API that can help generate the HTML response (nicely formatted css table) from Java objects or it has to be cooked using raw HTML tags (, etc.)?
I was also researching to see if BIRT or Jasper can provide HTML response but it doesn't seem like they are meant for that. If anyone has experience building a solution for such a use case please let me know.
Take a look at Thymeleaf. It's a HTML template engine.
It's as simple as this:
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setTemplateMode("HTML5");
resolver.setSuffix(".html");
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(resolver);
final Context context = new Context(Locale.CANADA);
String name = "John Doe";
context.setVariable("name", name);
// add more objects from your ResultSet
final String html = templateEngine.process("myhtml", context);
with a myhtml.html file:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-3.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>My first template with Thymeleaf</title>
</head>
<body>
<p th:text="${name}">A Random Name</p>
</body>
</html>
Here the placeholder ${name} will replace the value A Random Name in the <p> element by the value you inserted in the context.
As for your requirement of reading and generating a table, Thymeleaf provides constructs to loop as many times as is required (ie. as long as you have data remaining). Example:
<tr th:each="prod : ${allProducts}">
will iterate through allProducts, assigning each object to the variable prod at each iteration. Take a look at the tutorials and the docs for more.
Notice, you have to write the HTML yourself.
Take a look at this answer for generating HTML report through Jasper
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