You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Apache POI(docx)中居中定位图片?

如何在Apache POI中实现DOCX图片居中定位?

我现有一段用于处理DOCX图片的代码(来自Stack Overflow的《Wrap Text in Apache POI(docx)?》问题解答),目前无法正确定位图片,想实现图片居中:

CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
long width = drawing.getInlineArray(0).getExtent().getCx();
long height = drawing.getInlineArray(0).getExtent().getCy();
    String anchorXML = "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
        +"simplePos=\"0\" relativeHeight=\"0\" behindDoc=\""+((behind)?1:0)+"\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
        +"<wp:simplePos x=\"0\" y=\"0\"/>"
        +"<wp:positionH relativeFrom=\"column\"><wp:posOffset>0</wp:posOffset></wp:positionH>"
        +"<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>0</wp:posOffset></wp:positionV>"
        +"<wp:extent cx=\""+width+"\" cy=\""+height+"\"/>"
        +"<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/><wp:wrapNone/>"
        +"<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\""+drawingDescr+"\"/><wp:cNvGraphicFramePr/>"
        +"</wp:anchor>";

drawing = CTDrawing.Factory.parse(anchorXML);
CTAnchor anchor = drawing.getAnchorArray(0);
anchor.setGraphic(graphicalobject);
return anchor;  

实现图片水平居中的修改方案

要让图片水平居中,核心是修改锚点XML中的<wp:positionH>节点,用对齐属性替代固定偏移值:

修改后的完整代码

CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
long width = drawing.getInlineArray(0).getExtent().getCx();
long height = drawing.getInlineArray(0).getExtent().getCy();
String anchorXML = "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
    +"simplePos=\"0\" relativeHeight=\"0\" behindDoc=\""+((behind)?1:0)+"\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
    +"<wp:simplePos x=\"0\" y=\"0\"/>"
    +"<wp:positionH relativeFrom=\"column\">"
    +"    <wp:align>center</wp:align>"
    +"</wp:positionH>"
    +"<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>0</wp:posOffset></wp:positionV>"
    +"<wp:extent cx=\""+width+"\" cy=\""+height+"\"/>"
    +"<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/><wp:wrapNone/>"
    +"<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\""+drawingDescr+"\"/><wp:cNvGraphicFramePr/>"
    +"</wp:anchor>";

drawing = CTDrawing.Factory.parse(anchorXML);
CTAnchor anchor = drawing.getAnchorArray(0);
anchor.setGraphic(graphicalobject);
return anchor;  

关键修改说明

  • 原代码中<wp:positionH>用固定偏移posOffset="0"定位,改为使用<wp:align>center</wp:align>,让Word自动将图片相对于所在列(relativeFrom="column")水平居中。
  • 如果需要同时实现垂直居中,可对<wp:positionV>做类似修改,将<wp:posOffset>0</wp:posOffset>替换为<wp:align>center</wp:align>,参照对象保持relativeFrom="paragraph"即可。

内容的提问来源于stack exchange,提问作者Sr. Robô

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 07:54:51