常用的对Word文档进行保护的方法有加密文档或者限制编辑。加密的文档需要密码才能被打开,限制编辑的文档打开时无需密码,但编辑权限受到限制,例如:不允许任何更改(只读),只允许填写窗体,只允许批注,只允许修订。本文将介绍使用Spire.Doc实现不同的保护类和移除密码保护。
用密码进行加密
C#
//初始化一个Document实例并添加section
Document doc = new Document();
doc.AddSection();
//设置密码
doc.Encrypt("abc-123");
//保存文档
doc.SaveToFile("设置密码.docx", FileFormat.Docx2013);
VB.NET
'初始化一个Document实例并添加section Dim doc As Document = New Document doc.AddSection '设置密码
doc.Encrypt("abc-123")
'保存文档 doc.SaveToFile("设置密码.docx",FileFormat.Docx2013)
限制编辑
当新建一个文档或者加载一个现有的Word文档到Document对象后,我们可以调用Protect(ProtectionType type,string password)方法对文档进行选择性的保护。
C#
//不允许任何更改(只读),设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyReading,"123");//只允许填写窗体,设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyFormFields,"123");//只允许批注,设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyComments,"123");//只允许修订,设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyRevisions,"123");
VB.NET
'不允许任何更改(只读),设置解除限制编辑的密码
doc.Protect(ProtectionType.AllowOnlyReading, "123")
'只允许填写窗体,设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyFormFields,"123") '只允许批注,设置解除限制编辑的密码
doc.Protect(ProtectionType.AllowOnlyComments, "123")
'只允许修订,设置解除限制编辑的密码 doc.Protect(ProtectionType.AllowOnlyRevisions,"123")
效果示例:限制编辑,只读
解除密码保护
C#
//初始化一个Document实例 Document doc = new Document();//加载已加密文档,参数"adc-123"为文档密码 doc.LoadFromFile("加密文档.docx",FileFormat.Docx2013,"abc-123");//解除密码保护 doc.RemoveEncryption();//保存文档 doc.SaveToFile("解除密码.docx",FileFormat.Docx2013);
VB.NET
'初始化一个Document实例
Dim doc As Document = New Document
'加载已加密文档,参数"adc-123"为文档密码 doc.LoadFromFile("加密文档.docx",FileFormat.Docx2013,"abc-123") '解除密码保护
doc.RemoveEncryption
'保存文档 doc.SaveToFile("解除密码.docx",FileFormat.Docx2013)