I want to show a text in Word inside a box using Apache POI XWPF like this:
This example was done in Word using a shape with a text inside the shape.
But I am not able to do this correctly in Word using XWPF. When I try:
public void createDocument() throws IOException {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("The text");
CTGroup ctGroup = CTGroup.Factory.newInstance();
CTShape ctShape = ctGroup.addNewShape();
ctShape.setStyle("width:100pt;height:50pt");
ctShape.setFillcolor("FF0000");
Node ctGroupNode = ctGroup.getDomNode();
try {
CTPicture ctPicture = CTPicture.Factory.parse(ctGroupNode);
CTR cTR = run.getCTR();
cTR.addNewPict();
cTR.setPictArray(0, ctPicture);
} catch (XmlException ex) {
}
try ( OutputStream stream = new BufferedOutputStream(new FileOutputStream(file))) {
doc.write(stream);
}
doc.close();
}
I have a Shape, but the text is not inside the Shape, and the Shape is not filled.
I used this example: create text box in document .docx using apache poi
My examples in create text box in document .docx using apache poi uses Microsoft's VML Object Model.
The last example also works using current Apache POI 5.2.4.
The text in the text-box must be within a text box content. This code line set it:
But if fill a color shall be used, the surrounding shape would must have a closed line around. Either one would set a Path to describe the shape outlines. Or - easier - one would use a rectangle shape instead of a simple shape. Rectangle shape in Apache POI for Word is a
com.microsoft.schemas.vml.CTRect
insteadcom.microsoft.schemas.vml.CTShape
.Following works for me:
Produces: