TX Text Control .NET Server

Document Protection

Topic

Some documents may only partly change, such as contracts with a few editable passages or documents reviewed by several people. The Document Editor restricts what users can change with edit modes, the permissions stored in a document, password protection and editable regions, which keep parts of a protected document editable for certain users.

The examples build on the ASP.NET Core tutorial and store documents with the DocumentController of Loading and Saving Documents. Protected forms, in which users only fill out form fields, are described in Form Fields.

How Document Protection Works

Protection combines three things:

  • The edit mode decides whether the text can be changed at all.
  • The document permissions decide what users may still do in a protected document, such as formatting, copying or printing. They are stored in the document.
  • Editable regions are parts of the text that stay editable in a protected document, for everyone or for one user.

The edit mode is a value of EditMode:

ValueEffect
EditThe text can be edited.
ReadAndSelectThe text can be read and selected. The document permissions and the editable regions apply.
ReadOnlyThe text can only be read.
UsePasswordCombined with ReadAndSelect, opens a dialog box in which the user sets a password that protects the document.

The permissions and editable regions take effect when the edit mode changes from Edit to ReadAndSelect. With UsePassword, the permissions and the password are saved in the document in encrypted form, and a document protected with a password opens read-only.

Protect a Document With the Ribbon

Users protect documents on the Permissions tab of the ribbon:

  1. In the Restrict Editing group, select the restrictions: Read Only keeps the text from being changed, and Restrict Printing, Restrict Copy and Restrict filling in Form Fields take away these rights. For a form that users fill out, leave Restrict filling in Form Fields cleared. The Restrict Formatting group restricts formatting and formatting styles.
  2. To keep a passage editable, select it and click a user in the Mark Exceptions and set Users group. The Add Users dialog box adds users to the list.
  3. Click Enforce Protection, enter a password in the dialog box, or leave it empty for protection without a password, and confirm with OK.
  4. Save the document, for example in the TX Text Control format.

Permissions tab of the Document Editor with the groups Restrict Formatting, Restrict Editing, Mark Exceptions and set Users and Edit restricted Document, and the Enforce Protection dialog box with an optional password and its confirmation

The blog article Web Document Editor: Using Document Permissions shows these steps.

Mark Editable Regions and Protect From Code

The following view is used by the author of a document. It limits the users of the Add Users dialog box to a list, marks the selected text as editable for one user or for everyone, protects the document with a password and saves it. Replace the content of Views/Home/Index.cshtml:

@using TXTextControl.Web.MVC

@Html.TXTextControl().TextControl(settings => {
    settings.UserNames = new string[] { "Tim Typer" };
}).Render()

<input type="button" onclick="addEditableRegion('Paul Proof')" value="Editable for Paul Proof" />
<input type="button" onclick="addEditableRegion('')" value="Editable for Everyone" />
<input type="button" onclick="protectDocument()" value="Protect" />
<input type="button" onclick="saveToServer()" value="Save" />

<script>
    TXTextControl.addEventListener("textControlLoaded", function () {
        // Offer only these names in the Add Users dialog box of the Permissions tab
        TXTextControl.ribbonPermissionsTab.registeredUserNames = ["Tim Typer", "Paul Proof"];
        TXTextControl.ribbonPermissionsTab.allowAdditionalUserNames = false;

        // Highlight all editable regions
        TXTextControl.setEditableRegionHighlightMode(TXTextControl.HighlightMode.Always);
    });

    function addEditableRegion(userName) {
        TXTextControl.selection.getStart(function (start) {
            TXTextControl.selection.getLength(function (length) {
                if (length === 0) {
                    console.log("Select some text first.");
                    return;
                }

                // An empty user name makes the region editable for everyone
                TXTextControl.editableRegions.add(userName, 1, start + 1, length, function (response) {
                    if (response.addResult !== TXTextControl.AddResult.Successful) {
                        console.log("Region not added: " + response.addResult);
                    }
                }, function (error) {
                    console.log(error.msg);
                });
            });
        });
    }

    function protectDocument() {
        // ReadAndSelect with UsePassword opens a dialog box for the password
        TXTextControl.setEditMode(TXTextControl.EditMode.ReadAndSelect | TXTextControl.EditMode.UsePassword);
    }

    function saveToServer() {
        TXTextControl.saveDocument(TXTextControl.StreamType.InternalUnicodeFormat, function (result) {
            fetch("/Document/Save", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ name: "contract.tx", data: result.data })
            });
        });
    }
