简体   繁体   中英

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.

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");

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM