Search code examples
c#ms-wordopenxml-sdk

How do I lock all fields (CTRL-A, CTRL-F11) on a word doc using Open XML SDK in C#


I have a word document that contains macros that is downloaded form a third party. After the document is saved and opened it looks great, but when I go to print it, it loses the data that was applied with the macro and shows "Error! Reference source not found!". I found that if I press CTRL-A and CTRL-F11, it will lock all the fields. After that I go to print and my data is there. I would like to use Open XML SDK utility to load up this document and apply this locking to the word document before it's saved. Is this possible? I have document loading up, but I just can't seem to find how to set the fields to locked.


Solution

  • There's no way to lock the fields for the entire document - each field needs to be locked individually when working with the Word Open XML. It requires the FieldLock property of the FieldChar object.

    This corresponds to the xml

    <w:r>
      <w:fldChar w:fldCharType="start" w:fldLock="true"/>
    </w:r>
    

    The following snippet locks all the field codes in the document.

        using (WordprocessingDocument pkgDoc = WordprocessingDocument.Open(fileNameDoc, true))
        {
            int countFields = 0;
            Body body = pkgDoc.MainDocumentPart.Document.Body;
            FieldChar[] fieldchars = (FieldChar[]) body.Descendants<FieldChar>().ToArray();
            foreach (FieldChar fc in fieldchars)
            {
                fc.FieldLock = true;
                countFields++;
            }
            System.Diagnostics.Debug.Print(countFields.ToString() + " fields locked");
    
        }