1

For example,

{
  "appId": "wxa033f083bd79132d",
  "timestamp": 1657699905,
  "nonceStr": "SKIe2Ce352",
  "signature": "20fbc391ed6ed78a3a267c31526239110926a8d1",
  "jsApiList": [
    "updateAppMessageShareData",
    "updateTimelineShareData"
  ]
}

I want to generate pdf file with formatted json,like this:

json pdf

But I can only generate something like this:

my pdf

I've tried making it rich text and displaying it inside the pdf, but that doesn't seem to work. And my code

public void testPDF() throws IOException {

        String json = "{\"appId\":\"wxa033f083bd79132d\",\"timestamp\":1657699905,\"nonceStr\":\"SKIe2Ce352\",\"signature\":\"20fbc391ed6ed78a3a267c31526239110926a8d1\",\"jsApiList\":[\"updateAppMessageShareData\",\"updateTimelineShareData\"]}";
        JSONObject jsonObject = JSON.parseObject(json);
        PDDocument document = new PDDocument();
        PDPage pdPage = new PDPage();
        document.addPage(pdPage);
        PDPageContentStream contentStream = new PDPageContentStream(document, pdPage);

        contentStream.beginText();

        contentStream.setFont(PDType1Font.HELVETICA_BOLD, 14);

        contentStream.newLineAtOffset(25, 500);
        contentStream.setLeading(14.5f);
        contentStream.showText("{");
        contentStream.newLine();
        jsonObject.forEach((key, value) -> {
            try {
                contentStream.showText(String.format("\"%s\": %s ", key, value));
                contentStream.newLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        contentStream.showText("}");
        contentStream.newLine();

        contentStream.endText();
        contentStream.close();

        document.save(new File("D:\\new-doc-text.pdf"));

        document.close();

    }
Tilman Hausherr
  • 17,731
  • 7
  • 58
  • 97

1 Answers1

0

PdfBox is very low level Pdf library and if you want to use it to display aligned lines you will have to write whitespace offsetting logic by yourself.

If I were to do it I would use a library like Gson and pretty printing (Pretty-Print JSON in Java) to first parse it line-by-line with whitespaces at front and then print line-by-line.

Another approach is to use a higher level library such as freemarker templates and it's export to PDF. I was using PDFBox and wish I have switched to freemarker much earlier.

Piotr73
  • 84
  • 4