</script>

The code works as follows:

Select a passage, click Editable for Paul Proof, then Protect, enter a password and click Save. The project's Documents folder now contains contract.tx.

Before you click Protect, the region is highlighted, and with the input position in it, the Permissions tab shows the user it belongs to:

Letter in the Document Editor with an editable region highlighted in the paragraph text and the Permissions tab, whose user list shows Paul Proof checked for the region at the input position

Regions can overlap, and a region that overlaps or directly follows another one with the same user name and ID is combined with it. The permissions and the password are saved with the TX Text Control format, DOCX, RTF and PDF.

Open a Protected Document

The following view opens the protected document for Paul Proof in the ReadAndSelect edit mode. In the protected document, this user can change only the regions marked for Paul Proof or for everyone. Replace the content of Views/Home/Index.cshtml:

@using TXTextControl.Web.MVC

@Html.TXTextControl().TextControl(settings => {
    settings.UserNames = new string[] { "Paul Proof" };
    settings.EditMode = TXTextControl.Web.EditMode.ReadAndSelect;
}).LoadText("Documents/contract.tx", TXTextControl.Web.StreamType.InternalUnicodeFormat).Render()

<input type="button" onclick="listEditableRegions()" value="List Editable Regions" />
<input type="button" onclick="logProtection()" value="Log Protection" />

<script>
    function listEditableRegions() {
        TXTextControl.getUserNames(function (userNames) {
            TXTextControl.editableRegions.forEach(function (region) {
                region.getUserName(function (userName) {
                    region.getText(function (text) {
                        var editable = !userName || userNames.indexOf(userName) !== -1;
                        console.log((userName ? userName : "Everyone") +
                            (editable ? " (editable for you): " : ": ") + text);
                    });
                });
            });
        });
    }

    function logProtection() {
        var permissions = TXTextControl.documentPermissions;

        TXTextControl.getEditMode(function (editMode) {
            console.log("Protected: " + (editMode !== TXTextControl.EditMode.Edit));
            console.log("Read only: " + permissions.readOnly +
                ", formatting: " + permissions.allowFormatting +
                ", form fields: " + permissions.allowEditingFormFields);
        });

        TXTextControl.getCanPrint(function (canPrint) {
            console.log("Can print: " + canPrint);
        });
    }
</script>

In a plain JavaScript page, pass the edit mode and the user names to TXTextControl.init instead, as editMode and userNames of the DocumentEditorSettings.

To remove the protection, the edit mode is set back to Edit, and the user has to enter the same password.

The Document Permissions

PropertyAllows
readOnlyWhen true, neither the text nor its formatting can be changed
allowFormatting, allowFormattingStylesFormatting text, and formatting it with styles
allowCopyCopying content
allowPrintingPrinting the document
allowEditingFormFieldsFilling out form fields

Set the permissions with the Restrict Editing group of the ribbon. Your code reads the result in the protected document with the methods that consider both the permissions and the edit mode:

Use these methods to enable or disable buttons of your own application.

Work With Editable Regions

  • EditableRegionCollection.getItems passes an array of the regions at the input position, or null if there is none.
  • remove removes a region but not its text. With true as the second parameter, it removes only the selected part of the region, which can split the region in two.
  • An EditableRegion has methods for its user name, ID, text, position and highlighting, save to save its content and scrollTo to move the input position to it.

The editor raises editableRegionCreated and editableRegionDeleted when a region is added or deleted, and editableRegionEntered and editableRegionLeft when the input position moves into or out of a region. The handlers receive EditableRegionEventArgs. Events lists all events.

To save a document without its editable regions, pass EditableRegions from OmittedContent in SaveSettings.omittedContent. The text and its formatting are kept.

Passwords of PDF Documents

The protection described on this page is part of the document and applies in the editor. PDF documents have their own passwords and access permissions, which are set when a document is saved as PDF: userPassword, masterPassword and documentAccessPermissions of the save settings. Create a PDF describes them.

The blog article Document Protection in ASP.NET with TX Text Control: Healthcare Use Cases combines editable regions and users in an ASP.NET Core application.

Next Steps