I try to generate a simple text like this by Java into docx document
This is **bold** test
I search the online this part of the code will be the close one, however it bolds the whole line, not a specific word
ObjectFactory factory = Context.getWmlObjectFactory();
P p = factory.createP();
R r = factory.createR();
Text text = factory.createText();
RPr rpr = factory.createRPr();
text.setValue("This is bold test");
BooleanDefaultTrue boldTrue = new BooleanDefaultTrue();
boldTrue.setVal(Boolean.TRUE);
rpr.setB(boldTrue);
r.getContent().add(text);
p.getContent().add(r);
r.setRPr(this.rpr);
mainDocumentPart.getContent().add(p);
This will bold all the paragraph, however I just want that word "bold" into bold, and keep remain unbold.
How can I fix this?
You can use the docx4j webapp or Word Helper AddIn to generate the code you need from a suitable sample Word docx.
In this case:
// Create object for p
P p = wmlObjectFactory.createP();
// Create object for r
R r = wmlObjectFactory.createR();
p.getContent().add( r);
// Create object for t (wrapped in JAXBElement)
Text text = wmlObjectFactory.createText();
JAXBElement<org.docx4j.wml.Text> textWrapped = wmlObjectFactory.createRT(text);
r.getContent().add( textWrapped);
text.setValue( "This is ");
text.setSpace( "preserve");
// Create object for r
R r2 = wmlObjectFactory.createR();
p.getContent().add( r2);
// Create object for rPr
RPr rpr = wmlObjectFactory.createRPr();
r2.setRPr(rpr);
// Create object for b
BooleanDefaultTrue booleandefaulttrue = wmlObjectFactory.createBooleanDefaultTrue();
rpr.setB(booleandefaulttrue);
// Create object for bCs
BooleanDefaultTrue booleandefaulttrue2 = wmlObjectFactory.createBooleanDefaultTrue();
rpr.setBCs(booleandefaulttrue2);
// Create object for t (wrapped in JAXBElement)
Text text2 = wmlObjectFactory.createText();
JAXBElement<org.docx4j.wml.Text> textWrapped2 = wmlObjectFactory.createRT(text2);
r2.getContent().add( textWrapped2);
text2.setValue( "bold");
// Create object for r
R r3 = wmlObjectFactory.createR();
p.getContent().add( r3);
// Create object for t (wrapped in JAXBElement)
Text text3 = wmlObjectFactory.createText();
JAXBElement<org.docx4j.wml.Text> textWrapped3 = wmlObjectFactory.createRT(text3);
r3.getContent().add( textWrapped3);
text3.setValue( " test");
text3.setSpace( "preserve");
Then your mainDocumentPart.getContent().add(p);