一、方式一
1.引入pom
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
2.示例
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("C:\\Users\\Mac\\Downloads\\QQQ.docx");
XWPFDocument doc = new XWPFDocument(is);
//设置编辑限制的类型及文档保护密码
doc.enforceFillingFormsProtection("123", HashAlgorithm.sha512);
OutputStream os=new FileOutputStream("C:\\Users\\Mac\\Downloads\\QQ.docx");
doc.write(os);
}
二、方式二
1.引入pom
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.doc</artifactId>
<version>5.4.2</version>
</dependency>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
2.示例
public static void main(String[] args) throws Exception {
Document document = new Document();
document.loadFromFile("C:\\Users\\Mac\\Downloads\\QQQ.docx");
//不允许任何更改(只读)
document.protect(ProtectionType.Allow_Only_Reading, "123456");
//仅允许批注
//document.protect(ProtectionType.Allow_Only_Comments, "123456");
//仅允许填写窗体
//document.protect(ProtectionType.Allow_Only_Form_Fields, "123456");
//仅允许修订
//document.protect(ProtectionType.Allow_Only_Revisions, "123456");
//保存文档
document.saveToFile("C:\\Users\\Mac\\Downloads\\Q.docx", FileFormat.Docx_2013);
InputStream is = new FileInputStream("C:\\Users\\Mac\\Downloads\\Q.docx");
XWPFDocument doc = new XWPFDocument(is);
//以上Spire.Doc 生成的文件会自带警告信息,这里来删除Spire.Doc 的警告
doc.removeBodyElement(0);
//输出word内容文件流,新输出路径位置
OutputStream os=new FileOutputStream("C:\\Users\\Mac\\Downloads\\QQ.docx");
doc.write(os);
}
参考文档:
https://www.e-iceblue.cn/docforjavasecurity/set-editing-restrictions-in-word-in-java.html