Skip to content

add "Restrict Editing" method to public API #1641

Open

Description

@nikristovski1

It would be useful to support Word's document protection features, such as Restrict Editing → No Changes (Read Only).

Currently, enabling document protection requires manually modifying the underlying Open XML contained within the DOCX file. This involves extracting the document package, updating word/settings.xml to add a w:documentProtection element, and then rebuilding the DOCX archive.

While this approach works, it requires low-level knowledge of the DOCX format and direct XML manipulation. A high-level API would make it significantly easier to create documents that can be viewed and printed but are protected against accidental modification.

Possible API examples:

document.protection.read_only = True

or

document.protection.restrict_editing()

This would provide a more convenient and discoverable way to configure document protection without requiring users to work directly with Open XML internals.

Activity

  1. bactiar291 commented on Dec 4, 2026

    @bactiar291

    For a new document created with python-docx's default template, this low-level workaround sets the read-only OOXML flag without manually extracting/repacking the DOCX archive:

    from docx import Document
    from docx.oxml import OxmlElement
    from docx.oxml.ns import qn
    
    def restrict_read_only(document):
        settings = document.settings._element
        protection = settings.find(qn("w:documentProtection"))
        if protection is None:
            protection = OxmlElement("w:documentProtection")
            settings.insert_element_before(protection, "w:defaultTabStop")
        protection.set(qn("w:edit"), "readOnly")
        protection.set(qn("w:enforcement"), "1")
    
    doc = Document()
    restrict_read_only(doc)
    doc.save("read-only.docx")

    I tested this with python-docx 1.2.0: the element and both attributes survive save/reopen, and calling the helper twice does not add a duplicate. This uses private XML internals and the default template's settings order; a public API would still be preferable. I verified the package round-trip, but not the editing UI behavior in Word/LibreOffice. Microsoft's Open XML reference says document protection is intended to prevent unintentional changes, not to encrypt or secure the file: https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing.documentprotection?view=openxml-3.0.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions