TX Text Control .NET Server

Events

Topic

On a server, no user clicks or types, so the events of ServerTextControl report what happens to the document itself: which tables, images and tracked changes a loaded document contains, which fonts had to be replaced and which elements your code removed. Every event is listed below with when it occurs and what its arguments contain, followed by two typical uses.

Events of a mail merge are described in Overview of Mail Merge and Reporting, and the JavaScript events of the browser components in Events of the Document Editor and Events of the Document Viewer.

How Events Work on the Server

You handle an event of ServerTextControl like any .NET event, with a method or a lambda expression added with +=. Three rules help you use them:

  • Attach handlers before loading. Most events occur while a document is loaded, so the handler must be attached before Load is called.
  • Created events report loaded content. For images, text frames, charts, barcodes, drawings and signature fields, the Created event occurs when a document that contains them is loaded, not when your code adds one with the Add method of its collection.
  • Deleted events report removed content. For images, text frames, charts, barcodes, drawings and signature fields, the Deleted event also occurs when your code removes the element with the Remove method of its collection. Inside a Deleted handler, only some properties of the removed element are still valid, as the table below notes.

Document Events

EventOccursArguments
DocumentLoadedWhen a new document has been loadedEventArgs
ContentsResetWhen all text contents have been deleted and all attributes have been reset to the state after initializationEventArgs

Events of Document Elements

Each kind of document element has a Created and a Deleted event. The element is in a property of the event arguments:

ElementEventsArguments and propertyOccurs
TablesTableCreated, TableDeletedTableEventArgs.TableCreated for a table without an ID in a loaded document, not for tables that have an ID. After deletion, only Table.ID is valid
ImagesImageCreated, ImageDeletedImageEventArgs.ImageCreated when a document with images is loaded; deleted also by ImageCollection.Remove
Text framesTextFrameCreated, TextFrameDeletedTextFrameEventArgs.TextFrameCreated for each text frame of a loaded document; deleted also by TextFrameCollection.Remove
ChartsChartCreated, ChartDeletedChartEventArgs.ChartFrameCreated when a document with charts is loaded; deleted by ChartCollection.Remove
BarcodesBarcodeCreated, BarcodeDeletedBarcodeEventArgs.BarcodeFrameCreated when a document with barcodes is loaded; deleted by BarcodeCollection.Remove
DrawingsDrawingCreated, DrawingDeletedDrawingEventArgs.DrawingFrameCreated when a document with drawings is loaded; deleted also by DrawingCollection.Remove
Signature fieldsSignatureFieldCreated, SignatureFieldDeletedSignatureFieldEventArgs.SignatureFieldCreated when a document with signature fields is loaded; deleted also by SignatureFieldCollection.Remove
Tracked changesTrackedChangeCreated, TrackedChangeDeletedTrackedChangeEventArgs.TrackedChangeCreated when a document with tracked changes is loaded; deleted when a change is accepted or rejected. After deletion, ChangeKind, UserName, ChangeTime, HighlightColor and HighlightMode are valid
Subtext partsSubTextPartCreated, SubTextPartDeletedSubTextPartEventArgs.SubTextPartWhen a subtext part has been created or deleted. After deletion, ID, Name, HighlightColor and HighlightMode are valid
Editable regionsEditableRegionCreated, EditableRegionDeletedEditableRegionEventArgs.EditableRegionWhen an editable region has been created or deleted. After deletion, ID, UserName, HighlightColor and HighlightMode are valid
Text fieldsTextFieldCreated, TextFieldDeletedTextFieldEventArgs.TextFieldWhen a text field has been created or deleted. The field can be of any field class, such as an application field, a hypertext link or a form field. After deletion, ID and Name are valid
BookmarksDocumentTargetCreated, DocumentTargetDeletedDocumentTargetEventArgs.DocumentTargetWhen a document target has been created or deleted. After deletion, TargetName, Deleteable, ID and Name are valid
Tables of contentsTableOfContentsCreated, TableOfContentsDeletedTableOfContentsEventArgs.TableOfContentsWhen a table of contents has been created or deleted. After deletion, ID, Name, the structure levels, HasLinks, HasPageNumbers, HasRightAlignedPageNumbers and the highlight settings are valid
CommentsCommentCreated, CommentDeletedCommentEventArgs.CommentedTextWhen text has been commented or a comment has been removed. After deletion, Comment, UserName, CreationTime, ID, HighlightColor and HighlightMode are valid
FootnotesFootnoteCreated, FootnoteDeletedFootnoteEventArgs.FootnoteWhen a footnote has been created or deleted. After deletion, ID, Name, HighlightColor and HighlightMode are valid

