【问题标题】:How to draw a rectangle in Word with Apache poi and fill it with colors?如何使用 Apache poi 在 Word 中绘制一个矩形并用颜色填充它?
【发布时间】:2022-11-13 20:21:58
【问题描述】:

我需要在 Apache poi 的帮助下创建一个 Word 文档,并且需要在顶部创建一个红色条。我没有在 apache poi 中找到任何形状模块或函数来绘制矩形。我在某处读到,借助 Apche poi 可以在 Vector 标记语言的帮助下插入 Word 中的形状。我应该如何处理这个问题?

我尝试在下面实现一些形状,但我没有成功地做同样的事情,因为它抛出了错误 -

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();

我尝试在 VML 的帮助下绘制形状。但是,它会抛出错误,因为它无法识别 v 和 w 之类的标签。

【问题讨论】:

    标签: java xml apache-poi vml


    【解决方案1】:

    您可以使用Java AWT Graphics 库创建矩形,然后可以将图像保存到临时BitmapJPEG 文件。

    您可以使用以下代码将图像插入 Word 文档:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 2019-01-31
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多