### Working with FieldStart Node Example
Source: https://reference.aspose.com/words/net/aspose.words.fields/fieldchar
Demonstrates how to create a field, access its start character, and retrieve information about the field using the FieldChar object. This example shows inserting a FieldDate, accessing its start node, and verifying properties like FieldType and IsDirty.
```APIDOC
## Examples
Shows how to work with a FieldStart node.
```csharp
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
FieldDate field = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
field.Format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();
FieldChar fieldStart = field.Start;
Assert.That(fieldStart.FieldType, Is.EqualTo(FieldType.FieldDate));
Assert.That(fieldStart.IsDirty, Is.EqualTo(false));
Assert.That(fieldStart.IsLocked, Is.EqualTo(false));
// Retrieve the facade object which represents the field in the document.
field = (FieldDate)fieldStart.GetField();
Assert.That(field.IsLocked, Is.EqualTo(false));
Assert.That(field.GetFieldCode(), Is.EqualTo(" DATE \\@ \"dddd, MMMM dd, yyyy\""));
// Update the field to show the current date.
field.Update();
```
```
--------------------------------
### Example: Creating, Updating, and Printing Bookmarks
Source: https://reference.aspose.com/words/net/aspose.words/bookmark/bookmarkend
This example shows how to create bookmarks, update their properties, and access their start and end nodes using the BookmarkEnd property.
```APIDOC
## Examples
Shows how to add bookmarks and update their contents.
```csharp
public void CreateUpdateAndPrintBookmarks()
{
// Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
Document doc = CreateDocumentWithBookmarks(3);
BookmarkCollection bookmarks = doc.Range.Bookmarks;
PrintAllBookmarkInfo(bookmarks);
// Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
bookmarks[0].Name = $"{bookmarks[0].Name}_NewName";
bookmarks["MyBookmark_2"].Text = $"Updated text contents of {bookmarks[1].Name}";
// Print all bookmarks again to see updated values.
PrintAllBookmarkInfo(bookmarks);
}
///
/// Create a document with a given number of bookmarks.
///
private static Document CreateDocumentWithBookmarks(int numberOfBookmarks)
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 1; i <= numberOfBookmarks; i++)
{
string bookmarkName = "MyBookmark_" + i;
builder.Write("Text before bookmark.");
builder.StartBookmark(bookmarkName);
builder.Write($"Text inside {bookmarkName}.");
builder.EndBookmark(bookmarkName);
builder.Writeln("Text after bookmark.");
}
return doc;
}
///
/// Use an iterator and a visitor to print info of every bookmark in the collection.
///
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
// Get each bookmark in the collection to accept a visitor that will print its contents.
using (IEnumerator enumerator = bookmarks.GetEnumerator())
{
while (enumerator.MoveNext())
{
Bookmark currentBookmark = enumerator.Current;
if (currentBookmark != null)
{
currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
currentBookmark.BookmarkEnd.Accept(bookmarkVisitor); // Accessing BookmarkEnd here
Console.WriteLine(currentBookmark.BookmarkStart.GetText());
}
}
}
}
///
/// Prints contents of every visited bookmark to the console.
///
public class BookmarkInfoPrinter : DocumentVisitor
{
public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
{
Console.WriteLine($"BookmarkStart name: \"{bookmarkStart.Name}\", Contents: \"{bookmarkStart.Bookmark.Text}\"");
return VisitorAction.Continue;
}
public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
{
Console.WriteLine($"BookmarkEnd name: \"{bookmarkEnd.Name}\"");
return VisitorAction.Continue;
}
}
```
```
--------------------------------
### Accessing BookmarkStart Node
Source: https://reference.aspose.com/words/net/aspose.words/bookmark/bookmarkstart
This example demonstrates how to get the BookmarkStart node for a given bookmark.
```APIDOC
## Bookmark.BookmarkStart Property
Gets the node that represents the start of the bookmark.
```csharp
public BookmarkStart BookmarkStart { get; }
```
### Example Usage
This example shows how to add bookmarks and update their contents, including accessing the BookmarkStart node.
```csharp
public void CreateUpdateAndPrintBookmarks()
{
// Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
Document doc = CreateDocumentWithBookmarks(3);
BookmarkCollection bookmarks = doc.Range.Bookmarks;
PrintAllBookmarkInfo(bookmarks);
// Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
bookmarks[0].Name = $"{bookmarks[0].Name}_NewName";
bookmarks["MyBookmark_2"].Text = $"Updated text contents of {bookmarks[1].Name}";
// Print all bookmarks again to see updated values.
PrintAllBookmarkInfo(bookmarks);
}
///
/// Create a document with a given number of bookmarks.
///
private static Document CreateDocumentWithBookmarks(int numberOfBookmarks)
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 1; i <= numberOfBookmarks; i++)
{
string bookmarkName = "MyBookmark_" + i;
builder.Write("Text before bookmark.");
builder.StartBookmark(bookmarkName);
builder.Write($"Text inside {bookmarkName}.");
builder.EndBookmark(bookmarkName);
builder.Writeln("Text after bookmark.");
}
return doc;
}
///
/// Use an iterator and a visitor to print info of every bookmark in the collection.
///
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
// Get each bookmark in the collection to accept a visitor that will print its contents.
using (IEnumerator enumerator = bookmarks.GetEnumerator())
{
while (enumerator.MoveNext())
{
Bookmark currentBookmark = enumerator.Current;
if (currentBookmark != null)
{
currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);
Console.WriteLine(currentBookmark.BookmarkStart.GetText());
}
}
}
}
///
/// Prints contents of every visited bookmark to the console.
///
public class BookmarkInfoPrinter : DocumentVisitor
{
public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
{
Console.WriteLine($"BookmarkStart name: \"{bookmarkStart.Name}\", Contents: \"{bookmarkStart.Bookmark.Text}\");
return VisitorAction.Continue;
}
public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
{
Console.WriteLine($"BookmarkEnd name: \"{bookmarkEnd.Name}\");
return VisitorAction.Continue;
}
}
```
```
--------------------------------
### Working with Bookmarks Example
Source: https://reference.aspose.com/words/net/aspose.words/bookmark
Demonstrates how to create, update, and print bookmarks within an Aspose.Words document. This example covers starting and ending bookmarks, accessing them by index or name, and modifying their text content.
```APIDOC
## Example: Create, Update, and Print Bookmarks
### Description
Shows how to add bookmarks and update their contents.
### Code
```csharp
public void CreateUpdateAndPrintBookmarks()
{
// Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
Document doc = CreateDocumentWithBookmarks(3);
BookmarkCollection bookmarks = doc.Range.Bookmarks;
PrintAllBookmarkInfo(bookmarks);
// Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
bookmarks[0].Name = $"{bookmarks[0].Name}_NewName";
bookmarks["MyBookmark_2"].Text = $"Updated text contents of {bookmarks[1].Name}";
// Print all bookmarks again to see updated values.
PrintAllBookmarkInfo(bookmarks);
}
///
/// Create a document with a given number of bookmarks.
///
private static Document CreateDocumentWithBookmarks(int numberOfBookmarks)
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 1; i <= numberOfBookmarks; i++)
{
string bookmarkName = "MyBookmark_" + i;
builder.Write("Text before bookmark.");
builder.StartBookmark(bookmarkName);
builder.Write($"Text inside {bookmarkName}.");
builder.EndBookmark(bookmarkName);
builder.Writeln("Text after bookmark.");
}
return doc;
}
///
/// Use an iterator and a visitor to print info of every bookmark in the collection.
///
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
// Get each bookmark in the collection to accept a visitor that will print its contents.
using (IEnumerator enumerator = bookmarks.GetEnumerator())
{
while (enumerator.MoveNext())
{
Bookmark currentBookmark = enumerator.Current;
if (currentBookmark != null)
{
currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);
Console.WriteLine(currentBookmark.BookmarkStart.GetText());
}
}
}
}
///
/// Prints contents of every visited bookmark to the console.
///
public class BookmarkInfoPrinter : DocumentVisitor
{
public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
{
Console.WriteLine($"BookmarkStart name: \"{bookmarkStart.Name}\", Contents: \"{bookmarkStart.Bookmark.Text}\"");
return VisitorAction.Continue;
}
public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
{
Console.WriteLine($"BookmarkEnd name: \"{bookmarkEnd.Name}\"");
return VisitorAction.Continue;
}
}
```
```
--------------------------------
### Applying and Reverting Page Setup Settings
Source: https://reference.aspose.com/words/net/aspose.words/pagesetup/verticalalignment
This example demonstrates how to modify page setup properties, specifically vertical alignment and orientation, for sections in a document. It also shows how to revert these settings to their default values using the ClearFormatting method.
```C#
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Modify the page setup properties for the builder's current section and add text.
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center;
builder.Writeln("This is the first section, which landscape oriented with vertically centered text.");
// If we start a new section using a document builder,
it will inherit the builder's current page setup properties.
builder.InsertBreak(BreakType.SectionBreakNewPage);
// We can revert its page setup properties to their default values using the "ClearFormatting" method.
builder.PageSetup.ClearFormatting();
builder.Writeln("This is the second section, which is in default Letter paper size, portrait orientation and top alignment.");
doc.Save(ArtifactsDir + "PageSetup.ClearFormatting.docx");
```
--------------------------------
### Example: Applying AutoFitBehavior.AutoFitToContents
Source: https://reference.aspose.com/words/net/aspose.words.tables/autofitbehavior
Demonstrates how to build a new table and apply the AutoFitToContents behavior.
```APIDOC
## Example: Applying AutoFitBehavior.AutoFitToContents
Shows how to build a new table while applying a style.
```
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
// We must insert at least one row before setting any table formatting.
builder.InsertCell();
// Set the table style used based on the style identifier.
// Note that not all table styles are available when saving to .doc format.
table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1;
// Partially apply the style to features of the table based on predicates, then build the table.
table.StyleOptions =
TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow;
table.AutoFit(AutoFitBehavior.AutoFitToContents);
builder.Writeln("Item");
builder.CellFormat.RightPadding = 40;
builder.InsertCell();
builder.Writeln("Quantity (kg)");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Apples");
builder.InsertCell();
builder.Writeln("20");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Bananas");
builder.InsertCell();
builder.Writeln("40");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Carrots");
builder.InsertCell();
builder.Writeln("50");
builder.EndRow();
doc.Save(ArtifactsDir + "DocumentBuilder.InsertTableWithStyle.docx");
```
```
--------------------------------
### OfficeMath.AcceptStart Method
Source: https://reference.aspose.com/words/net/aspose.words.math/officemath/acceptstart
Accepts a visitor for visiting the start of the office math. This method is part of the visitor pattern implementation in Aspose.Words.
```APIDOC
## OfficeMath.AcceptStart method
### Description
Accepts a visitor for visiting the start of the office math.
### Method Signature
```csharp
public override VisitorAction AcceptStart(DocumentVisitor visitor)
```
### Parameters
* **visitor** (DocumentVisitor) - The document visitor.
### Return Value
The action to be taken by the visitor.
```
--------------------------------
### Get the custom XML data identifier of an XML part
Source: https://reference.aspose.com/words/net/aspose.words.markup/xmlmapping/storeitemid
This example demonstrates how to access the StoreItemId property to get the GUID of a custom XML part associated with a StructuredDocumentTag.
```APIDOC
## Get the custom XML data identifier of an XML part
### Description
Shows how to get the custom XML data identifier of an XML part.
### Method
```csharp
public string StoreItemId { get; }
```
### Parameters
This property does not take any parameters.
### Request Example
```csharp
Document doc = new Document(MyDir + "Custom XML part in structured document tag.docx");
// Structured document tags have IDs in the form of GUIDs.
StructuredDocumentTag tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
Assert.That(tag.XmlMapping.StoreItemId, Is.EqualTo("{F3029283-4FF8-4DD2-9F31-395F19ACEE85}"));
```
```
--------------------------------
### Get Phonetic Guide Properties
Source: https://reference.aspose.com/words/net/aspose.words/phoneticguide/basetext
Demonstrates how to access and retrieve properties of a phonetic guide, including its base text and ruby text, from a document. Ensure the document contains runs with phonetic guides for this example to be effective.
```csharp
Document doc = new Document(MyDir + "Phonetic guide.docx");
RunCollection runs = doc.FirstSection.Body.FirstParagraph.Runs;
// Use phonetic guide in the Asian text.
Assert.That(runs[0].IsPhoneticGuide, Is.EqualTo(true));
Assert.That(runs[0].PhoneticGuide.BaseText, Is.EqualTo("base"));
Assert.That(runs[0].PhoneticGuide.RubyText, Is.EqualTo("ruby"));
```
--------------------------------
### Row.AcceptStart Method
Source: https://reference.aspose.com/words/net/aspose.words.tables/row/acceptstart
Accepts a visitor for visiting the start of the row. The visitor can then perform actions based on the row's starting state.
```APIDOC
## Row.AcceptStart method
### Description
Accepts a visitor for visiting the start of the row.
### Method Signature
```csharp
public override VisitorAction AcceptStart(DocumentVisitor visitor)
```
### Parameters
* **visitor** (DocumentVisitor) - Required - The document visitor.
### Return Value
The action to be taken by the visitor.
### Example
Shows how to print the node structure of every table in a document.
```csharp
Document doc = new Document(MyDir + "DocumentVisitor-compatible features.docx");
TableStructurePrinter visitor = new TableStructurePrinter();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc.Accept(visitor);
Console.WriteLine(visitor.GetText());
```
```
--------------------------------
### Get Match End Node in Aspose.Words
Source: https://reference.aspose.com/words/net/aspose.words.replacing/replacingargs/matchendnode
Demonstrates how to access the MatchEndNode property within a custom IReplacingCallback to retrieve the end node of a match. This example shows how to extract text from both the start and end nodes of a match.
```csharp
[Test]
public void MatchEndNode()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("1");
builder.Writeln("2");
builder.Writeln("3");
ReplacingCallback replacingCallback = new ReplacingCallback();
FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = replacingCallback;
doc.Range.Replace(new Regex("1[\s\S]*3"), "X", options);
Assert.That(replacingCallback.StartNodeText, Is.EqualTo("1"));
Assert.That(replacingCallback.EndNodeText, Is.EqualTo("3"));
}
///
/// The replacing callback.
///
private class ReplacingCallback : IReplacingCallback
{
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
StartNodeText = e.MatchNode.GetText().Trim();
EndNodeText = e.MatchEndNode.GetText().Trim();
return ReplaceAction.Replace;
}
internal string StartNodeText { get; private set; }
internal string EndNodeText { get; private set; }
}
```
--------------------------------
### Initialize License using File - Aspose.Words
Source: https://reference.aspose.com/words/net/aspose.words/license
Shows how to initialize Aspose.Words using a license file from the local file system. The code first determines the correct license file name based on the compilation environment (C++ or .NET) and then sets the license using the file path. It also demonstrates copying the license file to the application's binaries folder and setting the license by just providing the file name, relying on Aspose.Words to find it in local directories.
```C#
#if CPLUSPLUS
string testLicenseFileName = "Aspose.Total.C++.lic";
#else
string testLicenseFileName = "Aspose.Total.NET.lic";
#endif
// Set the license for our Aspose.Words product by passing the local file system filename of a valid license file.
string licenseFileName = Path.Combine(LicenseDir, testLicenseFileName);
License license = new License();
license.SetLicense(licenseFileName);
// Create a copy of our license file in the binaries folder of our application.
string licenseCopyFileName = Path.Combine(AssemblyDir, testLicenseFileName);
File.Copy(licenseFileName, licenseCopyFileName);
// If we pass a file's name without a path,
// the SetLicense will search several local file system locations for this file.
// One of those locations will be the "bin" folder, which contains a copy of our license file.
license.SetLicense(testLicenseFileName);
```
--------------------------------
### License Constructor and SetLicense Method
Source: https://reference.aspose.com/words/net/aspose.words/license/license
Demonstrates how to initialize the License class and apply a license file to Aspose.Words. The example shows setting the license using a local file path and also by relying on the library to find the license file in common locations like the 'bin' folder.
```APIDOC
## License Constructor and SetLicense Method
### Description
Initializes a new instance of the `License` class and demonstrates how to set the license for Aspose.Words using a license file. The `SetLicense` method can accept a file name, and the library will search for the file in several local file system locations, including the 'bin' folder.
### Method Signature
```csharp
public License()
public void SetLicense(string licenseFileName)
```
### Example
```csharp
// Determine the license file name based on the C++ or .NET environment.
#if CPLUSPLUS
string testLicenseFileName = "Aspose.Total.C++.lic";
#else
string testLicenseFileName = "Aspose.Total.NET.lic";
#endif
// Construct the full path to the license file.
string licenseFileName = Path.Combine(LicenseDir, testLicenseFileName);
// Initialize the License object.
License license = new License();
// Set the license using the full file path.
license.SetLicense(licenseFileName);
// Copy the license file to the application's binaries folder for easier access.
string licenseCopyFileName = Path.Combine(AssemblyDir, testLicenseFileName);
File.Copy(licenseFileName, licenseCopyFileName);
// Set the license again, this time relying on the library to find the file in local locations.
license.SetLicense(testLicenseFileName);
```
### See Also
* class License
* namespace Aspose.Words
* assembly Aspose.Words
```
--------------------------------
### Get Properties of Multi-Section Structured Document Tags
Source: https://reference.aspose.com/words/net/aspose.words.markup/istructureddocumenttag/color
This example demonstrates how to retrieve various properties of multi-section structured document tags, including their color. It accesses both the start and end range tags to display their attributes.
```csharp
Document doc = new Document(MyDir + "Multi-section structured document tags.docx");
StructuredDocumentTagRangeStart rangeStartTag =
doc.GetChildNodes(NodeType.StructuredDocumentTagRangeStart, true)[0] as StructuredDocumentTagRangeStart;
StructuredDocumentTagRangeEnd rangeEndTag =
doc.GetChildNodes(NodeType.StructuredDocumentTagRangeEnd, true)[0] as StructuredDocumentTagRangeEnd;
Console.WriteLine("StructuredDocumentTagRangeStart values:");
Console.WriteLine($"\t|Id: {rangeStartTag.Id}");
Console.WriteLine($"\t|Title: {rangeStartTag.Title}");
Console.WriteLine($"\t|PlaceholderName: {rangeStartTag.PlaceholderName}");
Console.WriteLine($"\t|IsShowingPlaceholderText: {rangeStartTag.IsShowingPlaceholderText}");
Console.WriteLine($"\t|LockContentControl: {rangeStartTag.LockContentControl}");
Console.WriteLine($"\t|LockContents: {rangeStartTag.LockContents}");
Console.WriteLine($"\t|Level: {rangeStartTag.Level}");
Console.WriteLine($"\t|NodeType: {rangeStartTag.NodeType}");
Console.WriteLine($"\t|RangeEnd: {rangeStartTag.RangeEnd}");
Console.WriteLine($"\t|Color: {rangeStartTag.Color.ToArgb()}");
Console.WriteLine($"\t|SdtType: {rangeStartTag.SdtType}");
Console.WriteLine($"\t|FlatOpcContent: {rangeStartTag.WordOpenXML}");
Console.WriteLine($"\t|Tag: {rangeStartTag.Tag}
");
Console.WriteLine("StructuredDocumentTagRangeEnd values:");
Console.WriteLine($"\t|Id: {rangeEndTag.Id}");
Console.WriteLine($"\t|NodeType: {rangeEndTag.NodeType}");
```
--------------------------------
### Get Custom XML Data Identifier of an XML Part
Source: https://reference.aspose.com/words/net/aspose.words.markup/xmlmapping/storeitemid
This example demonstrates how to access the StoreItemId property to retrieve the GUID of a custom XML part associated with a StructuredDocumentTag. Ensure the document contains custom XML data within structured document tags.
```csharp
Document doc = new Document(MyDir + "Custom XML part in structured document tag.docx");
// Structured document tags have IDs in the form of GUIDs.
StructuredDocumentTag tag = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);
Assert.That(tag.XmlMapping.StoreItemId, Is.EqualTo("{F3029283-4FF8-4DD2-9F31-395F19ACEE85}"));
```
--------------------------------
### FieldStart.Accept Method
Source: https://reference.aspose.com/words/net/aspose.words.fields/fieldstart/accept
Accepts a visitor. Calls `VisitFieldStart`.
```APIDOC
## FieldStart.Accept method
Accepts a visitor.
```csharp
public override bool Accept(DocumentVisitor visitor)
```
### Parameters
* **visitor** (DocumentVisitor) - The visitor that will visit the node.
### Return Value
**False** if the visitor requested the enumeration to stop.
### Remarks
Calls `VisitFieldStart`.
For more info see the Visitor design pattern.
```
--------------------------------
### Example: Working with VBA References
Source: https://reference.aspose.com/words/net/aspose.words.vba/vbareference/libid
Demonstrates how to retrieve and remove elements from the VBA reference collection, including getting the LibId path.
```APIDOC
## Examples
Shows how to get/remove an element from the VBA reference collection.
```csharp
const string brokenPath = @"X:\broken.dll";
Document doc = new Document(MyDir + "VBA project.docm");
VbaReferenceCollection references = doc.VbaProject.References;
Assert.That(references.Count, Is.EqualTo(5 ));
for (int i = references.Count - 1; i >= 0; i--)
{
VbaReference reference = doc.VbaProject.References[i];
string path = GetLibIdPath(reference);
if (path == brokenPath)
references.RemoveAt(i);
}
Assert.That(references.Count, Is.EqualTo(4 ));
references.Remove(references[1]);
Assert.That(references.Count, Is.EqualTo(3 ));
doc.Save(ArtifactsDir + "VbaProject.RemoveVbaReference.docm");
```
Shows how to get/remove an element from the VBA reference collection (GetLibIdPath).
```csharp
///
/// Returns string representing LibId path of a specified reference.
///
private static string GetLibIdPath(VbaReference reference)
{
switch (reference.Type)
{
case VbaReferenceType.Registered:
case VbaReferenceType.Original:
case VbaReferenceType.Control:
return GetLibIdReferencePath(reference.LibId);
case VbaReferenceType.Project:
return GetLibIdProjectPath(reference.LibId);
default:
throw new ArgumentOutOfRangeException();
}
}
///
/// Returns path from a specified identifier of an Automation type library.
///
private static string GetLibIdReferencePath(string libIdReference)
{
if (libIdReference != null)
{
string[] refParts = libIdReference.Split('#');
if (refParts.Length > 3)
return refParts[3];
}
return "";
}
///
/// Returns path from a specified identifier of an Automation type library.
///
private static string GetLibIdProjectPath(string libIdProject)
{
return libIdProject != null ? libIdProject.Substring(3) : "";
}
```
```
--------------------------------
### Getting Shadow Color Example
Source: https://reference.aspose.com/words/net/aspose.words.drawing/shadowformat
This example demonstrates how to retrieve the shadow color and type from a shape in a document.
```APIDOC
## Examples
Shows how to get shadow color.
```
Document doc = new Document(MyDir + "Shadow color.docx");
Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
ShadowFormat shadowFormat = shape.ShadowFormat;
Assert.That(shadowFormat.Color.ToArgb(), Is.EqualTo(Color.Red.ToArgb()));
Assert.That(shadowFormat.Type, Is.EqualTo(ShadowType.ShadowMixed));
```
```
--------------------------------
### Example: Printing Table Structure
Source: https://reference.aspose.com/words/net/aspose.words.tables/cell/acceptend
This example demonstrates how to use the Accept method with a custom visitor to print the node structure of every table in a document. The AcceptEnd method is implicitly called during the visitor's traversal.
```APIDOC
## Examples
Shows how to print the node structure of every table in a document.
```csharp
Document doc = new Document(MyDir + "DocumentVisitor-compatible features.docx");
TableStructurePrinter visitor = new TableStructurePrinter();
// When we get a composite node to accept a document visitor, the visitor visits the accepting node,
// and then traverses all the node's children in a depth-first manner.
// The visitor can read and modify each visited node.
doc.Accept(visitor);
Console.WriteLine(visitor.GetText());
```
```
--------------------------------
### Working with FieldStart Node
Source: https://reference.aspose.com/words/net/aspose.words.fields/fieldchar/getfield
Demonstrates how to insert a date field, update it, and then retrieve its facade object using GetField. It also shows how to assert properties of the field and its start node.
```csharp
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
FieldDate field = (FieldDate)builder.InsertField(FieldType.FieldDate, true);
field.Format.DateTimeFormat = "dddd, MMMM dd, yyyy";
field.Update();
FieldChar fieldStart = field.Start;
Assert.That(fieldStart.FieldType, Is.EqualTo(FieldType.FieldDate));
Assert.That(fieldStart.IsDirty, Is.EqualTo(false));
Assert.That(fieldStart.IsLocked, Is.EqualTo(false));
// Retrieve the facade object which represents the field in the document.
field = (FieldDate)fieldStart.GetField();
Assert.That(field.IsLocked, Is.EqualTo(false));
Assert.That(field.GetFieldCode(), Is.EqualTo(" DATE \@ \"dddd, MMMM dd, yyyy\""));
// Update the field to show the current date.
field.Update();
```
--------------------------------
### Populate and Format an INDEX Field with Multiple Columns
Source: https://reference.aspose.com/words/net/aspose.words.fields/fieldindex/numberofcolumns
Demonstrates how to create an INDEX field, populate it with entries using XE fields, and configure its appearance, including setting the number of columns. This example shows how to group entries, apply formatting, and control the range of letters included in the index.
```csharp
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Create an INDEX field which will display an entry for each XE field found in the document.
// Each entry will display the XE field's Text property value on the left side,
// and the number of the page that contains the XE field on the right.
// If the XE fields have the same value in their "Text" property,
// the INDEX field will group them into one entry.
FieldIndex index = (FieldIndex)builder.InsertField(FieldType.FieldIndex, true);
index.LanguageId = "1033";
// Setting this property's value to "A" will group all the entries by their first letter,
// and place that letter in uppercase above each group.
index.Heading = "A";
// Set the table created by the INDEX field to span over 2 columns.
index.NumberOfColumns = "2";
// Set any entries with starting letters outside the "a-c" character range to be omitted.
index.LetterRange = "a-c";
Assert.That(index.GetFieldCode(), Is.EqualTo(" INDEX \z 1033 \h A \c 2 \p a-c"));
// These next two XE fields will show up under the "A" heading,
// with their respective text stylings also applied to their page numbers.
builder.InsertBreak(BreakType.PageBreak);
FieldXE indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Apple";
indexEntry.IsItalic = true;
Assert.That(indexEntry.GetFieldCode(), Is.EqualTo(" XE Apple \i"));
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Apricot";
indexEntry.IsBold = true;
Assert.That(indexEntry.GetFieldCode(), Is.EqualTo(" XE Apricot \b"));
// Both the next two XE fields will be under a "B" and "C" heading in the INDEX fields table of contents.
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Banana";
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Cherry";
// INDEX fields sort all entries alphabetically, so this entry will show up under "A" with the other two.
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Avocado";
// This entry will not appear because it starts with the letter "D",
// which is outside the "a-c" character range that the INDEX field's LetterRange property defines.
builder.InsertBreak(BreakType.PageBreak);
indexEntry = (FieldXE)builder.InsertField(FieldType.FieldIndexEntry, true);
indexEntry.Text = "Durian";
doc.UpdatePageLayout();
doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.INDEX.XE.Formatting.docx");
```
--------------------------------
### Iterating Through Nodes and Getting Page Spans
Source: https://reference.aspose.com/words/net/aspose.words.layout/layoutcollector/getstartpageindex
This example demonstrates how to populate a document with content, update its page layout, and then iterate through all nodes to retrieve their starting page, ending page, and total page span using the LayoutCollector. It also shows how to use the LayoutEnumerator to inspect layout entities.
```csharp
Document doc = new Document();
LayoutCollector layoutCollector = new LayoutCollector(doc);
// Call the "GetNumPagesSpanned" method to count how many pages the content of our document spans.
// Since the document is empty, that number of pages is currently zero.
Assert.That(layoutCollector.Document, Is.EqualTo(doc));
Assert.That(layoutCollector.GetNumPagesSpanned(doc), Is.EqualTo(0));
// Populate the document with 5 pages of content.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Section 1");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.SectionBreakEvenPage);
builder.Write("Section 2");
builder.InsertBreak(BreakType.PageBreak);
builder.InsertBreak(BreakType.PageBreak);
// Before the layout collector, we need to call the "UpdatePageLayout" method to give us
// an accurate figure for any layout-related metric, such as the page count.
Assert.That(layoutCollector.GetNumPagesSpanned(doc), Is.EqualTo(0));
layoutCollector.Clear();
doc.UpdatePageLayout();
Assert.That(layoutCollector.GetNumPagesSpanned(doc), Is.EqualTo(5));
// We can see the numbers of the start and end pages of any node and their overall page spans.
NodeCollection nodes = doc.GetChildNodes(NodeType.Any, true);
foreach (Node node in nodes)
{
Console.WriteLine($"-> NodeType.{node.NodeType}: ");
Console.WriteLine(
$"\tStarts on page {layoutCollector.GetStartPageIndex(node)}, ends on page {layoutCollector.GetEndPageIndex(node)}," +
$" spanning {layoutCollector.GetNumPagesSpanned(node)} pages.");
}
// We can iterate over the layout entities using a LayoutEnumerator.
LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);
Assert.That(layoutEnumerator.Type, Is.EqualTo(LayoutEntityType.Page));
// The LayoutEnumerator can traverse the collection of layout entities like a tree.
// We can also apply it to any node's corresponding layout entity.
layoutEnumerator.Current = layoutCollector.GetEntity(doc.GetChild(NodeType.Paragraph, 1, true));
Assert.That(layoutEnumerator.Type, Is.EqualTo(LayoutEntityType.Span));
Assert.That(layoutEnumerator.Text, Is.EqualTo("ΒΆ"));
```
--------------------------------
### Example: Building a Table with Custom Borders and Text Wrapping
Source: https://reference.aspose.com/words/net/aspose.words.tables/cellformat/wraptext
This example demonstrates how to create a table with custom borders and cell formatting, including setting the WrapText property to false for specific cells.
```APIDOC
## Example: Building a Table with Custom Borders and Text Wrapping
Shows how to build a table with custom borders.
```csharp
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartTable();
// Setting table formatting options for a document builder
// will apply them to every row and cell that we add with it.
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.CellFormat.ClearFormatting();
builder.CellFormat.Width = 150;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.CellFormat.Shading.BackgroundPatternColor = Color.GreenYellow;
builder.CellFormat.WrapText = false; // Text wrapping is disabled for this cell
builder.CellFormat.FitText = true;
builder.RowFormat.ClearFormatting();
builder.RowFormat.HeightRule = HeightRule.Exactly;
builder.RowFormat.Height = 50;
builder.RowFormat.Borders.LineStyle = LineStyle.Engrave3D;
builder.RowFormat.Borders.Color = Color.Orange;
builder.InsertCell();
builder.Write("Row 1, Col 1");
builder.InsertCell();
builder.Write("Row 1, Col 2");
builder.EndRow();
// Changing the formatting will apply it to the current cell,
// and any new cells that we create with the builder afterward.
// This will not affect the cells that we have added previously.
builder.CellFormat.Shading.ClearFormatting();
builder.InsertCell();
builder.Write("Row 2, Col 1");
builder.InsertCell();
builder.Write("Row 2, Col 2");
builder.EndRow();
// Increase row height to fit the vertical text.
builder.InsertCell();
builder.RowFormat.Height = 150;
builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Write("Row 3, Col 1");
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Write("Row 3, Col 2");
builder.EndRow();
builder.EndTable();
doc.Save(ArtifactsDir + "DocumentBuilder.InsertTable.docx");
```
```
--------------------------------
### Get the number of form fields
Source: https://reference.aspose.com/words/net/aspose.words.fields/formfieldcollection/count
This example demonstrates how to get the number of form fields in a document using the Count property.
```csharp
Document doc = new Document("YourDocument.docx");
FormFieldCollection formFields = doc.Range.FormFields;
// Get the number of form fields in the document.
int count = formFields.Count;
Console.WriteLine("Number of form fields: " + count);
```
--------------------------------
### Accessing Product and Version Information
Source: https://reference.aspose.com/words/net/aspose.words/buildversioninfo
This example demonstrates how to access and display the product name and version using the static properties of the BuildVersionInfo class.
```APIDOC
## BuildVersionInfo Class
Provides information about the current product name and version.
```csharp
public static class BuildVersionInfo
```
### Properties
* **Product** { get; }
Gets the full name of the product.
* **Version** { get; }
Gets the product version.
### Example
Shows how to display information about your installed version of Aspose.Words.
```csharp
Console.WriteLine($"I am currently using {BuildVersionInfo.Product}, version number {BuildVersionInfo.Version}!");
```
```
--------------------------------
### BookmarkStart Property
Source: https://reference.aspose.com/words/net/aspose.words/bookmark/bookmarkstart
Gets the node that represents the start of the bookmark.
```csharp
public BookmarkStart BookmarkStart { get; }
```
--------------------------------
### Sign a Document with Additional Signing Options
Source: https://reference.aspose.com/words/net/aspose.words.digitalsignatures/signoptions/applicationversion
This example demonstrates how to sign a document using SignOptions, setting properties like WindowsVersion, ApplicationVersion, OfficeVersion, HorizontalResolution, VerticalResolution, and ColorDepth. It then verifies these properties on the signed document.
```csharp
SignOptions signOptions = new SignOptions()
{
WindowsVersion = "10.0",
ApplicationVersion = "16.0.19127",
OfficeVersion = "16.0.19127/27",
HorizontalResolution = 1024,
VerticalResolution = 768,
ColorDepth = 24
};
byte[] certBytes = File.ReadAllBytes(MyDir + "morzal.pfx");
CertificateHolder cert = CertificateHolder.Create(certBytes, "aw");
DigitalSignatureUtil.Sign(MyDir + "Digitally signed.docx", ArtifactsDir + "DigitalSignatureUtil.docx", cert, signOptions);
Document signedDoc = new Document(ArtifactsDir + "DigitalSignatureUtil.docx");
DigitalSignature signature = signedDoc.DigitalSignatures[0];
Assert.That(signedDoc.DigitalSignatures.Count, Is.EqualTo(1));
Assert.That(signature.IsValid, Is.True);
Assert.That(signature.WindowsVersion, Is.EqualTo("10.0"));
Assert.That(signature.ApplicationVersion, Is.EqualTo("16.0.19127"));
Assert.That(signature.OfficeVersion, Is.EqualTo("16.0.19127/27"));
Assert.That(signature.HorizontalResolution, Is.EqualTo(1024));
Assert.That(signature.VerticalResolution, Is.EqualTo(768));
Assert.That(signature.ColorDepth, Is.EqualTo(24));
```
--------------------------------
### Get Font Source Type
Source: https://reference.aspose.com/words/net/aspose.words.fonts/streamfontsource/type
This example demonstrates how to get the type of a font source. The Type property returns a FontSourceType enumeration value.
```csharp
public FontSourceType Type { get; }
```
--------------------------------
### Create and Configure an INCLUDE Field
Source: https://reference.aspose.com/words/net/aspose.words.fields/fieldinclude/lockfields
Demonstrates how to create an INCLUDE field, specify its source document and bookmark, and set the LockFields property. This example also shows how to verify the field code and update fields in the document.
```csharp
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// We can use an INCLUDE field to import a portion of another document in the local file system.
// The bookmark from the other document that we reference with this field contains this imported portion.
FieldInclude field = (FieldInclude)builder.InsertField(FieldType.FieldInclude, true);
field.SourceFullName = MyDir + "Bookmarks.docx";
field.BookmarkName = "MyBookmark1";
field.LockFields = false;
field.TextConverter = "Microsoft Word";
Assert.That(Regex.Match(field.GetFieldCode(), " INCLUDE .* MyBookmark1 \\c \"Microsoft Word\"").Success, Is.True);
doc.UpdateFields();
doc.Save(ArtifactsDir + "Field.INCLUDE.docx");
```
--------------------------------
### Adjusting Page Setup Settings
Source: https://reference.aspose.com/words/net/aspose.words/pagesetup/headerdistance
This example demonstrates how to adjust various page setup settings, including header distance, for a document section.
```APIDOC
## Examples
Shows how to adjust paper size, orientation, margins, along with other settings for a section.
```
CopyDocument doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.PageSetup.PaperSize = PaperSize.Legal;
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.TopMargin = ConvertUtil.InchToPoint(1.0);
builder.PageSetup.BottomMargin = ConvertUtil.InchToPoint(1.0);
builder.PageSetup.LeftMargin = ConvertUtil.InchToPoint(1.5);
builder.PageSetup.RightMargin = ConvertUtil.InchToPoint(1.5);
builder.PageSetup.HeaderDistance = ConvertUtil.InchToPoint(0.2);
builder.PageSetup.FooterDistance = ConvertUtil.InchToPoint(0.2);
builder.Writeln("Hello world!");
doc.Save(ArtifactsDir + "PageSetup.PageMargins.docx");
```
```
--------------------------------
### Table.EnsureMinimum Method Example
Source: https://reference.aspose.com/words/net/aspose.words.tables/table/ensureminimum
This example demonstrates how to use the EnsureMinimum method to prepare a table for content insertion. It shows that before calling EnsureMinimum, a table might have no child nodes, and after calling it, it is guaranteed to have at least one row, one cell, and one paragraph, allowing content like text runs to be appended.
```APIDOC
## Table.EnsureMinimum Method
### Description
If the table has no rows, creates and appends one `Row`.
```csharp
public void EnsureMinimum()
```
### Examples
Shows how to ensure that a table node contains the nodes we need to add content.
```csharp
Document doc = new Document();
Table table = new Table(doc);
doc.FirstSection.Body.AppendChild(table);
// Tables contain rows, which contain cells, which may contain paragraphs
// with typical elements such as runs, shapes, and even other tables.
// Our new table has none of these nodes, and we cannot add contents to it until it does.
Assert.That(table.GetChildNodes(NodeType.Any, true).Count, Is.EqualTo(0));
// Calling the "EnsureMinimum" method on a table will ensure that
// the table has at least one row and one cell with an empty paragraph.
table.EnsureMinimum();
table.FirstRow.FirstCell.FirstParagraph.AppendChild(new Run(doc, "Hello world!"));
```
### See Also
* class Table
* namespace Aspose.Words.Tables
* assembly Aspose.Words
```
--------------------------------
### Helper Methods for Mapped Data Fields Example
Source: https://reference.aspose.com/words/net/aspose.words.mailmerging/mappeddatafieldcollection/clear
Provides helper methods to create a source document with MERGEFIELDs and a data table for the mail merge example. These are necessary setup components for the main example.
```csharp
private static Document CreateSourceDocMappedDataFields()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField(" MERGEFIELD Column1");
builder.Write(", ");
builder.InsertField(" MERGEFIELD Column3");
return doc;
}
private static DataTable CreateSourceTableMappedDataFields()
{
DataTable dataTable = new DataTable("MyTable");
dataTable.Columns.Add("Column1");
dataTable.Columns.Add("Column2");
dataTable.Rows.Add(new object[] { "Value1", "Value2" });
return dataTable;
}
```
--------------------------------
### Create, Update, and Print Bookmarks Example
Source: https://reference.aspose.com/words/net/aspose.words/bookmarkend/name
This example demonstrates how to create a document with bookmarks, access them by index or name, update their names and content, and then print their information.
```APIDOC
## Examples
Shows how to add bookmarks and update their contents.
```csharp
public void CreateUpdateAndPrintBookmarks()
{
// Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
Document doc = CreateDocumentWithBookmarks(3);
BookmarkCollection bookmarks = doc.Range.Bookmarks;
PrintAllBookmarkInfo(bookmarks);
// Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
bookmarks[0].Name = $"{bookmarks[0].Name}_NewName";
bookmarks["MyBookmark_2"].Text = $"Updated text contents of {bookmarks[1].Name}";
// Print all bookmarks again to see updated values.
PrintAllBookmarkInfo(bookmarks);
}
///
/// Create a document with a given number of bookmarks.
///
private static Document CreateDocumentWithBookmarks(int numberOfBookmarks)
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
for (int i = 1; i <= numberOfBookmarks; i++)
{
string bookmarkName = "MyBookmark_" + i;
builder.Write("Text before bookmark.");
builder.StartBookmark(bookmarkName);
builder.Write($"Text inside {bookmarkName}.");
builder.EndBookmark(bookmarkName);
builder.Writeln("Text after bookmark.");
}
return doc;
}
///
/// Use an iterator and a visitor to print info of every bookmark in the collection.
///
private static void PrintAllBookmarkInfo(BookmarkCollection bookmarks)
{
BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
// Get each bookmark in the collection to accept a visitor that will print its contents.
using (IEnumerator enumerator = bookmarks.GetEnumerator())
{
while (enumerator.MoveNext())
{
Bookmark currentBookmark = enumerator.Current;
if (currentBookmark != null)
{
currentBookmark.BookmarkStart.Accept(bookmarkVisitor);
currentBookmark.BookmarkEnd.Accept(bookmarkVisitor);
Console.WriteLine(currentBookmark.BookmarkStart.GetText());
}
}
}
}
///
/// Prints contents of every visited bookmark to the console.
///
public class BookmarkInfoPrinter : DocumentVisitor
{
public override VisitorAction VisitBookmarkStart(BookmarkStart bookmarkStart)
{
Console.WriteLine($"BookmarkStart name: \"{bookmarkStart.Name}\", Contents: \"{bookmarkStart.Bookmark.Text}\"");
return VisitorAction.Continue;
}
public override VisitorAction VisitBookmarkEnd(BookmarkEnd bookmarkEnd)
{
Console.WriteLine($"BookmarkEnd name: \"{bookmarkEnd.Name}\"");
return VisitorAction.Continue;
}
}
```
```
--------------------------------
### Document.AcceptStart Method
Source: https://reference.aspose.com/words/net/aspose.words/document/acceptstart
Accepts a visitor for visiting the start of the document. This method is part of the DocumentVisitor pattern and allows custom logic to be executed when the visitor encounters the beginning of the document.
```APIDOC
## Document.AcceptStart Method
### Description
Accepts a visitor for visiting the start of the document.
### Method Signature
```csharp
public override VisitorAction AcceptStart(DocumentVisitor visitor)
```
### Parameters
#### Path Parameters
- **visitor** (DocumentVisitor) - Required - The document visitor.
```
--------------------------------
### Get and Set Source.Department Property
Source: https://reference.aspose.com/words/net/aspose.words.bibliography/source/department
This property gets or sets the department of a source. It is demonstrated within a larger example of accessing and manipulating bibliography sources.
```csharp
public string Department { get; set; }
```
--------------------------------
### GlossaryDocument.AcceptStart Method
Source: https://reference.aspose.com/words/net/aspose.words.buildingblocks/glossarydocument/acceptstart
Accepts a visitor for visiting the start of the Glossary document.
```APIDOC
## GlossaryDocument.AcceptStart method
### Description
Accepts a visitor for visiting the start of the Glossary document.
### Method Signature
```csharp
public override VisitorAction AcceptStart(DocumentVisitor visitor)
```
### Parameters
#### visitor
- **Type**: DocumentVisitor
- **Description**: The document visitor.
### Return Value
The action to be taken by the visitor.
```