【Java】通过poi给word首页添加水印图片

背景:

poi并没有提供直接插入水印图片的方法,目前需要再word的首页插入一张水印图片,于是就需要通过另一种方式,插入透明图片(png格式)并将图片设置为“浮于文字上方”的方式实现该需求。

所需jar:

poi-3.8.jar
poi-ooxml-3.8.jar
poi-ooxml-schemas-3.8.jar
xmlbeans-2.6.0.jar
dom4j-1.6.1.jar

示例代码:

创建CustomXWPFDocument类

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.*;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;

import java.io.IOException;
import java.io.InputStream;

/**
 * 文档对象
 */
public class CustomXWPFDocument extends XWPFDocument {
	
	public CustomXWPFDocument() {
		super();
	}

	public CustomXWPFDocument(InputStream in) throws IOException {
		super(in);
	}

	public CustomXWPFDocument(OPCPackage pkg) throws IOException {
		super(pkg);
	}

	/**
	 * 创建一个包含图片的XWPFParagraph,将图片插入到指定或新建的段落中。
	 *
	 * @param blipId 图片在文档关系中的唯一标识(r:embed属性值),用于链接到图片数据。
	 * @param id     图片在文档中的唯一标识(cNvPr元素的id属性值)。
	 * @param width  图片的宽度,单位为像素。内部转换为EMU(English Metric Unit)单位。
	 * @param height 图片的高度,单位为像素。内部转换为EMU单位。
	 * @param paragraph 可选参数,要插入图片的XWPFParagraph。如果为null,则会创建一个新的段落。
	 */
	public void createPicture(String blipId, int id, int width, int height,
									 XWPFParagraph paragraph) {
		// 定义EMU(English Metric Unit)常量,1EMU等于1/914400米,是OpenXML中使用的长度单位。
		final int EMU = 9525;

		// 将像素宽度和高度转换为EMU单位。
		width *= EMU;
		height *= EMU;

		// 如果传入的段落为空,则创建一个新的段落。
		if (paragraph == null) {
			paragraph = createParagraph();
		}

		// 在段落中创建一个新的运行(Run),并在运行的底层XML结构(CTR)中添加一个新的内联图形(Inline)元素。
		CTInline inline = paragraph.createRun().getCTR().addNewDrawing()
				.addNewInline();

		// 构建包含图片详细信息的XML字符串,遵循OpenXML DrawingML规范。
	
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值