Skip to main content
You are viewing help content for pre-release software. This document and the features it describes are subject to change.
All docs
V26.2
  • Safer Document Processing

    • 9 minutes to read

    Documents from untrusted sources can contain content that requires excessive memory or processing time to load (for example, many paragraphs, large tables, or deeply nested XML elements). Documents can also contain unsafe content (for example, macros, DDE fields, and links to external resources) or hidden data that you do not want to share.

    The Word Processing Document API allows you to process these documents in the following ways:

    Task API
    Limit resources that a load operation consumes LoadOptions.SecurityLoadingLimits
    Remove unsafe content when you load a document LoadOptions.SecurityLoadingOptions
    Log security violations or continue a load operation LoadOptions.SecurityLoadingHandler
    Detect metadata, comments, tracked changes, macros, and hidden content in a loaded document WordDocument.Inspect()
    Remove detected content, process tracked changes, or make hidden content visible WordDocument.Sanitize()

    Limit Resources of a Load Operation

    Use the LoadOptions.SecurityLoadingLimits property to specify security limits for a document load operation. The DocumentSecurityLoadingLimits class contains the following limits:

    Property Description
    MaxFileSize Gets or sets the maximum size of a loaded file in bytes.
    MaxXmlElementDepth Gets or sets the maximum nesting depth of XML elements in each XML file of a loaded document.
    MaxXmlElementCount Gets or sets the maximum number of XML elements in each XML file of a loaded document.
    MaxSectionsCount Gets or sets the maximum number of sections in a loaded document.
    MaxParagraphCount Gets or sets the maximum number of paragraphs in a loaded document.
    MaxTableCount Gets or sets the maximum number of tables in a loaded document.
    MaxTableRowCount Gets or sets the maximum number of rows in each table of a loaded document.
    MaxSubDocumentCount Gets or sets the maximum number of sub-documents in a loaded document.

    If a property is set to null, the corresponding limit does not apply.

    If a loaded document exceeds a limit specified by a DocumentSecurityLoadingLimits property, WordDocument(stream, options) and WordDocument(buffer, options) constructors throw a SecurityLoadingLimitExceededException. To log the violation and continue loading, assign an ISecurityLoadingHandler implementation to the LoadOptions.SecurityLoadingHandler property.

    Remove Unsafe Content When You Load a Document

    Use the LoadOptions.SecurityLoadingOptions property to specify content that the API removes when it loads a document. The DocumentSecurityLoadingOptions class contains the following settings:

    Property Description
    RemoveMacros Gets or sets whether to remove macros from a loaded document.
    RemoveActiveXContent Gets or sets whether to remove ActiveX controls from a loaded document.
    RemoveOleObjects Gets or sets whether to remove embedded OLE objects from a loaded document.
    RemoveCustomXMLParts Gets or sets whether to remove custom XML parts from a loaded document.
    RemoveExternalImages Gets or sets whether to remove references to external images from a loaded document.
    RestrictedHyperlinkRemovalMode Gets or sets how the API processes restricted hyperlinks in a loaded document.
    RemoveDDEFields Gets or sets whether to remove DDE fields from a loaded document.
    RemoveIncludePictureFields Gets or sets whether to remove INCLUDEPICTURE fields from a loaded document.

    The following code snippet limits the file size and the number of tables and table rows, removes macros, DDE fields, and INCLUDEPICTURE fields, and loads a document:

    using System.IO;
    using DevExpress.Docs.Word;
    
    var loadOptions = new LoadOptions {
        SecurityLoadingLimits = new DocumentSecurityLoadingLimits {
            MaxFileSize = 10 * 1024 * 1024,
            MaxTableCount = 100,
            MaxTableRowCount = 1000
        },
        SecurityLoadingOptions = new DocumentSecurityLoadingOptions {
            RemoveMacros = true,
            RemoveDDEFields = true,
            RemoveIncludePictureFields = true
        }
    };
    
    using var stream = File.OpenRead("Document.docx");
    using var document = new WordDocument(stream, loadOptions);
    
    // Process the document.
    

    Handle Security Violations

    To log security violations, load documents that exceed a limit, or keep content that a security loading option detects, implement the ISecurityLoadingHandler interface. Assign the implementation to the LoadOptions.SecurityLoadingHandler property.

    The API calls the following methods of the ISecurityLoadingHandler implementation:

    Method Call Condition Return Value
    HandleLimitExceeded The document exceeds a limit specified by the SecurityLoadingLimits property. SecurityLimitAction.Continue loads the entire document. SecurityLimitAction.Throw stops the load operation and throws a SecurityLoadingLimitExceededException.
    HandleOptionsViolation The document contains content that the SecurityLoadingOptions property specifies. SecurityViolationAction.Remove removes content. SecurityViolationAction.Keep keeps content.

    The API calls the HandleLimitExceeded method once for each exceeded document limit (for example, MaxParagraphCount or MaxTableCount). For the MaxTableRowCount limit, the API calls the HandleLimitExceeded method once for each table that exceeds the limit.

    The API calls the HandleOptionsViolation method once for each option that detects content and applies the returned action to all content that the option detects. The PropertyName property of the parameters argument gets the name of the limit or option (for example, MaxTableRowCount or RemoveDDEFields).

    The following code snippet logs security violations to the console, loads the entire document if the document exceeds a limit, and removes detected DDE fields:

    using System;
    using System.IO;
    using DevExpress.Docs.Office;
    using DevExpress.Docs.Word;
    
    var loadOptions = new LoadOptions {
        SecurityLoadingLimits = new DocumentSecurityLoadingLimits { MaxTableRowCount = 100 },
        SecurityLoadingOptions = new DocumentSecurityLoadingOptions { RemoveDDEFields = true },
        SecurityLoadingHandler = new SecurityViolationLogger()
    };
    
    using var stream = File.OpenRead("Document.docx");
    using var document = new WordDocument(stream, loadOptions);
    
    class SecurityViolationLogger : ISecurityLoadingHandler {
        public SecurityLimitAction HandleLimitExceeded(SecurityLimitExceededParams parameters) {
            Console.WriteLine($"Limit exceeded: {parameters.PropertyName}");
            return SecurityLimitAction.Continue;
        }
        public SecurityViolationAction HandleOptionsViolation(SecurityOptionsViolationParams parameters) {
            Console.WriteLine($"Content removed: {parameters.PropertyName}");
            return SecurityViolationAction.Remove;
        }
    }
    

    Inspect a Document

    Before you share or archive a document, call the WordDocument.Inspect method to detect content that can pose security or privacy risks. The DocumentInspectResult.ContentTypes property gets detected content types (DocumentContentType).

    The parameterless Inspect method detects all supported content types. To inspect specific content types, pass a combination of DocumentInspectOptions flags to the WordDocument.Inspect(options) method.

    Note

    The Inspect method does not modify a document. To remove detected content, pass the result of the DocumentInspectResult.CreateSanitizeOptions() method to the WordDocument.Sanitize(options) method.

    A new document stores the creation date and application information (Application and Version document properties). The Inspect method reports this information as DocumentContentType.DocumentHistory and DocumentContentType.ExtendedProperty.

    The following code snippet inspects a document, displays detected content types in the console, removes the detected content, and saves the document:

    using System;
    using System.IO;
    using DevExpress.Docs.Word;
    
    Directory.CreateDirectory("output");
    
    using var inputStream = File.OpenRead("Document.docx");
    using var document = new WordDocument(inputStream);
    var inspectResult = document.Inspect();
    foreach (var contentType in inspectResult.ContentTypes)
        Console.WriteLine($"Detected: {contentType}");
    
    // Remove the detected content.
    var sanitizeOptions = inspectResult.CreateSanitizeOptions();
    foreach (var result in document.Sanitize(sanitizeOptions))
        Console.WriteLine($"{result.Type}: {result.Action}");
    
    using var outputStream = File.Create(Path.Combine("output", "Document.docx"));
    document.Save(outputStream, DocumentFormat.Docx);
    

    Sanitize a Document

    Call the WordDocument.Sanitize method to remove unsafe and sensitive content from a loaded document.

    The parameterless Sanitize method processes the following content:

    • Removes document properties (metadata) and custom XML parts
    • Removes comments
    • Removes macros, ActiveX controls, and embedded OLE objects
    • Rejects tracked changes
    • Removes hidden text and invisible text (text that has the same color as the background)

    To keep specific content, accept tracked changes, or make hidden content visible, pass a DocumentSanitizeOptions object to the WordDocument.Sanitize(options) method:

    Property Description
    Metadata Gets or sets metadata categories that the API removes when it sanitizes a document.
    RemoveComments Gets or sets whether to remove comments when the API sanitizes a document.
    RemoveCustomXmlParts Gets or sets whether to remove custom XML parts when the API sanitizes a document.
    RemoveActiveXContent Gets or sets whether to remove ActiveX controls when the API sanitizes a document.
    RemoveMacros Gets or sets whether to remove macros when the API sanitizes a document.
    RemoveOleObjects Gets or sets whether to remove embedded OLE objects when the API sanitizes a document.
    TrackedChanges Gets or sets how the API processes tracked changes when it sanitizes a document.
    HiddenText Gets or sets how the API processes hidden text when it sanitizes a document.
    InvisibleText Gets or sets how the API processes text that has the same color as the background.

    The Metadata property does not remove custom XML parts. To remove custom XML parts, use the RemoveCustomXmlParts property.

    The Sanitize method returns a list that contains one DocumentSanitizeResult item for each processed content type, regardless of the number of processed objects. If the document does not contain content of a specific type, the list does not contain an item for the type.

    If the Sanitize method modifies document content (for example, removes comments or hidden text), document elements that you obtained before the call (for example, Paragraph objects) are no longer associated with the document. Get the elements from the document again after the call.

    The following code snippet removes author and organization information and comments, accepts tracked changes, makes hidden text visible, and keeps other document content:

    using System;
    using System.IO;
    using DevExpress.Docs.Office;
    using DevExpress.Docs.Word;
    
    Directory.CreateDirectory("output");
    
    using var inputStream = File.OpenRead("Document.docx");
    using var document = new WordDocument(inputStream);
    
    var sanitizeOptions = new DocumentSanitizeOptions {
        Metadata = MetadataRemovalScope.AuthorInfo | MetadataRemovalScope.OrganizationInfo,
        RemoveComments = true,
        RemoveCustomXmlParts = false,
        RemoveActiveXContent = false,
        RemoveMacros = false,
        RemoveOleObjects = false,
        TrackedChanges = TrackedChangesSanitizeMode.Accept,
        HiddenText = HiddenContentSanitizeMode.MakeVisible,
        InvisibleText = InvisibleContentSanitizeMode.Ignore
    };
    foreach (var result in document.Sanitize(sanitizeOptions))
        Console.WriteLine($"{result.Type}: {result.Action}");
    
    using var outputStream = File.Create(Path.Combine("output", "Document.docx"));
    document.Save(outputStream, DocumentFormat.Docx);
    

    Next Steps