Section protection allows users to be able to edit only the forms (if any) rather than any other content within it. When we protect a document, we can specify that the specific sections of the document be protected. This is useful in case we want to protect parts of a Word document.
Following code snippets demonstrate the same.
Step 1: Initialize an instance of Document class.
Document doc = new Document();
Step 2: Add two sections to the document.
Section s1 = doc.AddSection(); Section s2 = doc.AddSection();
Step 3: Append some text to section 1 and section 2.
s1.AddParagraph().AppendText("section 1"); s2.AddParagraph().AppendText("section 2");
Step 4: Protect the document with AllowOnlyFormFields protection type.
doc.Protect(ProtectionType.AllowOnlyFormFields, "123");
Step 5: Unprotect section 2.
s2.ProtectForm = false;
Step 6: Save the document.
doc.SaveToFile("Protect_Section.docx");
Result:
Run the program, we should get the file in which section 1 is protected to allow only editing in form fields while section 2 can be edited freely.
Full Code:
using Spire.Doc; namespace LockSection { class Program { static void Main(string[] args) { Document doc = new Document(); Section s1 = doc.AddSection(); Section s2 = doc.AddSection(); s1.AddParagraph().AppendText("section 1"); s2.AddParagraph().AppendText("section 2"); //protect all sections doc.Protect(ProtectionType.AllowOnlyFormFields, "123"); //unprotect section 2 s2.ProtectForm = false; doc.SaveToFile("Protect_Section.docx"); } } }
Imports Spire.Doc Namespace LockSection Class Program Private Shared Sub Main(args As String()) Dim doc As New Document() Dim s1 As Section = doc.AddSection() Dim s2 As Section = doc.AddSection() s1.AddParagraph().AppendText("section 1") s2.AddParagraph().AppendText("section 2") 'protect all sections doc.Protect(ProtectionType.AllowOnlyFormFields, "123") 'unprotect section 2 s2.ProtectForm = False doc.SaveToFile("Protect_Section.docx") End Sub End Class End Namespace