栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java使用poi给Word加水印(目前自己了解的仅支持后缀为.docx格式的,.doc仍在研究)开源、免费。

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java使用poi给Word加水印(目前自己了解的仅支持后缀为.docx格式的,.doc仍在研究)开源、免费。

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

1、pom依赖:


    
        org.apache.poi
        poi-ooxml
        4.1.2
    

 

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();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/704638.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号