Problem statement: preetify string in to json format and store in pdf file.
Earlier I am able to solve this problem by preetifying string using below code.
public Long convertJsonToPdf(Long customerId,
Object json,
String documentType) {
log.info("In convert Json To Pdf");
String fileName = documentType + ".pdf";
ObjectMapper objectMapper = new ObjectMapper();
String json1 = null;
try {
json1 = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
} catch (JsonProcessingException e) {
log.warn("Error occurred in parsing json {}", e.getMessage(), e);
}
try {
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
PdfWriter.getInstance(document, new FileOutputStream(filename));
document.open();
document.add(new Paragraph(json1));
Paragraph signature = new Paragraph("Created by me.");
signature.setAlignment(Paragraph.ALIGN_RIGHT);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(signature);
document.close();
} catch (Exception e) {
log.info("exception occurred in creating pdf {}", e.getMessage(), e);
}
// code to store in cloud.
}
Above code was able to solve my problem. Now it is not able to solve my problem i.e not able preetify the json.
I tried other solutions from this preety-print-json-in-java.
I tried using JSONObject.
JSONObject json = new JSONObject(jsonString); // Convert text to object
System.out.println(json.toString(4)); // Print it with specified indentation
or this:
json1 = objectMapper.readTree(json.toString()).toPrettyString();
When I print json1 in my console it is able to preetify it properly. but when this is stored in pdf then at a position there is a gap to 3-4 line between two field. This error occur for a specific file. In other file it is able to print correctly in pdf.
json in pdf file:
"city": "city name",
"state": "state name"