When working with Word documents using the OpenXML SDK, it’s not obvious how to remove document protection. The following code shows you how:
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open("[path to Word document]", true)) { DocumentFormat.OpenXml.OpenXmlElement protectedDocElement = wordDocument.MainDocumentPart.DocumentSettingsPart.ChildElements.FirstOrDefault(el => el.XmlQualifiedName.Name.Equals("documentProtection")); if (protectedDocElement != null) { protectedDocElement.Remove(); } wordDocument.MainDocumentPart.Document.Save(); } |
Following on from that, it’s also straight forward enough to remove macros from a document (or template):
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open("[path to Word document]", true)) { VbaProjectPart vbaProjectPart = wordDocument.MainDocumentPart.VbaProjectPart; if (vbaProjectPart != null) { wordDocument.MainDocumentPart.DeletePart(vbaProjectPart); } wordDocument.MainDocumentPart.Document.Save(); } |
and finally, how to open a Word document stored in a SharePoint library and persist any changes made:
using (MemoryStream memoryStream = new MemoryStream()) { byte[] fileBinary = spFile.OpenBinary(); memoryStream.Write(fileBinary, 0, fileBinary.Length); using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(memStream, true)) { // ... wordDocument.MainDocumentPart.Document.Save(); } // Save changes back to document spFile.SaveBinary(memoryStream); } |