How to draw a rectangle in Word with Apache poi and fill it with colors?

310 Views Asked by At

I need to create a Word document with the help of Apache poi and need to create a red bar at the top. I did not find any shape module or function in apache poi to draw a rectangle. I read somewhere that the shapes in the Word with the help of the Apche poi can be inserted with the help of the Vector markup language. How should I approach the problem?

I tried implementing few shapes in the following but I was not successful in doing the same as it is throwing error-

Exception in thread "main" org.apache.xmlbeans.XmlException: error: The prefix "w" for element "w:shape" is not bound.

String cTAbstractNumBulletXML =
    "<v:shape type=\"#downArrow\" style='position: absolute; left: 77; top: 16; width: 64; height: 128'/>";

CTNumbering cTNumbering = CTNumbering.Factory.parse(cTAbstractNumBulletXML);

CTAbstractNum cTAbstractNum = cTNumbering.getAbstractNumArray(0);

XWPFAbstractNum abstractNum = new XWPFAbstractNum(cTAbstractNum);
XWPFNumbering numbering = document.createNumbering();
BigInteger abstractNumID = numbering.addAbstractNum(abstractNum);
BigInteger numID = numbering.addNum(abstractNumID);

//Create a blank paragraph
XWPFParagraph paragraph = document.createParagraph();
paragraph.setNumID(numID);

FileOutputStream fileOutputStream = new FileOutputStream("C:\\xx\\xxx"
                                                         + "xxxx.docs");
document.write(fileOutputStream);
fileOutputStream.close();

I tried to draw shapes with the help of the VML. However, it is throwing error because it is not able to recognise the tags like v and w.

1

There are 1 best solutions below

0
MomoTheDev On

You can use the Java AWT Graphics library to create the rectangle, then you can save the image to a temporary Bitmap or JPEG file.

You can insert the image into a Word-Document using this code:

private void insertImage(final XWPFDocument document, final File image, final int width, final int height) {
    final FileInputStream fileInputStream = new FileInputStream(image);
    run.addBreak();
    run.addPicture(fileInputStream, XWPFDocument.PICTURE_TYPE_JPEG, image, Units.toEMU(width), Units.toEMU(height));
    fileInputStream.close();
}