The pages of the elements describe how to work with them, for example Tables, Track Changes and Comments.

Font, Proofing and XML Events

EventOccursArguments
AdaptFontFor each font that must be replaced because it isn't supported. Only when FontSettings.AdaptFontEvent is trueAdaptFontEventArgs
SpellCheckTextWhen text has changed and must be checked, if spell checking is enabled and no spell checking component is connectedSpellCheckTextEventArgs
HyphenateWordWhen a word doesn't fit on its line and must be hyphenated, if IsHyphenationEnabled is trueHyphenateWordEventArgs
XmlInvalidWhen a loaded XML document can't be validated with its document type definition (DTD); the document is still loadedXmlErrorEventArgs
XmlNotWellFormedWhen a loaded XML document isn't well-formed; the document isn't loadedXmlErrorEventArgs

XML Documents shows how to load XML files with their DTD and handle both events.

  • AdaptFont. A font must be replaced when a loaded document uses a font that isn't available, when another printer is set with FormattingPrinter or when FontSettings restricts the fonts with EmbeddableFontsOnly or TrueTypeFontsOnly. FontName is the missing font and AdaptedFontName the font that replaces it. Your handler can set another replacement, which must be one of the fonts in SupportedFonts. Creating Documents shows the event in use.
  • SpellCheckText and HyphenateWord are described in Spell Checking and Hyphenation.
  • XML errors. XmlErrorEventArgs contains the Reason of the error and its position: LineNumber, LinePosition and FilePosition, each 0 when the information isn't available.

Collect the Elements of a Loaded Document

Created events give you an inventory of a document while it's loaded. The following program counts the tables without an ID, the images, the text frames and the tracked changes of Documents/sample.docx and lists the fonts that were replaced:

using TXTextControl;

int tablesWithoutId = 0;
int images = 0;
int textFrames = 0;
int trackedChanges = 0;
List<string> replacedFonts = new List<string>();

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    // Attach the handlers before the document is loaded
    tx.TableCreated += (sender, e) => tablesWithoutId++;
    tx.ImageCreated += (sender, e) => images++;
    tx.TextFrameCreated += (sender, e) => textFrames++;
    tx.TrackedChangeCreated += (sender, e) => trackedChanges++;

    tx.FontSettings.AdaptFontEvent = true;
    tx.AdaptFont += (sender, e) => replacedFonts.Add($"{e.FontName} replaced with {e.AdaptedFontName}");

    tx.DocumentLoaded += (sender, e) => Console.WriteLine("Document loaded");

    tx.Load("Documents/sample.docx", StreamType.WordprocessingML);

    Console.WriteLine($"Tables without an ID: {tablesWithoutId}");
    Console.WriteLine($"Images: {images}");
    Console.WriteLine($"Text frames: {textFrames}");
    Console.WriteLine($"Tracked changes: {trackedChanges}");

    foreach (string font in replacedFonts)
    {
        Console.WriteLine(font);
    }
}

The handlers count the elements while Load runs, so the counters are complete when Load returns. A handler can also work with the element it receives, for example the cells of e.Table in TableCreated, as the blog article Import and Manipulate Excel Spreadsheets by Converting Cells into Merge Fields in C# does when it loads a spreadsheet.

React to Removed Elements

Deleted events tell you what your own code removed. The following program accepts all tracked changes of a document and logs each accepted change from the TrackedChangeDeleted event:

using TXTextControl;

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    // Only ChangeKind, UserName, ChangeTime and the highlight settings are valid here
    tx.TrackedChangeDeleted += (sender, e) =>
        Console.WriteLine($"Accepted: {e.TrackedChange.ChangeKind} by {e.TrackedChange.UserName} ({e.TrackedChange.ChangeTime:u})");

    tx.Load("Documents/revised.docx", StreamType.WordprocessingML);

    while (tx.TrackedChanges.Count > 0)
    {
        if (!tx.TrackedChanges.Remove(tx.TrackedChanges[1], true))
        {
            break;
        }
    }

    tx.Save("accepted.docx", StreamType.WordprocessingML);
}

TrackedChangeDeleted occurs when a change is accepted or rejected with TrackedChangeCollection.Remove. The handler reads only the properties that are valid for a removed change.

The On Methods

For most events, ServerTextControl has a protected method that raises it, named after the event with the prefix On, such as OnTableCreated for TableCreated. Each takes the event arguments of its event. The reference lists them with the members of ServerTextControl.