ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java使用poi实现Word添加水印(仅支持后缀为.docx格式)

2022-01-12 18:04:46  阅读:268  来源: 互联网

标签:docx Word ctshape doc 水印 headerFooterPolicy poi new


最近要做电子合同,客户提出为了安全性要将合同中都添加水印,这个之前在网上看到过,貌似使用POI很好加。去网上一搜发现,清一色的只有一篇文章,并且这段代码是用不了的;在文章下边的评论里也发现都说用不了,不能用。唉,木办法了,只能自己探索。

1、pom依赖:

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

废话不多说,上demo;

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

3、总结

虽然实现了,但是还是比较简陋;水印的字体、大小、颜色等都木有设置,用的都是默认的;这是以后可以优化的地方。不过整体效果还是可以的,而且这样添加水印后生成pdf也是带有水印的。至于生成pdf的代码后边有时间再写吧,谁想要可以在评论区给我留言,我看到了就把demo发给你。





标签:docx,Word,ctshape,doc,水印,headerFooterPolicy,poi,new
来源: https://www.cnblogs.com/shift25/p/15793673.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有