I use the Java Spring Boot framework and I need to convert my Json to PDF. The problem is that all text in the PDF is written in one line, which means that line breaks do not work. As a result, I get a PDF in which the first line is blank or an empty file.
@GetMapping("/pdf/{Id}")
@Secured({"ROLE_ADMIN", "ROLE_OPERATOR", "ROLE_GUEST"})
public ResponseEntity<PDDocument> findOnePdfByIdJob(@PathVariable("Id") Long id) throws DocumentException, IOException {
Job job = jobService.findById(id);
if (job == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
ObjectMapper objectMapper = new ObjectMapper();
String jsonInString = objectMapper.writeValueAsString(job);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonInString);
String prettyJsonString = gson.toJson(je);
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.setFont(PDType1Font.COURIER, 12);
contentStream.beginText();
contentStream.showText(jsonInString);
contentStream.endText();
contentStream.close();
document.save("pdfBoxHelloWorld.pdf");
document.close();
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(document);
}
As a result, I get a PDF in which everything is written in one line. That is, the text cannot be read .... The first line becomes just a blank line.