【发布时间】:2019-08-14 08:35:44
【问题描述】:
我使用 Java Spring Boot 框架,我需要将我的 Json 转换为 PDF。问题是 PDF 中的所有文本都写在一行中,这意味着换行符不起作用。结果,我得到一个 PDF,其中第一行是空白或空文件。
@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);
}
因此,我得到了一个 PDF,其中所有内容都写在一行中。也就是无法读取文本....第一行变成了空行。
【问题讨论】:
标签: java json spring spring-boot pdf