Events
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
Loadis 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
Addmethod 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
Removemethod of its collection. Inside a Deleted handler, only some properties of the removed element are still valid, as the table below notes.
Document Events
| Event | Occurs | Arguments |
|---|---|---|
| DocumentLoaded | When a new document has been loaded | EventArgs |
| ContentsReset | When all text contents have been deleted and all attributes have been reset to the state after initialization | EventArgs |
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:
| Element | Events | Arguments and property | Occurs |
|---|---|---|---|
| Tables | TableCreated, TableDeleted | TableEventArgs.Table | Created for a table without an ID in a loaded document, not for tables that have an ID. After deletion, only Table.ID is valid |
| Images | ImageCreated, ImageDeleted | ImageEventArgs.Image | Created when a document with images is loaded; deleted also by ImageCollection.Remove |
| Text frames | TextFrameCreated, TextFrameDeleted | TextFrameEventArgs.TextFrame | Created for each text frame of a loaded document; deleted also by TextFrameCollection.Remove |
| Charts | ChartCreated, ChartDeleted | ChartEventArgs.ChartFrame | Created when a document with charts is loaded; deleted by ChartCollection.Remove |
| Barcodes | BarcodeCreated, BarcodeDeleted | BarcodeEventArgs.BarcodeFrame | Created when a document with barcodes is loaded; deleted by BarcodeCollection.Remove |
| Drawings | DrawingCreated, DrawingDeleted | DrawingEventArgs.DrawingFrame | Created when a document with drawings is loaded; deleted also by DrawingCollection.Remove |
| Signature fields | SignatureFieldCreated, SignatureFieldDeleted | SignatureFieldEventArgs.SignatureField | Created when a document with signature fields is loaded; deleted also by SignatureFieldCollection.Remove |
| Tracked changes | TrackedChangeCreated, TrackedChangeDeleted | TrackedChangeEventArgs.TrackedChange | Created 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 parts | SubTextPartCreated, SubTextPartDeleted | SubTextPartEventArgs.SubTextPart | When a subtext part has been created or deleted. After deletion, ID, Name, HighlightColor and HighlightMode are valid |
| Editable regions | EditableRegionCreated, EditableRegionDeleted | EditableRegionEventArgs.EditableRegion | When an editable region has been created or deleted. After deletion, ID, UserName, HighlightColor and HighlightMode are valid |
| Text fields | TextFieldCreated, TextFieldDeleted | TextFieldEventArgs.TextField | When 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 |
| Bookmarks | DocumentTargetCreated, DocumentTargetDeleted | DocumentTargetEventArgs.DocumentTarget | When a document target has been created or deleted. After deletion, TargetName, Deleteable, ID and Name are valid |
| Tables of contents | TableOfContentsCreated, TableOfContentsDeleted | TableOfContentsEventArgs.TableOfContents | When 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 |
| Comments | CommentCreated, CommentDeleted | CommentEventArgs.CommentedText | When text has been commented or a comment has been removed. After deletion, Comment, UserName, CreationTime, ID, HighlightColor and HighlightMode are valid |
| Footnotes | FootnoteCreated, FootnoteDeleted | FootnoteEventArgs.Footnote | When 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
| Event | Occurs | Arguments |
|---|---|---|
| AdaptFont | For each font that must be replaced because it isn't supported. Only when FontSettings.AdaptFontEvent is true | AdaptFontEventArgs |
| SpellCheckText | When text has changed and must be checked, if spell checking is enabled and no spell checking component is connected | SpellCheckTextEventArgs |
| HyphenateWord | When a word doesn't fit on its line and must be hyphenated, if IsHyphenationEnabled is true | HyphenateWordEventArgs |
| XmlInvalid | When a loaded XML document can't be validated with its document type definition (DTD); the document is still loaded | XmlErrorEventArgs |
| XmlNotWellFormed | When a loaded XML document isn't well-formed; the document isn't loaded | XmlErrorEventArgs |
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
FormattingPrinteror when FontSettings restricts the fonts withEmbeddableFontsOnlyorTrueTypeFontsOnly. 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.
XmlErrorEventArgscontains 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.