java poi 水印_Java 使用POI 给Word添加水印

这个Java代码示例展示了如何使用Apache POI库在Word文档中创建和设置水印,包括设置填充颜色和旋转角度。程序创建了一个带有默认水印的Word文档,并保存为'CreateWordHeaderFooterWatermark.docx'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.daydayup.study001.watermark;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import org.apache.poi.xwpf.usermodel.XWPFHeader;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import org.apache.poi.xwpf.usermodel.XWPFRun;

public class WatermarkForWord {

public static void main(String[] args) throws FileNotFoundException, IOException {

XWPFDocument doc= new XWPFDocument();

// the body content

XWPFParagraph paragraph = doc.createParagraph();

XWPFRun run=paragraph.createRun();

run.setText("The Body:");

// create header-footer

XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();

if (headerFooterPolicy == null) headerFooterPolicy = doc.createHeaderFooterPolicy();

// create default Watermark - fill color black and not rotated

headerFooterPolicy.createWatermark("Watermark");

// get the default header

// Note: createWatermark also sets FIRST and EVEN headers

// but this code does not updating those other headers

XWPFHeader header = headerFooterPolicy.getHeader(XWPFHeaderFooterPolicy.DEFAULT);

paragraph = header.getParagraphArray(0);

// get com.microsoft.schemas.vml.CTShape where fill color and rotation is set

org.apache.xmlbeans.XmlObject[] xmlobjects = paragraph.getCTP().getRArray(0).getPictArray(0).selectChildren(

new javax.xml.namespace.QName("urn:schemas-microsoft-com:vml", "shape"));

if (xmlobjects.length > 0) {

com.microsoft.schemas.vml.CTShape ctshape = (com.microsoft.schemas.vml.CTShape)xmlobjects[0];

// set fill color

ctshape.setFillcolor("#d8d8d8");

// set rotation

ctshape.setStyle(ctshape.getStyle() + ";rotation:315");

//System.out.println(ctshape);

}

doc.write(new FileOutputStream("CreateWordHeaderFooterWatermark.docx"));

doc.close();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值