Java使用poi實現Word添加水印(僅支持后綴為.docx格式)


最近要做電子合同,客戶提出為了安全性要將合同中都添加水印,這個之前在網上看到過,貌似使用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發給你。






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM