废话不多说,直接上代码!

1、pom依赖:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.1.2</version>
    </dependency>
</dependencies>

 

2、代码:
import java.io.*;

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

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

public class Test1 {

    public static void main(String[] args) throws Exception {

        //输入的docx文档
        InputStream in = new FileInputStream(new File("D:/aa.docx"));
        XWPFDocument doc= new XWPFDocument(in);

        // 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();

        // 水印内容
        headerFooterPolicy.createWatermark("WaterMaker");

        // 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);
        }
        //文件输出地址
        FileOutputStream out = new FileOutputStream("D:\\watermark.docx");
        System.out.println("水印添加成功!");
        doc.write(out);
        out.close();
        doc.close();
    }
}
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