0

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
RagaSGNur
  • 199
  • 1
  • 2
  • 15

1 Answers1

0

I have an answer for the question.

We can do the sanitization for the text which has special characters and want to appear as such in PDF file

private String sanitizeHtmlString(String text) {
 return nonNull(label) ? HtmlUtils.htmlEscape(label) : null;
}

HtmlUtils is available in spring-web-5.3.18.jar.

RagaSGNur
  • 199
  • 1
  • 2
  • 15