Thymeleaf (Java)
This guide explains how to generate an HTML string using Java's Thymeleaf template engine and convert it to PDF by sending it to pdfg's API.
Technical Overview
- Create a Thymeleaf template
- Pass data to the template to generate an HTML string
- Send the generated HTML string to pdfg's API to convert it to PDF
Sample
Defining the Template
<!-- templates/invoice.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head></head>
<body>
<div class="invoice">
<h1>Invoice</h1>
<table>
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${items}">
<td th:text="${item.name}"></td>
<td th:text="${item.price} + ' USD'"></td>
</tr>
</tbody>
</table>
<p class="total" th:text="'Total: ' + ${total} + ' USD'"></p>
</div>
</body>
</html>
Using the Template and Generating PDF
// GeneratePdf.java
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
public class GeneratePdf {
public static void main(String[] args) throws Exception {
// Configure Thymeleaf
TemplateEngine templateEngine = new TemplateEngine();
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("/templates/");
resolver.setSuffix(".html");
templateEngine.setTemplateResolver(resolver);
// Prepare data
List<Map<String, Object>> items = List.of(
Map.of("name", "Product A", "price", 1000),
Map.of("name", "Product B", "price", 2000)
);
int total = 3000;
// Set context
Context context = new Context();
context.setVariable("items", items);
context.setVariable("total", total);
// Generate HTML string
String html = templateEngine.process("invoice", context);
// Create request body
String requestBody = String.format("""
{
"html": "%s",
"pdfOptions": {
"format": "A4"
}
}
""", html.replace("\"", "\\\""));
// Request to pdfg's API
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.pdfg.net/v1"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer YOUR_API_KEY")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<byte[]> response = client.send(request,
HttpResponse.BodyHandlers.ofByteArray());
// Save PDF
if (response.statusCode() == 200) {
Files.write(Path.of("invoice.pdf"), response.body());
}
}
}