如何使用Apache POI XWPF设置文本底层的首页背景图片
解决Apache POI 5.2.5给DOCX首页添加居中底层背景图的方案
核心思路
通过给首页单独分节,添加浮动型图片并设置其层级为文字下方,同时调整水平、垂直居中参数,实现首页专属背景图效果。
具体实现代码
import org.apache.poi.xwpf.usermodel.*; import org.openxmlformats.schemas.wordprocessingml.x2006.main.*; import java.io.*; import java.math.BigInteger; public class DocxBackgroundUtil { public static void addFirstPageBackground(XWPFDocument doc, String imagePath) throws Exception { // 1. 确保首页为单独一节(若模板未分节) XWPFParagraph firstPara = doc.getParagraphs().get(0); if (firstPara.getCTP().getPPr() == null) { firstPara.getCTP().addNewPPr(); } CTSectPr sectPr = firstPara.getCTP().getPPr().addNewSectPr(); sectPr.addNewType().setVal(STSectionMark.NEXT_PAGE); // 2. 读取目标图片 File imageFile = new File(imagePath); FileInputStream fis = new FileInputStream(imageFile); String imageType = imagePath.substring(imagePath.lastIndexOf(".") + 1).toLowerCase(); // 按需求调整图片尺寸(1px ≈ 9525 EMU) int imageWidth = Units.toEMU(600); int imageHeight = Units.toEMU(800); // 3. 在首页段落插入图片 XWPFRun run = firstPara.createRun(); doc.addPictureData(fis, getPictureType(imageType)); run.addPicture(new FileInputStream(imageFile), getPictureType(imageType), imageFile.getName(), imageWidth, imageHeight); // 4. 将图片转为浮动型,置于文字底层 CTInline inline = run.getCTR().getDrawingArray(0).getInlineArray(0); CTAnchor anchor = inline.addNewAnchor(); anchor.setDistT(BigInteger.ZERO); anchor.setDistB(BigInteger.ZERO); anchor.setDistL(BigInteger.ZERO); anchor.setDistR(BigInteger.ZERO); anchor.setLocked(STOnOff.OFF); anchor.setRelativeHeight(BigInteger.valueOf(251658240)); anchor.setBehindDoc(STOnOff.ON); // 关键:置于文字下方 anchor.setAllowOverlap(STOnOff.ON); // 5. 设置水平+垂直居中 CTPositionH posH = anchor.addNewPositionH(); posH.setRelativeFrom(STPositionHRelativeFrom.PAGE); posH.setAlign(STHorizontalAlignment.CENTER); CTPositionV posV = anchor.addNewPositionV(); posV.setRelativeFrom(STPositionVRelativeFrom.PAGE); posV.setAlign(STVerticalAlignment.CENTER); // 移除原行内元素,保留浮动锚点 run.getCTR().getDrawingArray(0).removeInline(0); } // 辅助方法:匹配图片类型 private static int getPictureType(String imageType) { return switch (imageType) { case "jpg", "jpeg" -> XWPFDocument.PICTURE_TYPE_JPEG; case "png" -> XWPFDocument.PICTURE_TYPE_PNG; case "gif" -> XWPFDocument.PICTURE_TYPE_GIF; default -> XWPFDocument.PICTURE_TYPE_JPEG; }; } }
使用说明
- 直接传入已加载的
XWPFDocument对象和背景图路径即可调用 - 图片尺寸可通过
Units.toEMU()调整,按需适配页面大小 - 若模板已给首页单独分节,可跳过步骤1的分节设置
- 该方案仅对第一节(首页)生效,后续页面不受影响
旧方案失效原因
你提到的旧方案仅将图片插入到段落末尾,未设置浮动定位和层级属性,因此只能显示在文档底部。本方案通过CTAnchor将图片转为页面绑定的浮动元素,同时通过BehindDoc参数设置层级,再配合坐标系定位实现严格居中。
内容的提问来源于stack exchange,提问作者br00kx
相关产品推荐
相关产品推荐

