How to print pretty JSON using docx4j into a word document?

676 Views Asked by At

I want to print a simple pretty json string (containing multiple line breaks - many \n) into a word document. I tried the following but docx4j just prints all the contents inline in one single line (without \n). Ideally it should print multiline pretty json as it is recognising the "\n" the json string contains :

1)

  wordMLPackage.getMainDocumentPart().addParagraphOfText({multiline pretty json String})

2)

  ObjectFactory factory = Context.getWmlObjectFactory();
  P p = factory.createP();
  Text t = factory.createText();
  t.setValue(text);
  R run = factory.createR();
  run.getContent().add(t);
  p.getContent().add(run);
  PPr ppr = factory.createPPr();
  p.setPPr(ppr);
  ParaRPr paraRpr = factory.createParaRPr();
  ppr.setRPr(paraRpr);
  wordMLPackage.getMainDocumentPart().addObject(p);

Looking for help. Thanks.

1

There are 1 best solutions below

1
On BEST ANSWER

The docx file format doesn't treat \n as a newline.

So you'll need to split your string on \n, and either create a new P, or use w:br, like so:

Br br = wmlObjectFactory.createBr(); 
run.getContent().add( br);