I am trying to generate html template to pdf report using flying saucer in Spring Boot application. It is generating pdf but problem is joint letter is not structing properly. It is shown as plain letter. My attempts are as below:
pom.xml for flying saucer:
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.1.22</version>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.12</version>
</dependency>
Controller method:
public void generateReport(Model model, HttpServletResponse response) throws IOException, DocumentException {
// Load HTML template from file
InputStream templateStream = new ClassPathResource("templates/report.html").getInputStream();
String html = new String(templateStream.readAllBytes(), StandardCharsets.UTF_8);
// Set up Thymeleaf model with dynamic data
List<Item> items = new ArrayList<>();
items.add(new Item("পণ্য ১", 10));
items.add(new Item("পণ্য ২", 20));
items.add(new Item("পণ্য ৩", 30));
ReportData data = new ReportData("আমার রিপোর্ট", items);
model.addAttribute("data", data);
// Render HTML template with Thymeleaf
String renderedHtml = new org.thymeleaf.TemplateEngine()
.process(html, new org.thymeleaf.context.Context(Locale.getDefault(), model.asMap()));
// Generate PDF using Flying Saucer
ITextRenderer renderer = new ITextRenderer();
// Add font support
String fontPath = new ClassPathResource("kalpurush.ttf").getURI().toString();
renderer.getFontResolver().addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
// Set HTML source
renderer.setDocumentFromString(renderedHtml);
// Render PDF document
renderer.layout();
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
renderer.createPDF(outputStream);
response.setContentType("application/pdf");
response.setContentLength(outputStream.size());
response.setHeader("Content-Disposition", "inline; filename=report.pdf");
response.getOutputStream().write(outputStream.toByteArray());
}
}
Html page:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>My Report</title>
<style>
body {
font-family: Kalpurush,sans-serif;
}
</style>
</head>
<body>
<h1 th:text="${data.reportTitle}"></h1>
<table>
<thead>
<tr>
<th>নাম</th>
<th>পরিমাণ</th>
</tr>
</thead>
<tbody>
<tr th:each="item : ${data.items}">
<td th:text="${item.name}"></td>
<td th:text="${item.quantity}"></td>
</tr>
</tbody>
</table>
</body>
</html>
Problem uploading image, I provided Dropbox link:
To compare the header should look like: আমার রিপোর্ট