The online document's safety becomes more and more important in our daily life. This article is aimed to show you how to protect the Word document in Java application using Free Spire.Doc for Java library from the following three parts:
Encrypt Word Document
Set editing restrictions for word document
Decrypt Document
Encrypt Word Document. We could use the method document.encrypt(string) to set the password for the Word document.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class EncryptWord {
public static void main(String[] args) {
//create a Document object
Document document = new Document();
//load a Word document
document.loadFromFile("Sample.docx");
//encrypt the document with a password
document.encrypt("abc-123");
//save as docx file
document.saveToFile("output/Encrypt.docx", FileFormat.Docx);
}
}
Set editing restrictions for word document. We need to use the document.protect() method to set the word document read only, only allow comments, track changes, etc.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.ProtectionType;
public class RestrictEditing {
public static void main(String[] args){
//Create a Document instance
Document document = new Document();
//Load the Word document
document.loadFromFile("Sample.docx");
//No changes (Read only)
document.protect(ProtectionType.Allow_Only_Reading, "123456");
//Allow only comments
//document.protect(ProtectionType.Allow_Only_Comments, "123456");
//Allow only filling in forms
//document.protect(ProtectionType.Allow_Only_Form_Fields, "123456");
//Allow only tracked changes
//document.protect(ProtectionType.Allow_Only_Revisions, "123456");
//Save the result document
document.saveToFile("RestrictEditing.docx", FileFormat.Docx_2013);
}
}
Decrypt Document: We could also decrypt the Word document with password to remove the protection for the word document.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class DecryptWord {
public static void main(String[] args) {
//create a Document object
Document document = new Document();
//remove encryption while loading the password protected document
document.loadFromFile("Encrypt.docx", FileFormat.Docx, "abc-123");
//save as docx file.
document.saveToFile("output/Decrypt2.docx", FileFormat.Docx);
}
}
Top comments (0)