對一些重要文檔,咱們爲保證其文檔內容不被泄露,常須要對文件進行加密,查看文件時,須要正確輸入密碼才能打開文件。下面介紹了一種比較簡單的方法給Word文件添加密碼保護以及如何給已加密的Word文件取消密碼保護。html
使用工具:Free Spire.Doc for Java(免費版)java
Jar文件導入:maven
方法1:經過官網下載。下載後,解壓文件,並將lib文件夾下的Spire.Doc.jar文件導入到java程序。參考以下導入效果:工具
import com.spire.doc.*; public class Encrypt { public static void main(String[] args){ //加載測試文檔 String input = "test.docx"; String output= "result.docx"; Document doc = new Document(input); doc.encrypt("123");//設置文檔打開密碼 //doc.protect(ProtectionType.Allow_Only_Reading,"123");//設置文檔只讀 //doc.protect(ProtectionType.Allow_Only_Comments,"123"); //doc.protect(ProtectionType.Allow_Only_Revisions,"123"); //保存加密後的文檔 doc.saveToFile(output); doc.dispose(); } }
文件加密結果:加密
import com.spire.doc.*; public class Decrypt { public static void main(String[] args){ //加載帶密碼的文件,輸入原密碼並解除 Document doc = new Document(); doc.loadFromFile("result.docx",FileFormat.Docx_2013,"123"); //將解密後的文檔另存 doc.saveToFile("Decrypt.docx",FileFormat.Docx_2013); } }
運行程序後,生成的文件將再也不有密碼保護。spa
(本文完)3d