All , I am using Thymleaf , ITextRenderer , Spring Boot to try to generate the PDF file.
Input : JSON file
Java Code: Reads the JSON file , process it to retrieve the information and save it in JavaObjects. The information will be displayed in the PDF.
final TemplateEngine templateEngine;
private final ObjectMapper objectMapper;
//reportAsBytes will be sent to HTML file
byte[] reportAsBytes = generateReport(
TEST_TEMPLATE,
objectMapperWithNullValues.valueToTree(dataForReport)
);
public byte[] generateReport(String templateId, JsonNode data) {
Map<String, Object> dataAsMap = convertDataToMap(data);
String reportAsHtml = generateReportAsHtml(templateId, dataAsMap, 'en');
return generatePdfReportAsBytes(reportAsHtml);
}
private Map<String, Object> convertDataToMap(JsonNode data) {
return objectMapper.convertValue(data, new TypeReference<Map<String,Object>>() {});
}
private String generateReportAsHtml(String templateId, Map<String, Object> jsonData, Locale reportLocale) {
Context context = new Context();
context.setVariable("data", jsonData);
context.setLocale(reportLocale);
return templateEngine.process(templateId, context);
}
private byte[] generatePdfReportAsBytes(String reportAsHtml) {
ITextRenderer renderer = createRenderer();
renderer.setDocumentFromString(reportAsHtml);
renderer.layout();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
renderer.createPDF(outputStream);
return outputStream.toByteArray();
}
Thymleaf: HTML template having place holders ${"data".javaobject} to get the data from Java to populate the PDF file.
The PDF report is generated correctly . But , when the string value for any of the javaObject with special characters like '>', '<' , '&' stops the report generation.
Is there anyone to guide here?