使用Apache POI生成docx时如何实现图片右侧文字居中对齐效果
Apache POI 生成docx实现图片右侧垂直居中文字的方案
推荐方案:无边框表格实现(兼容性最高,效果最稳定)
你之前尝试的表格方案完全可行,仅需补充隐藏所有表格边框的配置即可,不会留下任何表格痕迹,完美匹配需求。
实现逻辑
- 创建1行2列的表格,宽度匹配页眉/页面的可用宽度
- 左单元格插入目标图片,右单元格插入展示文字
- 右单元格设置垂直居中对齐,单元格内段落按需设置水平对齐方式
- 隐藏表格所有内外边框,消除表格痕迹
完整示例代码
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.*; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STHdrFtr; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DocxImageTextTest { public static void main(String[] args) { XWPFDocument doc = new XWPFDocument(); XWPFHeader header = doc.createHeader(STHdrFtr.DEFAULT); // 创建1行2列的表格 XWPFTable table = header.createTable(1, 2); // 设置表格宽度为100% table.setWidth("100%"); // 隐藏所有表格边框 table.setTopBorder(XWPFTable.XWPFBorderType.NONE, 0, 0, null); table.setBottomBorder(XWPFTable.XWPFBorderType.NONE, 0, 0, null); table.setLeftBorder(XWPFTable.XWPFBorderType.NONE, 0, 0, null); table.setRightBorder(XWPFTable.XWPFBorderType.NONE, 0, 0, null); table.setInsideHBorder(XWPFTable.XWPFBorderType.NONE, 0, 0, null); table.setInsideVBorder(XWPFTable.XWPFBorderType.NONE, 0, 0, null); // 第一个单元格插入图片 XWPFTableCell imgCell = table.getRow(0).getCell(0); XWPFParagraph imgPara = imgCell.getParagraphs().get(0); XWPFRun pictureRun = imgPara.createRun(); String imgFile = "D:\\picture.jpg"; try (FileInputStream is = new FileInputStream(imgFile)) { pictureRun.addPicture(is, Document.PICTURE_TYPE_PNG, imgFile, Units.pixelToEMU(297), Units.pixelToEMU(124)); } catch (IOException | InvalidFormatException e) { e.printStackTrace(); } // 第二个单元格插入文字,设置居中对齐 XWPFTableCell textCell = table.getRow(0).getCell(1); // 垂直居中 textCell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); XWPFParagraph textPara = textCell.getParagraphs().get(0); // 水平居中,如需左对齐改为ParagraphAlignment.LEFT即可 textPara.setAlignment(ParagraphAlignment.CENTER); XWPFRun headerTextRun = textPara.createRun(); headerTextRun.setText("Some text"); // 导出文件 try (FileOutputStream out = new FileOutputStream("D:\\test.docx")) { doc.write(out); } catch (IOException e) { e.printStackTrace(); } } }
其他方案说明
如果不想使用表格,也可以将图片设置为左环绕浮动格式,给文字段落设置等于图片宽度的左侧缩进,再调整段落对齐即可,不过这种方案在不同版本的Office中打开可能出现排版偏移,稳定性不如无边框表格方案。
你之前尝试的其他方案无法达成效果的原因:
- 同段落多Run:图片会被识别为行内字符,默认和文字基线对齐,无法实现整块垂直居中,调整行高也很难适配不同尺寸的图片
- 独立段落:默认是块级元素会自动换行,无法和图片并排展示
- 局部双栏:Apache POI 没有提供针对单个段落的双栏配置,双栏是页面级别的设置,不适用这种局部排版的场景
内容的提问来源于stack exchange,提问作者Ethelea01
相关产品推荐
相关产品推荐

